diff --git a/.github/workflows/pr_verify_linked_issue.yml b/.github/workflows/pr_verify_linked_issue.yml deleted file mode 100755 index 861ecff77..000000000 --- a/.github/workflows/pr_verify_linked_issue.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: Verify PR - -on: - pull_request: - types: [edited, synchronize, opened, reopened] - branches: - - development - check_run: - -jobs: - verify_linked_issue: - runs-on: ubuntu-latest - if: github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' - name: Ensure Pull Request has a linked issue. - steps: - - name: Verify Linked Issue - id: verify_linked_issues - uses: Codeinwp/verify-linked-issue-action@master - env: - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} - with: - quiet: "true" - - name: Find Comment - uses: peter-evans/find-comment@v1 - id: find_coomment - with: - issue-number: ${{ github.event.pull_request.number }} - comment-author: "pirate-bot" - body-includes: No Linked Issue found - - name: Create or update comment - uses: peter-evans/create-or-update-comment@v1 - if: steps.verify_linked_issues.outputs.has_linked_issues != 'true' - with: - comment-id: ${{ steps.find_coomment.outputs.comment-id }} - token: ${{ secrets.BOT_TOKEN }} - issue-number: ${{ github.event.pull_request.number }} - body: | - :guardsman: PR Error! No Linked Issue found. Please link an issue or mention it in the body using # - edit-mode: replace - - name: Fail action on no issue found - if: steps.verify_linked_issues.outputs.has_linked_issues == 'false' - run: exit 1; - - name: Delete comment - uses: winterjung/comment@v1 - if: steps.verify_linked_issues.outputs.has_linked_issues == 'true' && steps.find_coomment.outputs.comment-id != '' - with: - type: delete - comment_id: ${{ steps.find_coomment.outputs.comment-id }} - token: ${{ secrets.BOT_TOKEN }} diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index d195658d2..0a01bb640 100755 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -34,6 +34,9 @@ jobs: run: composer install --no-dev - name: Start wp-env run: npx wp-env start + - name: Install the plugins the tests need + # The afterStart script of .wp-env.json installs them too, but they do not stay on the runner. + run: npx wp-env run tests-cli wp plugin install classic-editor elementor --activate - name: Run the tests run: | npm run test:e2e:playwright diff --git a/classes/Visualizer/Gutenberg/Block.php b/classes/Visualizer/Gutenberg/Block.php index d8acb4904..d5ae3e517 100644 --- a/classes/Visualizer/Gutenberg/Block.php +++ b/classes/Visualizer/Gutenberg/Block.php @@ -330,7 +330,7 @@ public function get_visualizer_data( $post ) { $data['visualizer-data'] = Visualizer_Module::sanitize_chart_data( apply_filters( Visualizer_Plugin::FILTER_GET_CHART_DATA, - Visualizer_Module::decode_content( html_entity_decode( get_post_field( 'post_content', $post_id, 'raw' ) ) ), + Visualizer_Module::can_read_chart_rows( $post_id ) ? Visualizer_Module::decode_content( html_entity_decode( get_post_field( 'post_content', $post_id, 'raw' ) ) ) : array(), $post_id, $data['visualizer-chart-type'] ) @@ -427,6 +427,10 @@ public function get_visualizer_data( $post ) { if ( ! empty( $json_url ) ) { $data['visualizer-json-schedule'] = $json_schedule; $data['visualizer-json-url'] = $json_url; + // The saved credentials stay on the server. + if ( is_array( $json_headers ) ) { + unset( $json_headers['auth'], $json_headers['auth_url'] ); + } $data['visualizer-json-headers'] = $json_headers; $data['visualizer-json-root'] = $json_root; diff --git a/classes/Visualizer/Module.php b/classes/Visualizer/Module.php index d00b2517a..94b1c706b 100644 --- a/classes/Visualizer/Module.php +++ b/classes/Visualizer/Module.php @@ -878,6 +878,61 @@ public static function maybe_decode_content( $value ) { return is_serialized( $value ) ? self::decode_content( $value ) : $value; } + /** + * Tells whether the current user can read the stored rows of a chart. + * + * A post-type chart of the Pro plugin stores post titles and meta values of posts in any status. + * A published chart shows its rows to everyone who can see it. The rows of an unpublished chart are for + * users who can read every post of the type: the post type has an admin screen, and the user can edit + * its posts of other users and read its private posts. This is the rule the Pro plugin has for the query. + * + * @param int $chart_id The chart ID, or the ID of a chart revision. + * @return bool + */ + public static function can_read_chart_rows( $chart_id ) { + if ( self::has_public_rows( $chart_id ) ) { + return true; + } + + $filter_config = get_post_meta( $chart_id, Visualizer_Plugin::CF_FILTER_CONFIG, true ); + $post_type = is_array( $filter_config ) && isset( $filter_config['type'] ) && is_string( $filter_config['type'] ) ? get_post_type_object( $filter_config['type'] ) : null; + return $post_type instanceof WP_Post_Type + && $post_type->show_ui + && current_user_can( $post_type->cap->edit_others_posts ) + && current_user_can( $post_type->cap->read_private_posts ); + } + + /** + * Tells whether everyone who can see a chart can read its stored rows: the chart has no post-type query, or it is published. + * + * @param int $chart_id The chart ID, or the ID of a chart revision. + * @return bool + */ + public static function has_public_rows( $chart_id ) { + $parent_id = wp_is_post_revision( $chart_id ); + return empty( get_post_meta( $chart_id, Visualizer_Plugin::CF_FILTER_CONFIG, true ) ) || 'publish' === get_post_status( $parent_id ? $parent_id : $chart_id ); + } + + /** + * Deletes the saved image of a chart whose rows are not public. + * + * The image shows the rows, and each visitor can read a file in the uploads folder. + * + * @param int $chart_id The chart ID. A revision has no image of its own. + * @return void + */ + public static function delete_image_of_private_rows( $chart_id ) { + if ( wp_is_post_revision( $chart_id ) || self::has_public_rows( $chart_id ) ) { + return; + } + $image_id = self::get_chart_image_id( $chart_id ); + // An image that WordPress did not delete keeps its meta, so a later call finds it. + if ( $image_id && ! wp_delete_attachment( $image_id, true ) ) { + return; + } + delete_post_meta( $chart_id, Visualizer_Plugin::CF_CHART_IMAGE ); + } + /** * Gets the chart content after common manipulations. * @@ -885,9 +940,14 @@ public static function maybe_decode_content( $value ) { * @param string $type The chart type passed to the data filter. * @param bool $run_filter Whether to run the chart data filter. * @param bool $sanitize Whether to prepare the cells for HTML-capable renderers; exports and editors need the stored values. - * @return mixed The chart data. + * @return mixed The chart data; an empty array when the current user cannot read the stored rows. */ public static function get_chart_data( $chart, $type, $run_filter = true, $sanitize = true ) { + // A chart object that is not a saved post has no ID and no saved post-type query. + if ( isset( $chart->ID ) && ! self::can_read_chart_rows( $chart->ID ) ) { + return array(); + } + // change HTML entities $post_content = html_entity_decode( htmlentities( $chart->post_content ) ); $post_content = preg_replace_callback( @@ -924,20 +984,68 @@ function ( $matches ) { return $sanitize ? self::sanitize_chart_data( $altered ) : $altered; } + /** + * Returns the saved credentials of a JSON chart for a request to the endpoint they were saved for. + * + * A user who does not know the credentials can then not send them to another address, or read them + * back from an address that returns its request headers. A save writes that endpoint beside the + * credentials as `auth_url`, so a later change of the chart endpoint does not move them. Headers of an + * older version have no `auth_url`; their credentials belong to the chart endpoint. + * + * @param int $chart_id The chart ID. + * @param string $url The JSON endpoint of the request. + * @return array{username: string, password: string}|string|null The credentials, or null when the chart has none for that endpoint. + */ + public static function get_saved_json_auth( $chart_id, $url ) { + $headers = get_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_HEADERS, true ); + $saved_url = is_array( $headers ) && isset( $headers['auth_url'] ) ? $headers['auth_url'] : get_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_URL, true ); + $saved_url = is_string( $saved_url ) ? trim( $saved_url ) : ''; + if ( ! is_array( $headers ) || empty( $headers['auth'] ) || ! self::is_json_endpoint( $saved_url, $url ) ) { + return null; + } + $auth = $headers['auth']; + if ( is_string( $auth ) || ( is_array( $auth ) && isset( $auth['username'], $auth['password'] ) && is_string( $auth['username'] ) && is_string( $auth['password'] ) ) ) { + return $auth; + } + return null; + } + + /** + * Tells whether a request address is the saved JSON endpoint of a chart. + * + * The chart editor prints the saved endpoint with esc_url(), which encodes some characters, and the browser + * decodes the HTML entities. The form then sends that address, so it counts as the saved endpoint too. + * + * @param string $saved_url The saved JSON endpoint. + * @param string $url The address of the request. + * @return bool + */ + private static function is_json_endpoint( $saved_url, $url ) { + $url = trim( $url ); + return '' !== $saved_url && ( $url === $saved_url || $url === html_entity_decode( esc_url( $saved_url ), ENT_QUOTES ) ); + } + /** * Saves a chart's JSON endpoint, recording the user who changes it as the WooCommerce report user. * * A scheduled refresh of the endpoint then uses this user's report access, - * not the access of whoever authorized an earlier endpoint. + * not the access of whoever authorized an earlier endpoint. Saved credentials belong to the endpoint + * they were saved for, so a new endpoint removes them. * * @param int $chart_id The chart ID. - * @param string $url The JSON endpoint. + * @param string $url The JSON endpoint, with slashes. * @return void */ public static function update_json_url( $chart_id, $url ) { - if ( get_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_URL, true ) !== $url ) { + $saved_url = trim( (string) get_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_URL, true ) ); + if ( $saved_url !== $url ) { update_post_meta( $chart_id, Visualizer_Plugin::CF_WOOCOMMERCE_REPORT_USER, get_current_user_id() ); } + $headers = get_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_HEADERS, true ); + if ( is_array( $headers ) && isset( $headers['auth'] ) && ! self::is_json_endpoint( $saved_url, wp_unslash( $url ) ) ) { + unset( $headers['auth'], $headers['auth_url'] ); + update_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_HEADERS, wp_slash( $headers ) ); + } update_post_meta( $chart_id, Visualizer_Plugin::CF_JSON_URL, $url ); } @@ -962,16 +1070,45 @@ static function ( $value ) { } /** - * Get chart image. + * Returns the name of the file that holds the saved image of a chart. * - * @param object $chart Chart data. + * @param int $chart_id The chart ID. * @return string */ + protected static function chart_image_filename( $chart_id ) { + return 'visualization-' . $chart_id . '.png'; + } + + /** + * Returns the ID of the image that was saved for a chart. + * + * A chart copied by an older version can point to the image of its source chart, also after that image is deleted. + * The file of an image keeps the name it was saved with. WordPress adds a suffix for a name that is in use, for an + * image that a user edits, and for a large image that it scales or rotates. + * + * @param int $chart_id The chart ID. + * @return int The attachment ID, or 0 when the chart has no image of its own. + */ + public static function get_chart_image_id( $chart_id ) { + $attachment_id = (int) get_post_meta( $chart_id, Visualizer_Plugin::CF_CHART_IMAGE, true ); + $saved_name = preg_quote( pathinfo( self::chart_image_filename( $chart_id ), PATHINFO_FILENAME ), '/' ); + if ( $attachment_id && preg_match( '/^' . $saved_name . '(-(\d+|e\d+|scaled|rotated))*\.png\z/', basename( (string) get_attached_file( $attachment_id ) ) ) ) { + return $attachment_id; + } + return 0; + } + + /** + * Get chart image. + * + * @param WP_Post|null $chart The chart post. + * @return array{csv: string} The `csv` value is the image tag of the saved chart image, or an empty string. + */ public function _getImage( $chart = null ) { $image = ''; if ( $chart ) { - $chart_image = get_post_meta( $chart->ID, Visualizer_Plugin::CF_CHART_IMAGE, true ); - if ( ! empty( $chart_image ) ) { + $chart_image = self::get_chart_image_id( $chart->ID ); + if ( $chart_image ) { $image = wp_get_attachment_image( $chart_image, 'full' ); } } diff --git a/classes/Visualizer/Module/Abilities.php b/classes/Visualizer/Module/Abilities.php index 738612725..7952b1dc6 100644 --- a/classes/Visualizer/Module/Abilities.php +++ b/classes/Visualizer/Module/Abilities.php @@ -968,22 +968,14 @@ private function setJsonSource( $chart, $input, $hours, $dry_run ) { $params['paging'] = sanitize_text_field( $input['json_paging'] ); } - // Credentials saved from the chart editor are reused for the same host only; they are never accepted or returned here. - $saved_headers = get_post_meta( $chart->ID, Visualizer_Plugin::CF_JSON_HEADERS, true ); - $saved_url = (string) get_post_meta( $chart->ID, Visualizer_Plugin::CF_JSON_URL, true ); - $auth = array(); - if ( is_array( $saved_headers ) && ! empty( $saved_headers['auth'] ) && '' !== $saved_url && wp_parse_url( $saved_url, PHP_URL_HOST ) === wp_parse_url( $url, PHP_URL_HOST ) && wp_parse_url( $saved_url, PHP_URL_SCHEME ) === wp_parse_url( $url, PHP_URL_SCHEME ) ) { - $auth = $saved_headers['auth']; - if ( is_array( $auth ) && isset( $auth['username'], $auth['password'] ) ) { - $params['username'] = $auth['username']; - $params['password'] = $auth['password']; - } elseif ( is_string( $auth ) ) { - $params['auth'] = $auth; - } - } + // Credentials saved from the chart editor are reused for the same endpoint only; they are never accepted or returned here. + // Each source gets them through setAuth(), because a source prints its parameters to the debug log. + $auth = self::get_saved_json_auth( $chart->ID, $url ); // First pass: discover the keys available under the chosen root. - $probe = $this->fetchSource( new Visualizer_Source_Json( $params ) ); + $probe_source = new Visualizer_Source_Json( $params ); + $probe_source->setAuth( $auth ); + $probe = $this->fetchSource( $probe_source ); if ( is_wp_error( $probe ) ) { return $probe; } @@ -997,7 +989,9 @@ private function setJsonSource( $chart, $input, $hours, $dry_run ) { if ( ! $mapping ) { if ( $dry_run ) { - $roots = ( new Visualizer_Source_Json( $params ) )->fetchRoots(); + $roots_source = new Visualizer_Source_Json( $params ); + $roots_source->setAuth( $auth ); + $roots = $roots_source->fetchRoots(); return array( 'id' => $chart->ID, 'source' => 'json', @@ -1025,6 +1019,7 @@ private function setJsonSource( $chart, $input, $hours, $dry_run ) { } $source = new Visualizer_Source_Json( $params ); + $source->setAuth( $auth ); try { $source->fetchFromEditableTable(); } catch ( Exception $e ) { @@ -1053,7 +1048,9 @@ private function setJsonSource( $chart, $input, $hours, $dry_run ) { $headers = array( 'method' => $params['method'] ); if ( $auth ) { - $headers['auth'] = $auth; + // add_post_meta() removes slashes, and the saved value is already without them. + $headers['auth'] = wp_slash( $auth ); + $headers['auth_url'] = wp_slash( $params['url'] ); } add_post_meta( $chart->ID, Visualizer_Plugin::CF_JSON_HEADERS, $headers ); if ( ! empty( $params['paging'] ) ) { diff --git a/classes/Visualizer/Module/Chart.php b/classes/Visualizer/Module/Chart.php index 34d615ab0..99a6091c0 100644 --- a/classes/Visualizer/Module/Chart.php +++ b/classes/Visualizer/Module/Chart.php @@ -177,9 +177,10 @@ public function getJsonRoots() { wp_send_json_error( array( 'msg' => esc_html__( 'You do not have permission to perform this action.', 'visualizer' ) ) ); } - $params = wp_parse_args( $_POST['params'] ); + $params = wp_parse_args( $_POST['params'] ); $source = new Visualizer_Source_Json( $params ); + $source->setAuth( self::saved_json_auth_for_editor( $params, isset( $params['chart'] ) ? absint( $params['chart'] ) : 0 ) ); $roots = $source->fetchRoots(); if ( empty( $roots ) ) { @@ -213,6 +214,7 @@ public function getJsonData() { } $source = new Visualizer_Source_Json( $params ); + $source->setAuth( self::saved_json_auth_for_editor( $params, absint( $chart_id ) ) ); $source->fetch(); $data = $source->getRawData(); @@ -224,6 +226,24 @@ public function getJsonData() { wp_send_json_success( array( 'table' => $data, 'root' => $params['root'], 'url' => $params['url'], 'paging' => $source->getPaginationElements() ) ); } + /** + * Returns the saved credentials that a JSON request from the chart editor uses. + * + * The chart editor does not show saved credentials, so its forms send empty credential fields for them. + * A request that brings credentials, or asks to remove the saved ones, does not use them. + * + * @param array $params JSON source parameters from the chart editor, with slashes. + * @param int $chart_id The chart ID. + * @return array{username: string, password: string}|string|null The credentials, or null when the request uses none. + */ + private static function saved_json_auth_for_editor( $params, $chart_id ) { + $has_auth_input = ! empty( $params['clear_auth'] ) || ! empty( $params['auth'] ) || ! empty( $params['username'] ) || ! empty( $params['password'] ); + if ( $has_auth_input || empty( $params['url'] ) || ! is_string( $params['url'] ) || ! self::can_edit_chart( $chart_id ) ) { + return null; + } + return self::get_saved_json_auth( $chart_id, wp_unslash( $params['url'] ) ); + } + /** * Updates the database with the correct post parameters for JSON-endpoint charts. * @@ -243,7 +263,11 @@ public function setJsonData() { $chart = get_post( $chart_id ); + // Read the saved credentials before the new endpoint replaces the one they belong to. + $saved_auth = self::saved_json_auth_for_editor( $params, $chart_id ); + $source = new Visualizer_Source_Json( $params ); + $source->setAuth( $saved_auth ); update_post_meta( $chart->ID, Visualizer_Plugin::CF_EDITABLE_TABLE, true ); $source->fetchFromEditableTable(); @@ -262,6 +286,14 @@ public function setJsonData() { $headers['auth'] = $params['auth']; } elseif ( ! empty( $params['username'] ) && ! empty( $params['password'] ) ) { $headers['auth'] = array( 'username' => $params['username'], 'password' => $params['password'] ); + } elseif ( null !== $saved_auth ) { + // add_post_meta() removes slashes, and the saved value is already without them. + $headers['auth'] = wp_slash( $saved_auth ); + } + + if ( isset( $headers['auth'] ) ) { + // The credentials belong to this endpoint. See get_saved_json_auth(). + $headers['auth_url'] = $params['url']; } add_post_meta( $chart->ID, Visualizer_Plugin::CF_JSON_HEADERS, $headers ); @@ -631,8 +663,8 @@ public function renderChartPages() { $post_meta = get_post_meta( $parent_chart_id ); $chart_id = $new_chart_id; foreach ( $post_meta as $key => $value ) { - // A copy refreshes reports with its own author's access. - if ( strpos( $key, 'visualizer-' ) !== false && Visualizer_Plugin::CF_WOOCOMMERCE_REPORT_USER !== $key ) { + // A copy refreshes reports with its own author's access, and it has no image until it is saved. + if ( strpos( $key, 'visualizer-' ) !== false && ! in_array( $key, array( Visualizer_Plugin::CF_WOOCOMMERCE_REPORT_USER, Visualizer_Plugin::CF_CHART_IMAGE ), true ) ) { add_post_meta( $new_chart_id, $key, self::maybe_decode_content( $value[0] ) ); } } @@ -651,7 +683,7 @@ public function renderChartPages() { $_POST['save_chart_image'] = isset( $_POST['save_chart_image'] ) && 'yes' === $_POST['save_chart_image'] ? true : false; $_POST['lazy_load_chart'] = isset( $_POST['lazy_load_chart'] ) && 'yes' === $_POST['lazy_load_chart'] ? true : false; - if ( isset( $_POST['chart-img'] ) && ! empty( $_POST['chart-img'] ) ) { + if ( ! empty( $_POST['chart-img'] ) && isset( $_GET['nonce'] ) && wp_verify_nonce( $_GET['nonce'] ) ) { $attachment_id = $this->save_chart_image( $_POST['chart-img'], $chart_id, $_POST['save_chart_image'] ); if ( $attachment_id ) { update_post_meta( $chart_id, Visualizer_Plugin::CF_CHART_IMAGE, $attachment_id ); @@ -843,6 +875,10 @@ private function _handleDataAndSettingsPage() { if ( isset( $existing['colors'] ) && is_array( $existing['colors'] ) && ! isset( $post_settings['colors'] ) ) { $post_settings['colors'] = $existing['colors']; } + // The sidebar builds the slice fields from the rows, so a user who cannot read the rows posts none. + if ( isset( $existing['slices'] ) && ! isset( $post_settings['slices'] ) && ! self::can_read_chart_rows( $this->_chart->ID ) ) { + $post_settings['slices'] = $existing['slices']; + } $post_settings = $this->sanitizeSettings( $post_settings ); update_post_meta( $this->_chart->ID, Visualizer_Plugin::CF_SETTINGS, $post_settings ); @@ -1313,6 +1349,14 @@ public function uploadData() { do_action( 'themeisle_log_event', Visualizer_Plugin::NAME, sprintf( 'Uploading data for chart %d with POST = %s and GET = %s', $chart_id, print_r( $_POST, true ), print_r( $_GET, true ) ), 'debug', __FILE__, __LINE__ ); + // A new data source removes the post-type query of the chart, and the stored rows stay when it gives no data. + // A user who cannot read those rows does not get them in an editor, so that user cannot replace them or the query. + if ( $can_die && ! self::can_read_chart_rows( $chart_id ) ) { + $render = new Visualizer_Render_Page_Update( array( 'message' => esc_html__( 'You cannot change the data of this chart, because it comes from posts that you cannot read.', 'visualizer' ) ) ); + $render->render(); + ( defined( 'WP_TESTS_DOMAIN' ) && function_exists( 'tests_add_filter' ) ) ? wp_die() : exit(); + } + if ( ! isset( $_POST['vz-import-time'] ) ) { apply_filters( 'visualizer_pro_remove_schedule', $chart_id ); } @@ -1476,8 +1520,8 @@ public function cloneChart() { } else { $post_meta = get_post_meta( $chart_id ); foreach ( $post_meta as $key => $value ) { - // A copy refreshes reports with its own author's access. - if ( strpos( $key, 'visualizer-' ) !== false && Visualizer_Plugin::CF_WOOCOMMERCE_REPORT_USER !== $key ) { + // A copy refreshes reports with its own author's access, and it has no image until it is saved. + if ( strpos( $key, 'visualizer-' ) !== false && ! in_array( $key, array( Visualizer_Plugin::CF_WOOCOMMERCE_REPORT_USER, Visualizer_Plugin::CF_CHART_IMAGE ), true ) ) { add_post_meta( $new_chart_id, $key, self::maybe_decode_content( $value[0] ) ); } } @@ -1748,17 +1792,21 @@ public function saveFilter() { * * @param string $base64_img Chart image. * @param int $chart_id Chart ID. - * @param bool $save_attachment Save attachment. + * @param bool $save_attachment Save attachment. A chart whose rows are not public gets no image. * @return int Attachment ID, or 0 when no attachment was saved. */ public function save_chart_image( $base64_img, $chart_id, $save_attachment = true ) { - // Delete old chart image. - $old_attachment_id = get_post_meta( $chart_id, Visualizer_Plugin::CF_CHART_IMAGE, true ); + $filename = self::chart_image_filename( $chart_id ); + + // Delete the old chart image, but only the image of this chart. + $old_attachment_id = self::get_chart_image_id( $chart_id ); if ( $old_attachment_id ) { wp_delete_attachment( $old_attachment_id, true ); } - if ( ! $save_attachment ) { + if ( ! $save_attachment || ! self::has_public_rows( $chart_id ) ) { + // The chart has no image now. A chart copied by an older version can still point to the image of its source chart. + delete_post_meta( $chart_id, Visualizer_Plugin::CF_CHART_IMAGE ); return 0; } @@ -1773,7 +1821,6 @@ public function save_chart_image( $base64_img, $chart_id, $save_attachment = tru if ( false === $decoded || 0 !== strncmp( $decoded, "\x89PNG\r\n\x1a\n", 8 ) ) { return 0; } - $filename = 'visualization-' . $chart_id . '.png'; $file_type = 'image/png'; $hashed_filename = $filename; diff --git a/classes/Visualizer/Module/Frontend.php b/classes/Visualizer/Module/Frontend.php index 9d589da5f..96b9c9986 100644 --- a/classes/Visualizer/Module/Frontend.php +++ b/classes/Visualizer/Module/Frontend.php @@ -423,7 +423,8 @@ public function renderChart( $atts ) { } if ( 'yes' === $atts['use_image'] ) { - $chart_image = $chart_data['chart_image']; + // Read the image on each render: the cached chart data can outlive the image. + $chart_image = self::get_chart_image_id( $chart->ID ); if ( $chart_image ) { return '
getHtmlAttributes( $attributes ) . '>' . wp_get_attachment_image( $chart_image, 'full' ) . '
'; } @@ -475,9 +476,12 @@ public function renderChart( $atts ) { $key = $array[0]; $mime = end( $array ); } + if ( ! isset( $actions[ $key ] ) ) { + continue; + } $label = $actions[ $key ]['label']; $title = $actions[ $key ]['title']; - $actions_div .= sprintf( '_getDataAs( $atts['id'], 'csv' ); @@ -763,7 +767,6 @@ private function getChartData( $cache_key = '', $chart_id = 0 ) { 'type' => get_post_meta( $chart->ID, Visualizer_Plugin::CF_CHART_TYPE, true ), 'settings' => $settings, 'series' => $series, - 'chart_image' => get_post_meta( $chart->ID, Visualizer_Plugin::CF_CHART_IMAGE, true ), 'is_woocommerce_report' => $is_woocommerce_report, ); diff --git a/classes/Visualizer/Module/Setup.php b/classes/Visualizer/Module/Setup.php index 3f530b358..c8df705f3 100644 --- a/classes/Visualizer/Module/Setup.php +++ b/classes/Visualizer/Module/Setup.php @@ -68,6 +68,15 @@ public function __construct( Visualizer_Plugin $plugin ) { $this->_addAction( 'init', 'maybe_reschedule_refresh_db' ); $this->_addAction( 'action_scheduler_ensure_recurring_actions', 'ensure_refresh_db_action' ); $this->_addFilter( 'visualizer_schedule_refresh_chart', 'refresh_db_for_chart', 10, 3 ); + $this->_addFilter( 'is_protected_meta', 'protect_chart_meta', 10, 3 ); + $this->_addFilter( 'wp_get_revision_ui_diff', 'remove_unreadable_rows_from_revision_diff', 10, 3 ); + $this->_addFilter( Visualizer_Plugin::FILTER_GET_CHART_SETTINGS, 'remove_image_of_unreadable_rows', 10, 2 ); + $this->_addAction( 'transition_post_status', 'delete_image_after_status_change', null, 10, 3 ); + $this->_addFilter( 'xmlrpc_enabled', 'restrict_xmlrpc_to_readable_rows' ); + $this->_addAction( 'added_post_meta', 'delete_image_after_query_change', null, 10, 3 ); + $this->_addAction( 'updated_post_meta', 'delete_image_after_query_change', null, 10, 3 ); + $this->_addFilter( 'map_meta_cap', 'deny_json_headers_meta_caps', 10, 4 ); + $this->_addFilter( 'wxr_export_skip_postmeta', 'skip_json_headers_in_export', 10, 2 ); $this->_addAction( 'admin_init', 'adminInit' ); $this->_addAction( 'init', 'setupCustomPostTypes' ); @@ -311,6 +320,156 @@ public function adminInit() { } + /** + * Removes the chart content from a revision comparison for a user who cannot read the rows of the chart. + * + * WordPress compares the revisions of each post that its user can edit, and the content of a chart is its rows. + * + * @param array $fields The compared fields. + * @param WP_Post|false $compare_from The older revision, or false for none. + * @param WP_Post $compare_to The newer revision, or the post. + * @return array + */ + public function remove_unreadable_rows_from_revision_diff( $fields, $compare_from, $compare_to ) { + $parent_id = wp_is_post_revision( $compare_to ); + if ( Visualizer_Plugin::CPT_VISUALIZER !== get_post_type( $parent_id ? $parent_id : $compare_to ) ) { + return $fields; + } + // The older revision can hold rows of a post-type query that the newer one no longer has. + if ( self::can_read_chart_rows( $compare_to->ID ) && ( ! $compare_from instanceof WP_Post || self::can_read_chart_rows( $compare_from->ID ) ) ) { + return $fields; + } + return array_values( wp_list_filter( $fields, array( 'id' => 'post_content' ), 'NOT' ) ); + } + + /** + * Removes the rendered chart image from the settings for a user who cannot read the rows of the chart. + * + * The chart editor saves a picture of the chart in the `chart-img` setting, and the picture shows the rows. + * + * @param mixed $settings The chart settings. + * @param int $chart_id The chart ID. + * @return mixed + */ + public function remove_image_of_unreadable_rows( $settings, $chart_id ) { + if ( is_array( $settings ) && isset( $settings['chart-img'] ) && ! self::can_read_chart_rows( $chart_id ) ) { + unset( $settings['chart-img'] ); + } + return $settings; + } + + /** + * Applies the rule for the stored rows to an XML-RPC request. + * + * The XML-RPC methods of WordPress return the content of each post that its user can edit, and the content + * of a chart is its rows. No screen of the plugin uses XML-RPC. The XML-RPC server runs this filter when it + * starts, before a method checks what its user can do. + * + * @param bool $is_enabled Whether XML-RPC is enabled. + * @return bool + */ + public function restrict_xmlrpc_to_readable_rows( $is_enabled ) { + $this->_addFilter( 'map_meta_cap', 'deny_chart_with_unreadable_rows', 10, 4 ); + return $is_enabled; + } + + /** + * Refuses a chart, or a chart revision, to a user who cannot read its rows. + * + * @param string[] $caps The primitive capabilities that the user needs. + * @param string $cap The capability that is checked. + * @param int $user_id The user ID. + * @param mixed[] $args The arguments of the check: the post ID comes first. + * @return string[] + */ + public function deny_chart_with_unreadable_rows( $caps, $cap, $user_id, $args ) { + if ( ! in_array( $cap, array( 'edit_post', 'read_post' ), true ) || empty( $args[0] ) ) { + return $caps; + } + $parent_id = wp_is_post_revision( $args[0] ); + if ( Visualizer_Plugin::CPT_VISUALIZER === get_post_type( $parent_id ? $parent_id : $args[0] ) && ! self::can_read_chart_rows( $args[0] ) ) { + $caps[] = 'do_not_allow'; + } + return $caps; + } + + /** + * Deletes the saved image of a chart that is no longer published, when its rows are not public. + * + * @param string $new_status The new status. + * @param string $old_status The old status. + * @param WP_Post $post The post. + * @return void + */ + public function delete_image_after_status_change( $new_status, $old_status, $post ) { + if ( Visualizer_Plugin::CPT_VISUALIZER === $post->post_type ) { + self::delete_image_of_private_rows( $post->ID ); + } + } + + /** + * Deletes the saved image of an unpublished chart that gets a post-type query. + * + * A restored revision brings the query and the image in any order. + * + * @param int $meta_id The meta ID. + * @param int $chart_id The post ID. + * @param string $meta_key The meta key. + * @return void + */ + public function delete_image_after_query_change( $meta_id, $chart_id, $meta_key ) { + if ( in_array( $meta_key, array( Visualizer_Plugin::CF_FILTER_CONFIG, Visualizer_Plugin::CF_CHART_IMAGE ), true ) ) { + self::delete_image_of_private_rows( $chart_id ); + } + } + + /** + * Marks the chart meta as protected. + * + * Chart meta selects the data source and holds its query, URL and credentials. A protected key + * cannot be written through the Custom Fields panel, XML-RPC or the REST API, so only the plugin sets it. + * + * @param bool $is_protected Whether the key is protected. + * @param string $meta_key Meta key. + * @param string $meta_type Type of the object the meta belongs to. + * + * @return bool + */ + public function protect_chart_meta( $is_protected, $meta_key, $meta_type ) { + return $is_protected || ( 'post' === $meta_type && 0 === strpos( (string) $meta_key, 'visualizer-' ) ); + } + + /** + * Refuses the meta capabilities for the JSON headers of a chart, which hold the saved credentials. + * + * A super administrator of a network passes the capability of every other protected key, and XML-RPC + * returns the custom fields that its user can edit. + * + * @param list $caps The primitive capabilities that the user needs. + * @param string $cap The capability that is checked. + * @param int $user_id The user ID. + * @param array $args The arguments of the check: the post ID, then the meta key. + * @return list + */ + public function deny_json_headers_meta_caps( $caps, $cap, $user_id, $args ) { + $is_meta_cap = in_array( $cap, array( 'edit_post_meta', 'add_post_meta', 'delete_post_meta' ), true ); + if ( $is_meta_cap && isset( $args[1] ) && Visualizer_Plugin::CF_JSON_HEADERS === $args[1] ) { + return array( 'do_not_allow' ); + } + return $caps; + } + + /** + * Leaves the JSON headers of a chart, which hold the saved credentials, out of a WordPress export. + * + * @param bool $skip Whether the export leaves the meta out. + * @param string $meta_key The meta key. + * @return bool + */ + public function skip_json_headers_in_export( $skip, $meta_key ) { + return $skip || Visualizer_Plugin::CF_JSON_HEADERS === $meta_key; + } + /** * Refresh the specific chart from the db. * diff --git a/classes/Visualizer/Module/Upgrade.php b/classes/Visualizer/Module/Upgrade.php index 1dcf3b9e3..39c8b7c9f 100644 --- a/classes/Visualizer/Module/Upgrade.php +++ b/classes/Visualizer/Module/Upgrade.php @@ -24,6 +24,12 @@ public static function upgrade() { $upgraded = true; } + // Once after each update: an earlier version keeps such an image, and no version number marks the first one that does not. + if ( version_compare( $last_version, Visualizer_Plugin::VERSION, '<' ) ) { + self::deleteImagesOfPrivateRows(); + $upgraded = true; + } + if ( ! $upgraded ) { return; } @@ -34,6 +40,33 @@ public static function upgrade() { update_option( 'visualizer-upgraded-from', $last_version ); } + /** + * Deletes the images that an earlier version saved for unpublished charts with a post-type query. + * + * @return void + */ + private static function deleteImagesOfPrivateRows() { + $chart_ids = get_posts( + array( + 'post_type' => Visualizer_Plugin::CPT_VISUALIZER, + 'post_status' => array_values( array_diff( get_post_stati(), array( 'publish' ) ) ), + 'fields' => 'ids', + 'posts_per_page' => -1, + 'meta_query' => array( + array( + 'key' => Visualizer_Plugin::CF_FILTER_CONFIG, + 'compare' => 'EXISTS', + ), + array( + 'key' => Visualizer_Plugin::CF_CHART_IMAGE, + 'compare' => 'EXISTS', + ), + ), + ) + ); + array_map( array( 'Visualizer_Module', 'delete_image_of_private_rows' ), $chart_ids ); + } + /** * All 'dataTable' and 'table' charts to become 'tabular'. * All charts that do not have a library, to get the default library. diff --git a/classes/Visualizer/Remote/Fetch.php b/classes/Visualizer/Remote/Fetch.php index b1923caec..be2a1f3e1 100644 --- a/classes/Visualizer/Remote/Fetch.php +++ b/classes/Visualizer/Remote/Fetch.php @@ -384,7 +384,7 @@ private static function ip_in_range( $ip, $cidr ) { * @param string $second Second URL. * @return bool */ - private static function same_origin( $first, $second ) { + public static function same_origin( $first, $second ) { $first = wp_parse_url( $first ); $second = wp_parse_url( $second ); if ( ! is_array( $first ) || ! is_array( $second ) || empty( $first['scheme'] ) || empty( $first['host'] ) || empty( $second['scheme'] ) || empty( $second['host'] ) ) { diff --git a/classes/Visualizer/Render/Layout.php b/classes/Visualizer/Render/Layout.php index ed9b5b211..6c19872a2 100644 --- a/classes/Visualizer/Render/Layout.php +++ b/classes/Visualizer/Render/Layout.php @@ -188,19 +188,18 @@ public static function _renderJsonScreen( $args ) { } $methods = apply_filters( 'visualizer_json_request_methods', array( 'GET', 'POST' ) ); - $auth = isset( $headers['auth'] ) ? $headers['auth'] : ''; - $auth_username = is_array( $auth ) && isset( $auth['username'] ) ? $auth['username'] : ''; - $auth_password = is_array( $auth ) && isset( $auth['password'] ) ? $auth['password'] : ''; - $auth_string = is_string( $auth ) ? $auth : ''; + // Saved credentials are never printed. The save keeps them when the credential fields come back empty. + $has_saved_auth = ! empty( $headers['auth'] ); // open the headers by default? - $headers_open = ! empty( $auth_username ) || ! empty( $auth_string ); + $headers_open = $has_saved_auth; ?>