table_name = $wpdb->prefix . 'adminease_notes'; $this->settings = Plugin::get_settings( 'notes' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); if ( empty( $this->settings['sticky_notes_enabled'] ) ) { return; } $this->maybe_upgrade_table(); add_action( 'admin_bar_menu', [ $this, 'admin_bar_menu' ], 999 ); add_action( 'admin_footer', [ $this, 'admin_footer' ] ); add_action( 'wp_ajax_adminease_sticky_notes_list', [ $this, 'ajax_list_notes' ] ); add_action( 'wp_ajax_adminease_sticky_notes_save', [ $this, 'ajax_save_note' ] ); add_action( 'wp_ajax_adminease_sticky_notes_position', [ $this, 'ajax_save_position' ] ); add_action( 'wp_ajax_adminease_sticky_notes_status', [ $this, 'ajax_set_status' ] ); add_action( 'wp_ajax_adminease_sticky_notes_delete', [ $this, 'ajax_delete_note' ] ); } /** * Whether the current user may read and write notes. * * Free limits notes to administrators. Pro widens this to the roles picked in the * settings, so every notes endpoint asks this instead of testing 'manage_options' * directly. * * @return bool True when the current user may use notes. */ public static function current_user_can_use_notes(): bool { return (bool) apply_filters( 'adminease_sticky_notes_user_can', current_user_can( 'manage_options' ) ); } /** * The places the notes button can live. * * @return array Position slug => translated label. */ public static function get_launcher_positions(): array { return [ 'floating' => __( 'Floating button', 'adminease' ), 'admin_bar' => __( 'Admin bar', 'adminease' ), ]; } /** * Adds the Notes settings fields. * * @param array $fields Existing settings fields. * * @return array Modified settings fields. */ public function adminease_settings_fields( array $fields ): array { $fields['notes']['fields'][] = [ 'type' => 'switch', 'id' => 'sticky-notes-enabled', 'name' => 'adminease[notes][sticky_notes_enabled]', 'value' => $this->settings['sticky_notes_enabled'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Sticky Notes', 'adminease' ), 'description' => __( 'Leave post-it notes anywhere in the admin. A pencil button opens a side panel holding the notes for the screen you are on, and every note is listed together on the board below. Turning this off hides the notes button everywhere without deleting a single note.', 'adminease' ), 'child_fields' => [ [ 'type' => 'switch', 'id' => 'sticky-notes-show-pinned', 'name' => 'adminease[notes][sticky_notes_show_pinned]', 'value' => $this->show_pinned() ? 1 : 0, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Show note markers on the page', 'adminease' ), 'field_description' => __( 'Each note also drops a small numbered marker on the screen it was written on. Drag a marker to move it, click it to open that note. Turn this off to keep notes in the side panel and on the board only.', 'adminease' ), 'attributes' => [ 'data-parent' => 'sticky-notes-enabled', ], ], [ 'type' => 'select', 'id' => 'sticky-notes-launcher-position', 'name' => 'adminease[notes][sticky_notes_launcher_position]', 'value' => $this->get_launcher_position(), 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Where the notes button sits', 'adminease' ), 'field_description' => __( 'Keep the button floating in the bottom corner of every screen, or move it up into the admin bar next to your name. If the admin bar is hidden the button goes back to floating on its own.', 'adminease' ), 'options' => self::get_launcher_positions(), 'attributes' => [ 'data-parent' => 'sticky-notes-enabled', ], ], ], ]; return $fields; } /** * Registers the assets used by the notes panel. * * The panel ships on every admin screen, so it stays deliberately small and is the * only thing this feature loads anywhere. * * @return void */ public function admin_enqueue_scripts(): void { if ( empty( $this->settings['sticky_notes_enabled'] ) ) { return; } if ( !self::current_user_can_use_notes() ) { return; } wp_enqueue_style( ADMINEASE_NAME . 'StickyNotes', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseStickyNotes.css', [], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseStickyNotes.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'StickyNotes', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseStickyNotes.js', [ 'jquery' ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseStickyNotes.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'StickyNotes', ADMINEASE_NAME . 'StickyNotesAjaxObj', $this->get_localize_data() ); } /** * Data handed to the panel. * * The 'features' block is what Pro switches on. Every control the panel can draw is * declared here as false so the free build never renders a Pro field, and Pro only * has to flip a flag rather than ship a second copy of the panel. * * @return array The localized script data. */ private function get_localize_data(): array { $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; return apply_filters( 'adminease_sticky_notes_localize', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'adminease_sticky_notes' ), 'enabled' => !empty( $this->settings['sticky_notes_enabled'] ), 'showPinned' => $this->show_pinned(), 'maxLength' => self::MAX_CONTENT_LENGTH, 'currentUser' => get_current_user_id(), 'screen' => [ 'id' => ( null !== $screen ) ? (string) $screen->id : '', 'label' => $this->get_screen_label( $screen ), 'url' => $this->get_current_admin_url(), ], 'features' => [ 'sharing' => false, 'assign' => false, 'due' => false, 'checklist' => false, 'object' => false, ], 'i18n' => [ 'newNote' => esc_html__( 'New note', 'adminease' ), 'showing' => esc_html__( 'Which notes to show', 'adminease' ), 'thisPage' => esc_html__( 'This page', 'adminease' ), 'allNotes' => esc_html__( 'All notes', 'adminease' ), 'searchNotes' => esc_html__( 'Search notes', 'adminease' ), 'noteStatus' => esc_html__( 'Note status', 'adminease' ), 'statusActive' => esc_html__( 'Open', 'adminease' ), 'statusArchived' => esc_html__( 'Done', 'adminease' ), 'statusTrashed' => esc_html__( 'Trash', 'adminease' ), 'hideHere' => esc_html__( 'Hide notes on this screen', 'adminease' ), 'showHere' => esc_html__( 'Show notes on this screen', 'adminease' ), 'notes' => esc_html__( 'Notes', 'adminease' ), 'placeholder' => esc_html__( 'Write your note…', 'adminease' ), 'saving' => esc_html__( 'Saving…', 'adminease' ), 'saved' => esc_html__( 'Saved', 'adminease' ), 'justNow' => esc_html__( 'Edited just now', 'adminease' ), 'markDone' => esc_html__( 'Mark as done', 'adminease' ), 'restore' => esc_html__( 'Restore', 'adminease' ), 'deleteNote' => esc_html__( 'Move to trash', 'adminease' ), 'deleteForever' => esc_html__( 'Delete permanently', 'adminease' ), 'loadMore' => esc_html__( 'Load more', 'adminease' ), 'close' => esc_html__( 'Close', 'adminease' ), 'emptyNote' => esc_html__( 'Empty note', 'adminease' ), 'move' => esc_html__( 'Move', 'adminease' ), 'confirmDelete' => esc_html__( 'Delete this note permanently?', 'adminease' ), 'unsaved' => esc_html__( 'A note has changes that have not been saved yet.', 'adminease' ), /* translators: 1: number of notes on the current screen, 2: number of open notes in the whole site. */ 'badgeTitle' => esc_html__( 'Notes: %1$d here, %2$d in all', 'adminease' ), 'genericError' => esc_html__( 'Something went wrong. Refresh the page and try again.', 'adminease' ), 'loading' => esc_html__( 'Loading notes…', 'adminease' ), 'noNotes' => esc_html__( 'No notes yet.', 'adminease' ), 'noResults' => esc_html__( 'No notes match these filters.', 'adminease' ), 'goToScreen' => esc_html__( 'Go to screen', 'adminease' ), 'somewhereElse' => esc_html__( 'No screen', 'adminease' ), 'by' => esc_html__( 'by', 'adminease' ), 'shared' => esc_html__( 'Shared', 'adminease' ), 'private' => esc_html__( 'Just me', 'adminease' ), 'visibility' => esc_html__( 'Who can see this', 'adminease' ), 'assignedTo' => esc_html__( 'Assigned to', 'adminease' ), 'nobody' => esc_html__( 'Nobody', 'adminease' ), 'dueDate' => esc_html__( 'Due date', 'adminease' ), 'overdue' => esc_html__( 'Overdue', 'adminease' ), 'checklist' => esc_html__( 'Checklist', 'adminease' ), 'addItem' => esc_html__( 'Add an item', 'adminease' ), 'removeItem' => esc_html__( 'Remove item', 'adminease' ), 'attachToThis' => esc_html__( 'Keep this note with this item', 'adminease' ), 'attachedTo' => esc_html__( 'Attached to', 'adminease' ), ], ] ); } /** * Adds the launcher to the admin bar when that is where the user wants it. * * The node is only added inside wp-admin, because the pad's script and stylesheet are * never loaded on the front end and an unstyled button in the toolbar would be worse * than no button at all. * * @param mixed $wp_admin_bar The WP_Admin_Bar instance. * * @return void */ public function admin_bar_menu( $wp_admin_bar ): void { if ( !is_admin() || !is_object( $wp_admin_bar ) ) { return; } if ( 'admin_bar' !== $this->get_launcher_position() || !self::current_user_can_use_notes() ) { return; } $title = ''; $wp_admin_bar->add_node( [ 'id' => 'adminease-notes-launcher', 'parent' => 'top-secondary', 'title' => $title, 'meta' => [ 'class' => 'ae-notes-launcher ae-notes-launcher--bar', ], ] ); $this->launcher_in_admin_bar = true; } /** * Prints the notes layer and, unless the admin bar already carries it, the launcher. * * The layer is left empty on purpose. The panel and the page markers are built into it * by the script, so everything the feature adds to a screen lives inside this one node. * * @return void */ public function admin_footer(): void { if ( !self::current_user_can_use_notes() ) { return; } ?>
launcher_in_admin_bar ) { return; } ?>
settings = $sanitized_settings['notes'] ?? []; if ( !empty( $this->settings['sticky_notes_enabled'] ) ) { $this->create_table(); } } /** * Creates the notes DB table using dbDelta. * * The visibility, assigned_to, due_date, reminder_sent, checklist, object_type and * object_id columns are only ever written by AdminEase Pro. They live in the free * schema so that Pro never has to run a schema change of its own. * * The anchor column holds the element a marker was dropped on, as the selector that * finds it again and the offset from its corner. pos_x and pos_y keep their own * meaning as plain viewport coordinates and are what a marker falls back to when the * element is no longer on the page. * * @return void */ public function create_table(): void { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$this->table_name} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, author_id bigint(20) unsigned NOT NULL DEFAULT 0, content longtext DEFAULT NULL, screen_id varchar(191) NOT NULL DEFAULT '', screen_label varchar(191) NOT NULL DEFAULT '', screen_url varchar(500) NOT NULL DEFAULT '', pos_x int(11) NOT NULL DEFAULT 0, pos_y int(11) NOT NULL DEFAULT 0, anchor varchar(500) NOT NULL DEFAULT '', status varchar(20) NOT NULL DEFAULT 'active', visibility varchar(20) NOT NULL DEFAULT 'private', assigned_to bigint(20) unsigned NOT NULL DEFAULT 0, due_date datetime DEFAULT NULL, reminder_sent tinyint(1) NOT NULL DEFAULT 0, checklist longtext DEFAULT NULL, object_type varchar(32) NOT NULL DEFAULT '', object_id bigint(20) unsigned NOT NULL DEFAULT 0, created_at datetime NOT NULL, updated_at datetime NOT NULL, updated_by bigint(20) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (id), KEY author_id (author_id), KEY screen_id (screen_id), KEY status (status), KEY assigned_to (assigned_to), KEY due_date (due_date), KEY attached_object (object_type,object_id) ) {$charset_collate};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); update_option( self::DB_VERSION_OPTION, self::DB_VERSION ); } /** * Runs the schema through dbDelta when the stored version is behind. * * Gated on an autoloaded option, so the usual request pays nothing for the check. * * @return void */ private function maybe_upgrade_table(): void { if ( self::DB_VERSION === get_option( self::DB_VERSION_OPTION ) ) { return; } $this->create_table(); } // ------------------------------------------------------------------------- // AJAX handlers // ------------------------------------------------------------------------- /** * AJAX: Returns the notes the current user is allowed to see. * * One page of at most LIST_LIMIT notes, taken from 'offset', plus the number of notes * the same filters match in full. The panel has no page numbers - it appends the next * page to the list it already holds - so the count is what tells it there is more to * ask for, and a request without an offset is simply the first page. * * @return void */ public function ajax_list_notes(): void { global $wpdb; if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_sticky_notes' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $this->verify_permissions(); $requested = sanitize_key( wp_unslash( $_POST['status'] ?? '' ) ); $status = in_array( $requested, [ 'archived', 'trashed' ], true ) ? $requested : 'active'; $scope = ( 'screen' === sanitize_key( wp_unslash( $_POST['scope'] ?? '' ) ) ) ? 'screen' : 'board'; $screen_id = isset( $_POST['screen_id'] ) ? sanitize_key( wp_unslash( $_POST['screen_id'] ) ) : ''; $search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : ''; $offset = isset( $_POST['offset'] ) ? absint( wp_unslash( $_POST['offset'] ) ) : 0; $where = $this->get_visibility_where() . ' AND status = %s'; $params = [ $status ]; if ( 'screen' === $scope ) { $where .= ' AND screen_id = %s'; $params[] = $screen_id; } if ( '' !== $search ) { $where .= ' AND content LIKE %s'; $params[] = '%' . $wpdb->esc_like( $search ) . '%'; } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $query = $wpdb->prepare( "SELECT * FROM {$this->table_name} WHERE {$where} ORDER BY updated_at DESC LIMIT %d OFFSET %d", array_merge( $params, [ self::LIST_LIMIT, $offset ] ) ); $count = $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table_name} WHERE {$where}", $params ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table lookup, query prepared above. $rows = $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table aggregate, query prepared above. $total = (int) $wpdb->get_var( $count ); $notes = []; foreach ( (array) $rows as $row ) { $notes[] = $this->prepare_note( $row ); } wp_send_json_success( apply_filters( 'adminease_sticky_notes_list_response', [ 'notes' => $notes, 'total' => $total, 'counts' => $this->get_counts( $screen_id ), ], $scope ) ); } /** * AJAX: Creates a note or updates an existing one. * * @return void */ public function ajax_save_note(): void { global $wpdb; if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_sticky_notes' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $this->verify_permissions(); $note_id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0; $content = isset( $_POST['content'] ) ? $this->trim_content( sanitize_textarea_field( wp_unslash( $_POST['content'] ) ) ) : ''; $user_id = get_current_user_id(); $now = gmdate( 'Y-m-d H:i:s' ); $data = [ 'content' => $content, 'updated_at' => $now, 'updated_by' => $user_id, ]; $formats = [ '%s', '%s', '%d' ]; $extra = (array) apply_filters( 'adminease_sticky_note_save_fields', [ 'data' => [], 'formats' => [] ], $note_id ); $extra_data = is_array( $extra['data'] ?? null ) ? $extra['data'] : []; $extra_formats = is_array( $extra['formats'] ?? null ) ? array_values( $extra['formats'] ) : []; if ( !empty( $extra_data ) && count( $extra_data ) === count( $extra_formats ) ) { $data = array_merge( $data, $extra_data ); $formats = array_merge( $formats, $extra_formats ); } if ( 0 === $note_id ) { $data['author_id'] = $user_id; $data['created_at'] = $now; $data['status'] = 'active'; $data['screen_id'] = isset( $_POST['screen_id'] ) ? sanitize_key( wp_unslash( $_POST['screen_id'] ) ) : ''; $data['screen_label'] = isset( $_POST['screen_label'] ) ? substr( sanitize_text_field( wp_unslash( $_POST['screen_label'] ) ), 0, 190 ) : ''; $data['screen_url'] = $this->sanitize_screen_url( isset( $_POST['screen_url'] ) ? wp_unslash( $_POST['screen_url'] ) : '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized by sanitize_screen_url(). $data['pos_x'] = isset( $_POST['x'] ) ? (int) $_POST['x'] : 0; $data['pos_y'] = isset( $_POST['y'] ) ? (int) $_POST['y'] : 0; $formats = array_merge( $formats, [ '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d' ] ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Writing to the plugin's own table. $inserted = $wpdb->insert( $this->table_name, $data, $formats ); if ( false === $inserted ) { wp_send_json_error( new WP_Error( 'save_failed', __( 'The note could not be saved.', 'adminease' ) ) ); } wp_send_json_success( [ 'note' => $this->get_note( (int) $wpdb->insert_id ) ] ); } $note = $this->get_row( $note_id ); if ( null === $note ) { wp_send_json_error( new WP_Error( 'not_found', __( 'That note no longer exists.', 'adminease' ) ) ); } if ( !$this->user_can_edit( $note ) ) { wp_send_json_error( new WP_Error( 'permissions', __( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Writing to the plugin's own table. $wpdb->update( $this->table_name, $data, [ 'id' => $note_id ], $formats, [ '%d' ] ); wp_send_json_success( [ 'note' => $this->get_note( $note_id ) ] ); } /** * AJAX: Stores where a note's marker was dragged to. * * @return void */ public function ajax_save_position(): void { global $wpdb; if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_sticky_notes' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $this->verify_permissions(); $note_id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0; $note = ( 0 < $note_id ) ? $this->get_row( $note_id ) : null; if ( null === $note ) { wp_send_json_error( new WP_Error( 'not_found', __( 'That note no longer exists.', 'adminease' ) ) ); } if ( !$this->user_can_edit( $note ) ) { wp_send_json_error( new WP_Error( 'permissions', __( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $anchor = $this->sanitize_anchor( sanitize_text_field( wp_unslash( $_POST['anchor'] ?? '' ) ), sanitize_text_field( wp_unslash( $_POST['anchor_frame'] ?? '' ) ), isset( $_POST['anchor_x'] ) ? (int) $_POST['anchor_x'] : 0, isset( $_POST['anchor_y'] ) ? (int) $_POST['anchor_y'] : 0 ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Writing to the plugin's own table. $wpdb->update( $this->table_name, [ 'pos_x' => isset( $_POST['x'] ) ? (int) $_POST['x'] : 0, 'pos_y' => isset( $_POST['y'] ) ? (int) $_POST['y'] : 0, 'anchor' => $anchor, ], [ 'id' => $note_id ], [ '%d', '%d', '%s' ], [ '%d' ] ); wp_send_json_success( [ 'id' => $note_id ] ); } /** * Cleans a selector posted with a marker into the anchor stored beside the note. * * Anything over MAX_ANCHOR_LENGTH, or carrying a character the browser's generated * paths never contain, is dropped rather than trimmed. A half a selector could match * some other element, and a marker with no anchor at all simply falls back to the * plain coordinates, which is the safer of the two outcomes. * * The frame is the iframe the element lives in, for the screens that put their content * in one, the block editor above all. It is empty on every ordinary screen, and an * unusable one takes the whole anchor with it: an element read out of a frame means * nothing without the frame it was read from. * * @param string $selector Selector as posted. * @param string $frame Selector for the iframe the element lives in, or an empty string. * @param int $offset_x Distance from the element's left edge. * @param int $offset_y Distance from the element's top edge. * * @return string The anchor as JSON, or an empty string when there is nothing to store. */ private function sanitize_anchor( string $selector, string $frame, int $offset_x, int $offset_y ): string { $clean_selector = $this->clean_selector( $selector ); $clean_frame = $this->clean_selector( $frame ); if ( '' === $clean_selector ) { return ''; } if ( '' !== trim( $frame ) && '' === $clean_frame ) { return ''; } return (string) wp_json_encode( [ 's' => $clean_selector, 'f' => $clean_frame, 'x' => $offset_x, 'y' => $offset_y, ] ); } /** * Accepts a selector only when it looks like one the browser generated. * * @param string $selector Selector as posted. * * @return string The selector, or an empty string when it is not usable. */ private function clean_selector( string $selector ): string { $selector = trim( $selector ); if ( '' === $selector || self::MAX_ANCHOR_LENGTH < strlen( $selector ) ) { return ''; } if ( 1 !== preg_match( '/^[a-zA-Z0-9 _\-#.\[\]="():>]+$/', $selector ) ) { return ''; } return $selector; } /** * Turns a stored anchor back into the parts a marker is positioned with. * * @param string $stored The anchor column as read from the table. * * @return array|null The selector and its offsets, or null when the note has no anchor. */ private function prepare_anchor( string $stored ): ?array { if ( '' === $stored ) { return null; } $anchor = json_decode( $stored, true ); if ( !is_array( $anchor ) || empty( $anchor['s'] ) ) { return null; } return [ 'selector' => (string) $anchor['s'], 'frame' => isset( $anchor['f'] ) ? (string) $anchor['f'] : '', 'x' => isset( $anchor['x'] ) ? (int) $anchor['x'] : 0, 'y' => isset( $anchor['y'] ) ? (int) $anchor['y'] : 0, ]; } /** * AJAX: Moves a note between the active list and the archive. * * @return void */ public function ajax_set_status(): void { global $wpdb; if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_sticky_notes' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $this->verify_permissions(); $note_id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0; $requested = sanitize_key( wp_unslash( $_POST['status'] ?? '' ) ); $status = in_array( $requested, [ 'archived', 'trashed' ], true ) ? $requested : 'active'; $note = ( 0 < $note_id ) ? $this->get_row( $note_id ) : null; if ( null === $note ) { wp_send_json_error( new WP_Error( 'not_found', __( 'That note no longer exists.', 'adminease' ) ) ); } if ( !$this->user_can_edit( $note ) ) { wp_send_json_error( new WP_Error( 'permissions', __( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Writing to the plugin's own table. $wpdb->update( $this->table_name, [ 'status' => $status, 'updated_at' => gmdate( 'Y-m-d H:i:s' ), 'updated_by' => get_current_user_id(), ], [ 'id' => $note_id ], [ '%s', '%s', '%d' ], [ '%d' ] ); wp_send_json_success( [ 'id' => $note_id, 'status' => $status, 'counts' => $this->get_counts() ] ); } /** * AJAX: Moves a note to the trash, or deletes it for good if it is already there. * * Deleting used to be immediate, guarded by nothing but a browser confirm, which is * the one dialog people are trained to click through. A note is something the user * wrote, so it takes two deliberate deletes to lose one. * * @return void */ public function ajax_delete_note(): void { global $wpdb; if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_sticky_notes' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $this->verify_permissions(); $note_id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0; $note = ( 0 < $note_id ) ? $this->get_row( $note_id ) : null; if ( null === $note ) { wp_send_json_success( [ 'id' => $note_id, 'counts' => $this->get_counts() ] ); } if ( !$this->user_can_edit( $note ) ) { wp_send_json_error( new WP_Error( 'permissions', __( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } if ( 'trashed' !== (string) $note['status'] ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Writing to the plugin's own table. $wpdb->update( $this->table_name, [ 'status' => 'trashed', 'updated_at' => gmdate( 'Y-m-d H:i:s' ), 'updated_by' => get_current_user_id(), ], [ 'id' => $note_id ], [ '%s', '%s', '%d' ], [ '%d' ] ); wp_send_json_success( [ 'id' => $note_id, 'status' => 'trashed', 'counts' => $this->get_counts() ] ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Deleting from the plugin's own table. $wpdb->delete( $this->table_name, [ 'id' => $note_id ], [ '%d' ] ); wp_send_json_success( [ 'id' => $note_id, 'status' => 'deleted', 'counts' => $this->get_counts() ] ); } // ------------------------------------------------------------------------- // Data helpers // ------------------------------------------------------------------------- /** * Stops a request made by a user who may not use notes. * * @return void */ private function verify_permissions(): void { if ( !self::current_user_can_use_notes() ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } } /** * The SQL condition deciding which notes the current user may see. * * Free shows a user their own notes and nothing else. Pro widens this to shared notes * and to notes assigned to the user. A callback MUST return a condition that is already * safe to interpolate - build it with sprintf( '%d' ) on integers, never with raw input. * * @return string An SQL condition, without the WHERE keyword. */ private function get_visibility_where(): string { $user_id = get_current_user_id(); return (string) apply_filters( 'adminease_sticky_notes_visibility_where', sprintf( 'author_id = %d', $user_id ), $user_id ); } /** * Reads one row straight from the table. * * @param int $note_id The note to read. * * @return array|null The row, or null when it does not exist. */ private function get_row( int $note_id ): ?array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table lookup. $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table_name} WHERE id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $note_id ), ARRAY_A ); return empty( $row ) ? null : $row; } /** * Reads one note in the shape the browser expects. * * @param int $note_id The note to read. * * @return array|null The prepared note, or null when it does not exist. */ private function get_note( int $note_id ): ?array { $row = $this->get_row( $note_id ); return ( null === $row ) ? null : $this->prepare_note( $row ); } /** * Turns a table row into the payload the pad and the board render. * * @param array $row A row from the notes table. * * @return array The note as sent to the browser. */ private function prepare_note( array $row ): array { $note = [ 'id' => (int) $row['id'], 'content' => (string) $row['content'], 'screenId' => (string) $row['screen_id'], 'screenLabel' => (string) $row['screen_label'], 'screenUrl' => (string) $row['screen_url'], 'x' => (int) $row['pos_x'], 'y' => (int) $row['pos_y'], 'anchor' => $this->prepare_anchor( (string) ( $row['anchor'] ?? '' ) ), 'status' => (string) $row['status'], 'authorId' => (int) $row['author_id'], 'authorName' => $this->get_user_name( (int) $row['author_id'] ), 'canEdit' => $this->user_can_edit( $row ), 'updatedLabel' => $this->format_updated( (string) $row['updated_at'] ), ]; return apply_filters( 'adminease_sticky_note_response', $note, $row ); } /** * Counts the notes the current user can see, split by status. * * 'screen' is the open notes on one screen rather than a status of its own, and is * only counted when a screen is given: it is what the launcher badge shows, so the * number on the pencil answers "is there anything written about this page" instead * of repeating the same site-wide total everywhere. * * @param string $screen_id Screen to count the open notes of, or an empty string. * * @return array Counts keyed by 'active', 'archived', 'trashed' and 'screen'. */ private function get_counts( string $screen_id = '' ): array { global $wpdb; $where = $this->get_visibility_where(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table aggregate, condition built from integers only. $rows = $wpdb->get_results( "SELECT status, COUNT(*) AS total FROM {$this->table_name} WHERE {$where} GROUP BY status", ARRAY_A ); $counts = [ 'active' => 0, 'archived' => 0, 'trashed' => 0, 'screen' => 0 ]; foreach ( (array) $rows as $row ) { $counts[ (string) $row['status'] ] = (int) $row['total']; } if ( '' !== $screen_id ) { // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $query = $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table_name} WHERE {$where} AND status = 'active' AND screen_id = %s", $screen_id ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table aggregate, query prepared above. $counts['screen'] = (int) $wpdb->get_var( $query ); } return apply_filters( 'adminease_sticky_notes_counts', $counts ); } /** * Whether the current user may change a note. * * @param array $row A row from the notes table. * * @return bool True when the note may be edited. */ private function user_can_edit( array $row ): bool { $can_edit = ( (int) $row['author_id'] === get_current_user_id() ); return (bool) apply_filters( 'adminease_sticky_note_can_edit', $can_edit, $row ); } /** * Builds the "Edited 5 mins ago" line shown at the foot of a note. * * @param string $updated_at A UTC datetime from the table. * * @return string The line to display. */ private function format_updated( string $updated_at ): string { $timestamp = strtotime( $updated_at . ' UTC' ); if ( false === $timestamp ) { return ''; } /* translators: %s: human readable time difference, for example "5 mins". */ return sprintf( esc_html__( 'Edited %s ago', 'adminease' ), human_time_diff( $timestamp, time() ) ); } /** * Resolves a user's display name. * * @param int $user_id The user to look up. * * @return string The display name, or an empty string. */ private function get_user_name( int $user_id ): string { if ( 0 === $user_id ) { return ''; } $user = get_userdata( $user_id ); return ( false === $user ) ? '' : (string) $user->display_name; } /** * Falls back to a readable name for the screen a note was written on. * * @param mixed $screen The current WP_Screen, or null. * * @return string The screen label. */ private function get_screen_label( $screen ): string { $title = isset( $GLOBALS['title'] ) ? (string) $GLOBALS['title'] : ''; if ( '' !== $title ) { return substr( wp_strip_all_tags( $title ), 0, 190 ); } return ( null !== $screen ) ? (string) $screen->id : ''; } /** * The path of the screen currently being viewed, used to link back from the board. * * @return string A root relative admin path, or an empty string. */ private function get_current_admin_url(): string { $uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; return $this->sanitize_screen_url( $uri ); } /** * Keeps only same-site, root relative admin paths. * * A note's link back is rendered as an href, so anything that could point off-site is * dropped rather than stored. * * @param string $url The candidate URL. * * @return string The accepted path, or an empty string. */ private function sanitize_screen_url( string $url ): string { $url = esc_url_raw( $url ); if ( '' === $url || 0 !== strpos( $url, '/' ) || 0 === strpos( $url, '//' ) ) { return ''; } return substr( $url, 0, 500 ); } /** * Caps a note at the maximum stored length. * * @param string $content The submitted note text. * * @return string The note text, shortened when needed. */ private function trim_content( string $content ): string { if ( function_exists( 'mb_substr' ) ) { return mb_substr( $content, 0, self::MAX_CONTENT_LENGTH ); } return substr( $content, 0, self::MAX_CONTENT_LENGTH ); } /** * Where the notes button is drawn. * * @return string A position slug that exists. */ private function get_launcher_position(): string { $position = (string) ( $this->settings['sticky_notes_launcher_position'] ?? '' ); return array_key_exists( $position, self::get_launcher_positions() ) ? $position : 'floating'; } /** * Whether a note draws a marker on the screen it was written on. * * The setting defaults to on, so an installation that has never saved the Notes tab * still gets markers rather than a panel-only experience. * * @return bool True when markers are shown. */ private function show_pinned(): bool { if ( !array_key_exists( 'sticky_notes_show_pinned', $this->settings ) ) { return true; } return !empty( $this->settings['sticky_notes_show_pinned'] ); } }