Categories
4 weeks ago
Coupons
4 weeks ago
Customers
2 months ago
Downloads
1 year ago
Export
3 years ago
Import
3 years ago
Orders
4 weeks ago
PerformanceIndicators
9 months ago
Products
4 weeks ago
Revenue
3 months ago
Stock
4 months ago
Taxes
4 weeks ago
Variations
4 weeks ago
Cache.php
4 years ago
Controller.php
11 months ago
DataStore.php
4 weeks ago
DataStoreInterface.php
4 years ago
ExportableInterface.php
4 years ago
ExportableTraits.php
4 years ago
FilteredGetDataTrait.php
1 year ago
GenericController.php
1 year ago
GenericQuery.php
1 year ago
GenericStatsController.php
1 year ago
OrderAwareControllerTrait.php
1 year ago
ParameterException.php
4 years ago
Query.php
1 year ago
Segmenter.php
1 year ago
SqlQuery.php
3 years ago
StatsDataStoreTrait.php
1 year ago
TimeInterval.php
2 years ago
DataStore.php
1624 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Admin\API\Reports\DataStore class file. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Admin\API\Reports; |
| 7 | |
| 8 | if ( ! defined( 'ABSPATH' ) ) { |
| 9 | exit; |
| 10 | } |
| 11 | |
| 12 | use Automattic\WooCommerce\Admin\API\Reports\DataStoreInterface; |
| 13 | use Automattic\WooCommerce\Admin\API\Reports\TimeInterval; |
| 14 | |
| 15 | /** |
| 16 | * Common parent for custom report data stores. |
| 17 | * |
| 18 | * We use Report DataStores to separate DB data retrieval logic from the REST API controllers. |
| 19 | * |
| 20 | * Handles caching, data normalization, intervals-related methods, and other common functionality. |
| 21 | * So, in your custom report DataStore class that extends this class |
| 22 | * you can focus on specifics by overriding the `get_noncached_data` method. |
| 23 | * |
| 24 | * Minimalistic example: |
| 25 | * <pre><code class="language-php">class MyDataStore extends DataStore implements DataStoreInterface { |
| 26 | * /** Cache identifier, used by the `DataStore` class to handle caching for you. */ |
| 27 | * protected $cache_key = 'my_thing'; |
| 28 | * /** Data store context used to pass to filters. */ |
| 29 | * protected $context = 'my_thing'; |
| 30 | * /** Table used to get the data. */ |
| 31 | * protected static $table_name = 'my_table'; |
| 32 | * /** |
| 33 | * * Method that overrides the `DataStore::get_noncached_data()` to return the report data. |
| 34 | * * Will be called by `get_data` if there is no data in cache. |
| 35 | * */ |
| 36 | * public function get_noncached_data( $query ) { |
| 37 | * // Do your magic. |
| 38 | * |
| 39 | * // Then return your data in conforming object structure. |
| 40 | * return (object) array( |
| 41 | * 'data' => $product_data, |
| 42 | * 'total' => 1, |
| 43 | * 'page_no' => 1, |
| 44 | * 'pages' => 1, |
| 45 | * ); |
| 46 | * } |
| 47 | * } |
| 48 | * </code></pre> |
| 49 | * |
| 50 | * Please use the `woocommerce_data_stores` filter to add your custom data store to the list of available ones. |
| 51 | * Then, your store could be accessed by Controller classes ({@see GenericController::get_datastore_data() GenericController::get_datastore_data()}) |
| 52 | * or using {@link \WC_Data_Store::load() \WC_Data_Store::load()}. |
| 53 | * |
| 54 | * We recommend registering using the REST base name of your Controller as the key, e.g.: |
| 55 | * <pre><code class="language-php">add_filter( 'woocommerce_data_stores', function( $stores ) { |
| 56 | * $stores['reports/my-thing'] = 'MyExtension\Admin\Analytics\Rest_API\MyDataStore'; |
| 57 | * } ); |
| 58 | * </code></pre> |
| 59 | * This way, `GenericController` will pick it up automatically. |
| 60 | * |
| 61 | * Note that this class is NOT {@link https://developer.woocommerce.com/docs/how-to-manage-woocommerce-data-stores/ a CRUD data store}. |
| 62 | * It does not implement the {@see WC_Object_Data_Store_Interface WC_Object_Data_Store_Interface} nor extend WC_Data & WC_Data_Store_WP classes. |
| 63 | */ |
| 64 | class DataStore extends SqlQuery implements DataStoreInterface { |
| 65 | |
| 66 | /** |
| 67 | * Cache group for the reports. |
| 68 | * |
| 69 | * @var string |
| 70 | */ |
| 71 | protected $cache_group = 'reports'; |
| 72 | |
| 73 | /** |
| 74 | * Time out for the cache. |
| 75 | * |
| 76 | * @var int |
| 77 | */ |
| 78 | protected $cache_timeout = 3600; |
| 79 | |
| 80 | /** |
| 81 | * Cache identifier. |
| 82 | * |
| 83 | * @var string |
| 84 | */ |
| 85 | protected $cache_key = ''; |
| 86 | |
| 87 | /** |
| 88 | * Table used as a data store for this report. |
| 89 | * |
| 90 | * @var string |
| 91 | */ |
| 92 | protected static $table_name = ''; |
| 93 | |
| 94 | /** |
| 95 | * Date field name. |
| 96 | * |
| 97 | * @var string |
| 98 | */ |
| 99 | protected $date_column_name = 'date_created'; |
| 100 | |
| 101 | /** |
| 102 | * Mapping columns to data type to return correct response types. |
| 103 | * |
| 104 | * @var array |
| 105 | */ |
| 106 | protected $column_types = array(); |
| 107 | |
| 108 | /** |
| 109 | * SQL columns to select in the db query. |
| 110 | * |
| 111 | * @var array |
| 112 | */ |
| 113 | protected $report_columns = array(); |
| 114 | |
| 115 | // @todo This does not really belong here, maybe factor out the comparison as separate class? |
| 116 | /** |
| 117 | * Order by property, used in the cmp function. |
| 118 | * |
| 119 | * @var string |
| 120 | */ |
| 121 | private $order_by = ''; |
| 122 | |
| 123 | /** |
| 124 | * Order property, used in the cmp function. |
| 125 | * |
| 126 | * @var string |
| 127 | */ |
| 128 | private $order = ''; |
| 129 | |
| 130 | /** |
| 131 | * Query limit parameters. |
| 132 | * |
| 133 | * @var array |
| 134 | */ |
| 135 | private $limit_parameters = array(); |
| 136 | |
| 137 | /** |
| 138 | * Data store context used to pass to filters. |
| 139 | * |
| 140 | * @override SqlQuery |
| 141 | * |
| 142 | * @var string |
| 143 | */ |
| 144 | protected $context = 'reports'; |
| 145 | |
| 146 | /** |
| 147 | * Subquery object for query nesting. |
| 148 | * |
| 149 | * @var SqlQuery |
| 150 | */ |
| 151 | protected $subquery; |
| 152 | |
| 153 | /** |
| 154 | * Totals query object. |
| 155 | * |
| 156 | * @var SqlQuery |
| 157 | */ |
| 158 | protected $total_query; |
| 159 | |
| 160 | /** |
| 161 | * Intervals query object. |
| 162 | * |
| 163 | * @var SqlQuery |
| 164 | */ |
| 165 | protected $interval_query; |
| 166 | |
| 167 | /** |
| 168 | * Refresh the cache for the current query when true. |
| 169 | * |
| 170 | * @var bool |
| 171 | */ |
| 172 | protected $force_cache_refresh = false; |
| 173 | |
| 174 | /** |
| 175 | * Include debugging information in the returned data when true. |
| 176 | * |
| 177 | * @var bool |
| 178 | */ |
| 179 | protected $debug_cache = true; |
| 180 | |
| 181 | /** |
| 182 | * Debugging information to include in the returned data. |
| 183 | * |
| 184 | * @var array |
| 185 | */ |
| 186 | protected $debug_cache_data = array(); |
| 187 | |
| 188 | /** |
| 189 | * Class constructor. |
| 190 | * |
| 191 | * @override SqlQuery::__construct() |
| 192 | */ |
| 193 | public function __construct() { |
| 194 | self::set_db_table_name(); |
| 195 | $this->assign_report_columns(); |
| 196 | |
| 197 | if ( $this->report_columns ) { |
| 198 | $this->report_columns = apply_filters( |
| 199 | 'woocommerce_admin_report_columns', |
| 200 | $this->report_columns, |
| 201 | $this->context, |
| 202 | self::get_db_table_name() |
| 203 | ); |
| 204 | } |
| 205 | |
| 206 | // Utilize enveloped responses to include debugging info. |
| 207 | // See https://querymonitor.com/blog/2021/05/debugging-wordpress-rest-api-requests/ |
| 208 | if ( isset( $_GET['_envelope'] ) ) { |
| 209 | $this->debug_cache = true; |
| 210 | add_filter( 'rest_envelope_response', array( $this, 'add_debug_cache_to_envelope' ), 999, 2 ); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | |
| 215 | /** |
| 216 | * Get the data based on args. |
| 217 | * |
| 218 | * Returns the report data based on parameters supplied by the user. |
| 219 | * Fetches it from cache or returns `get_noncached_data` result. |
| 220 | * |
| 221 | * @param array $query_args Query parameters. |
| 222 | * @return stdClass|WP_Error |
| 223 | */ |
| 224 | public function get_data( $query_args ) { |
| 225 | $defaults = $this->get_default_query_vars(); |
| 226 | $query_args = wp_parse_args( $query_args, $defaults ); |
| 227 | $this->normalize_timezones( $query_args, $defaults ); |
| 228 | |
| 229 | /* |
| 230 | * We need to get the cache key here because |
| 231 | * parent::update_intervals_sql_params() modifies $query_args. |
| 232 | */ |
| 233 | $cache_key = $this->get_cache_key( $query_args ); |
| 234 | $data = $this->get_cached_data( $cache_key ); |
| 235 | |
| 236 | if ( false === $data ) { |
| 237 | $data = $this->get_noncached_data( $query_args ); |
| 238 | $this->set_cached_data( $cache_key, $data ); |
| 239 | } |
| 240 | |
| 241 | return $data; |
| 242 | } |
| 243 | |
| 244 | /** |
| 245 | * Get the default query arguments to be used by get_data(). |
| 246 | * These defaults are only partially applied when used via REST API, as that has its own defaults. |
| 247 | * |
| 248 | * @return array Query parameters. |
| 249 | */ |
| 250 | public function get_default_query_vars() { |
| 251 | return array( |
| 252 | 'per_page' => get_option( 'posts_per_page' ), |
| 253 | 'page' => 1, |
| 254 | 'order' => 'DESC', |
| 255 | 'orderby' => 'date', |
| 256 | 'before' => TimeInterval::default_before(), |
| 257 | 'after' => TimeInterval::default_after(), |
| 258 | 'fields' => '*', |
| 259 | ); |
| 260 | } |
| 261 | |
| 262 | /** |
| 263 | * Get table name from database class. |
| 264 | */ |
| 265 | public static function get_db_table_name() { |
| 266 | global $wpdb; |
| 267 | return isset( $wpdb->{static::$table_name} ) ? $wpdb->{static::$table_name} : $wpdb->prefix . static::$table_name; |
| 268 | } |
| 269 | |
| 270 | /** |
| 271 | * Returns the report data based on normalized parameters. |
| 272 | * Will be called by `get_data` if there is no data in cache. |
| 273 | * |
| 274 | * @see get_data |
| 275 | * @param array $query_args Query parameters. |
| 276 | * @return stdClass|WP_Error Data object `{ totals: *, intervals: array, total: int, pages: int, page_no: int }`, or error. |
| 277 | */ |
| 278 | public function get_noncached_data( $query_args ) { |
| 279 | /* translators: %s: Method name */ |
| 280 | return new \WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass.", 'woocommerce' ), __METHOD__ ), array( 'status' => 405 ) ); |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Set table name from database class. |
| 285 | */ |
| 286 | protected static function set_db_table_name() { |
| 287 | global $wpdb; |
| 288 | if ( static::$table_name && ! isset( $wpdb->{static::$table_name} ) ) { |
| 289 | $wpdb->{static::$table_name} = $wpdb->prefix . static::$table_name; |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /** |
| 294 | * Whether or not the report should use the caching layer. |
| 295 | * |
| 296 | * Provides an opportunity for plugins to prevent reports from using cache. |
| 297 | * |
| 298 | * @return boolean Whether or not to utilize caching. |
| 299 | */ |
| 300 | protected function should_use_cache() { |
| 301 | /** |
| 302 | * Determines if a report will utilize caching. |
| 303 | * |
| 304 | * @param bool $use_cache Whether or not to use cache. |
| 305 | * @param string $cache_key The report's cache key. Used to identify the report. |
| 306 | */ |
| 307 | return (bool) apply_filters( 'woocommerce_analytics_report_should_use_cache', true, $this->cache_key ); |
| 308 | } |
| 309 | |
| 310 | /** |
| 311 | * Returns string to be used as cache key for the data. |
| 312 | * |
| 313 | * @param array $params Query parameters. |
| 314 | * @return string |
| 315 | */ |
| 316 | protected function get_cache_key( $params ) { |
| 317 | if ( isset( $params['force_cache_refresh'] ) ) { |
| 318 | if ( true === $params['force_cache_refresh'] ) { |
| 319 | $this->force_cache_refresh = true; |
| 320 | } |
| 321 | |
| 322 | // We don't want this param in the key. |
| 323 | unset( $params['force_cache_refresh'] ); |
| 324 | } |
| 325 | |
| 326 | if ( true === $this->debug_cache ) { |
| 327 | $this->debug_cache_data['query_args'] = $params; |
| 328 | } |
| 329 | |
| 330 | // Normalize the $params to reduce cache misses. |
| 331 | $params = array_filter( |
| 332 | $params, |
| 333 | function ( $param ) { |
| 334 | return ! empty( $param ); |
| 335 | } |
| 336 | ); |
| 337 | |
| 338 | // Normalize DateTime objects to ISO 8601 strings to avoid cache key |
| 339 | // instability caused by microsecond-level differences in serialization. |
| 340 | array_walk( |
| 341 | $params, |
| 342 | function ( &$value ) { |
| 343 | if ( $value instanceof \DateTimeInterface ) { |
| 344 | $value = $value->format( DATE_ATOM ); |
| 345 | } |
| 346 | } |
| 347 | ); |
| 348 | |
| 349 | ksort( $params ); |
| 350 | return implode( |
| 351 | '_', |
| 352 | array( |
| 353 | 'wc_report', |
| 354 | $this->cache_key, |
| 355 | md5( wp_json_encode( $params ) ), |
| 356 | ) |
| 357 | ); |
| 358 | } |
| 359 | |
| 360 | /** |
| 361 | * Wrapper around Cache::get(). |
| 362 | * |
| 363 | * @param string $cache_key Cache key. |
| 364 | * @return mixed |
| 365 | */ |
| 366 | protected function get_cached_data( $cache_key ) { |
| 367 | if ( true === $this->debug_cache ) { |
| 368 | $this->debug_cache_data['should_use_cache'] = $this->should_use_cache(); |
| 369 | $this->debug_cache_data['force_cache_refresh'] = $this->force_cache_refresh; |
| 370 | $this->debug_cache_data['cache_hit'] = false; |
| 371 | } |
| 372 | |
| 373 | if ( $this->should_use_cache() && false === $this->force_cache_refresh ) { |
| 374 | $cached_data = Cache::get( $cache_key ); |
| 375 | |
| 376 | $cache_hit = false !== $cached_data; |
| 377 | if ( true === $this->debug_cache ) { |
| 378 | $this->debug_cache_data['cache_hit'] = $cache_hit; |
| 379 | } |
| 380 | |
| 381 | return $cached_data; |
| 382 | } |
| 383 | |
| 384 | // Cached item has now functionally been refreshed. Reset the option. |
| 385 | $this->force_cache_refresh = false; |
| 386 | |
| 387 | return false; |
| 388 | } |
| 389 | |
| 390 | /** |
| 391 | * Wrapper around Cache::set(). |
| 392 | * |
| 393 | * @param string $cache_key Cache key. |
| 394 | * @param mixed $value New value. |
| 395 | * @return bool |
| 396 | */ |
| 397 | protected function set_cached_data( $cache_key, $value ) { |
| 398 | if ( $this->should_use_cache() ) { |
| 399 | return Cache::set( $cache_key, $value ); |
| 400 | } |
| 401 | |
| 402 | return true; |
| 403 | } |
| 404 | |
| 405 | /** |
| 406 | * Add cache debugging information to an enveloped API response. |
| 407 | * |
| 408 | * @param array $envelope |
| 409 | * @param \WP_REST_Response $response |
| 410 | * |
| 411 | * @return array |
| 412 | */ |
| 413 | public function add_debug_cache_to_envelope( $envelope, $response ) { |
| 414 | if ( 0 !== strncmp( '/wc-analytics', $response->get_matched_route(), 13 ) ) { |
| 415 | return $envelope; |
| 416 | } |
| 417 | |
| 418 | if ( ! empty( $this->debug_cache_data ) ) { |
| 419 | $envelope['debug_cache'] = $this->debug_cache_data; |
| 420 | } |
| 421 | |
| 422 | return $envelope; |
| 423 | } |
| 424 | |
| 425 | /** |
| 426 | * Compares two report data objects by pre-defined object property and ASC/DESC ordering. |
| 427 | * |
| 428 | * @param stdClass $a Object a. |
| 429 | * @param stdClass $b Object b. |
| 430 | * @return string |
| 431 | */ |
| 432 | private function interval_cmp( $a, $b ) { |
| 433 | if ( '' === $this->order_by || '' === $this->order ) { |
| 434 | return 0; |
| 435 | // @todo Should return WP_Error here perhaps? |
| 436 | } |
| 437 | if ( $a[ $this->order_by ] === $b[ $this->order_by ] ) { |
| 438 | // As relative order is undefined in case of equality in usort, second-level sorting by date needs to be enforced |
| 439 | // so that paging is stable. |
| 440 | if ( $a['time_interval'] === $b['time_interval'] ) { |
| 441 | return 0; // This should never happen. |
| 442 | } elseif ( $a['time_interval'] > $b['time_interval'] ) { |
| 443 | return 1; |
| 444 | } elseif ( $a['time_interval'] < $b['time_interval'] ) { |
| 445 | return -1; |
| 446 | } |
| 447 | } elseif ( $a[ $this->order_by ] > $b[ $this->order_by ] ) { |
| 448 | return strtolower( $this->order ) === 'desc' ? -1 : 1; |
| 449 | } elseif ( $a[ $this->order_by ] < $b[ $this->order_by ] ) { |
| 450 | return strtolower( $this->order ) === 'desc' ? 1 : -1; |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | /** |
| 455 | * Sorts intervals according to user's request. |
| 456 | * |
| 457 | * They are pre-sorted in SQL, but after adding gaps, they need to be sorted including the added ones. |
| 458 | * |
| 459 | * @param stdClass $data Data object, must contain an array under $data->intervals. |
| 460 | * @param string $sort_by Ordering property. |
| 461 | * @param string $direction DESC/ASC. |
| 462 | */ |
| 463 | protected function sort_intervals( &$data, $sort_by, $direction ) { |
| 464 | $this->sort_array( $data->intervals, $sort_by, $direction ); |
| 465 | } |
| 466 | |
| 467 | /** |
| 468 | * Sorts array of arrays based on subarray key $sort_by. |
| 469 | * |
| 470 | * @param array $arr Array to sort. |
| 471 | * @param string $sort_by Ordering property. |
| 472 | * @param string $direction DESC/ASC. |
| 473 | */ |
| 474 | protected function sort_array( &$arr, $sort_by, $direction ) { |
| 475 | $this->order_by = $this->normalize_order_by( $sort_by ); |
| 476 | $this->order = $direction; |
| 477 | usort( $arr, array( $this, 'interval_cmp' ) ); |
| 478 | } |
| 479 | |
| 480 | /** |
| 481 | * Fills in interval gaps from DB with 0-filled objects. |
| 482 | * |
| 483 | * @param array $db_intervals Array of all intervals present in the db. |
| 484 | * @param DateTime $start_datetime Start date. |
| 485 | * @param DateTime $end_datetime End date. |
| 486 | * @param string $time_interval Time interval, e.g. day, week, month. |
| 487 | * @param stdClass $data Data with SQL extracted intervals. |
| 488 | * @return stdClass |
| 489 | */ |
| 490 | protected function fill_in_missing_intervals( $db_intervals, $start_datetime, $end_datetime, $time_interval, &$data ) { |
| 491 | // @todo This is ugly and messy. |
| 492 | $local_tz = new \DateTimeZone( wc_timezone_string() ); |
| 493 | // At this point, we don't know when we can stop iterating, as the ordering can be based on any value. |
| 494 | $time_ids = array_flip( wp_list_pluck( $data->intervals, 'time_interval' ) ); |
| 495 | $db_intervals = array_flip( $db_intervals ); |
| 496 | // Totals object used to get all needed properties. |
| 497 | $totals_arr = get_object_vars( $data->totals ); |
| 498 | foreach ( $totals_arr as $key => $val ) { |
| 499 | $totals_arr[ $key ] = 0; |
| 500 | } |
| 501 | // @todo Should 'products' be in intervals? |
| 502 | unset( $totals_arr['products'] ); |
| 503 | while ( $start_datetime <= $end_datetime ) { |
| 504 | $next_start = TimeInterval::iterate( $start_datetime, $time_interval ); |
| 505 | $time_id = TimeInterval::time_interval_id( $time_interval, $start_datetime ); |
| 506 | // Either create fill-zero interval or use data from db. |
| 507 | if ( $next_start > $end_datetime ) { |
| 508 | $interval_end = $end_datetime->format( 'Y-m-d H:i:s' ); |
| 509 | } else { |
| 510 | $prev_end_timestamp = (int) $next_start->format( 'U' ) - 1; |
| 511 | $prev_end = new \DateTime(); |
| 512 | $prev_end->setTimestamp( $prev_end_timestamp ); |
| 513 | $prev_end->setTimezone( $local_tz ); |
| 514 | $interval_end = $prev_end->format( 'Y-m-d H:i:s' ); |
| 515 | } |
| 516 | if ( array_key_exists( $time_id, $time_ids ) ) { |
| 517 | // For interval present in the db for this time frame, just fill in dates. |
| 518 | $record = &$data->intervals[ $time_ids[ $time_id ] ]; |
| 519 | $record['date_start'] = $start_datetime->format( 'Y-m-d H:i:s' ); |
| 520 | $record['date_end'] = $interval_end; |
| 521 | } elseif ( ! array_key_exists( $time_id, $db_intervals ) ) { |
| 522 | // For intervals present in the db outside of this time frame, do nothing. |
| 523 | // For intervals not present in the db, fabricate it. |
| 524 | $record_arr = array(); |
| 525 | $record_arr['time_interval'] = $time_id; |
| 526 | $record_arr['date_start'] = $start_datetime->format( 'Y-m-d H:i:s' ); |
| 527 | $record_arr['date_end'] = $interval_end; |
| 528 | $data->intervals[] = array_merge( $record_arr, $totals_arr ); |
| 529 | } |
| 530 | $start_datetime = $next_start; |
| 531 | } |
| 532 | return $data; |
| 533 | } |
| 534 | |
| 535 | /** |
| 536 | * Converts input datetime parameters to local timezone. If there are no inputs from the user in query_args, |
| 537 | * uses default from $defaults. |
| 538 | * |
| 539 | * @param array $query_args Array of query arguments. |
| 540 | * @param array $defaults Array of default values. |
| 541 | */ |
| 542 | protected function normalize_timezones( &$query_args, $defaults ) { |
| 543 | $local_tz = new \DateTimeZone( wc_timezone_string() ); |
| 544 | foreach ( array( 'before', 'after' ) as $query_arg_key ) { |
| 545 | if ( isset( $query_args[ $query_arg_key ] ) && is_string( $query_args[ $query_arg_key ] ) ) { |
| 546 | // Assume that unspecified timezone is a local timezone. |
| 547 | $datetime = new \DateTime( $query_args[ $query_arg_key ], $local_tz ); |
| 548 | // In case timezone was forced by using +HH:MM, convert to local timezone. |
| 549 | $datetime->setTimezone( $local_tz ); |
| 550 | $query_args[ $query_arg_key ] = $datetime; |
| 551 | } elseif ( isset( $query_args[ $query_arg_key ] ) && is_a( $query_args[ $query_arg_key ], 'DateTime' ) ) { |
| 552 | // In case timezone is in other timezone, convert to local timezone. |
| 553 | $query_args[ $query_arg_key ]->setTimezone( $local_tz ); |
| 554 | } else { |
| 555 | $query_args[ $query_arg_key ] = isset( $defaults[ $query_arg_key ] ) ? $defaults[ $query_arg_key ] : null; |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /** |
| 561 | * Removes extra records from intervals so that only requested number of records get returned. |
| 562 | * |
| 563 | * @param stdClass $data Data from whose intervals the records get removed. |
| 564 | * @param int $page_no Offset requested by the user. |
| 565 | * @param int $items_per_page Number of records requested by the user. |
| 566 | * @param int $db_interval_count Database interval count. |
| 567 | * @param int $expected_interval_count Expected interval count on the output. |
| 568 | * @param string $order_by Order by field. |
| 569 | * @param string $order ASC or DESC. |
| 570 | */ |
| 571 | protected function remove_extra_records( &$data, $page_no, $items_per_page, $db_interval_count, $expected_interval_count, $order_by, $order ) { |
| 572 | if ( 'date' === strtolower( $order_by ) ) { |
| 573 | $offset = 0; |
| 574 | } else { |
| 575 | if ( 'asc' === strtolower( $order ) ) { |
| 576 | $offset = ( $page_no - 1 ) * $items_per_page; |
| 577 | } else { |
| 578 | $offset = ( $page_no - 1 ) * $items_per_page - $db_interval_count; |
| 579 | } |
| 580 | $offset = $offset < 0 ? 0 : $offset; |
| 581 | } |
| 582 | $count = $expected_interval_count - ( $page_no - 1 ) * $items_per_page; |
| 583 | if ( $count < 0 ) { |
| 584 | $count = 0; |
| 585 | } elseif ( $count > $items_per_page ) { |
| 586 | $count = $items_per_page; |
| 587 | } |
| 588 | $data->intervals = array_slice( $data->intervals, $offset, $count ); |
| 589 | } |
| 590 | |
| 591 | /** |
| 592 | * Returns expected number of items on the page in case of date ordering. |
| 593 | * |
| 594 | * @param int $expected_interval_count Expected number of intervals in total. |
| 595 | * @param int $items_per_page Number of items per page. |
| 596 | * @param int $page_no Page number. |
| 597 | * |
| 598 | * @return float|int |
| 599 | */ |
| 600 | protected function expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no ) { |
| 601 | $total_pages = (int) ceil( $expected_interval_count / $items_per_page ); |
| 602 | if ( $page_no < $total_pages ) { |
| 603 | return $items_per_page; |
| 604 | } elseif ( $page_no === $total_pages ) { |
| 605 | return $expected_interval_count - ( $page_no - 1 ) * $items_per_page; |
| 606 | } else { |
| 607 | return 0; |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | /** |
| 612 | * Returns true if there are any intervals that need to be filled in the response. |
| 613 | * |
| 614 | * @param int $expected_interval_count Expected number of intervals in total. |
| 615 | * @param int $db_records Total number of records for given period in the database. |
| 616 | * @param int $items_per_page Number of items per page. |
| 617 | * @param int $page_no Page number. |
| 618 | * @param string $order asc or desc. |
| 619 | * @param string $order_by Column by which the result will be sorted. |
| 620 | * @param int $intervals_count Number of records for given (possibly shortened) time interval. |
| 621 | * |
| 622 | * @return bool |
| 623 | */ |
| 624 | protected function intervals_missing( $expected_interval_count, $db_records, $items_per_page, $page_no, $order, $order_by, $intervals_count ) { |
| 625 | if ( $expected_interval_count <= $db_records ) { |
| 626 | return false; |
| 627 | } |
| 628 | if ( 'date' === $order_by ) { |
| 629 | $expected_intervals_on_page = $this->expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no ); |
| 630 | return $intervals_count < $expected_intervals_on_page; |
| 631 | } |
| 632 | if ( 'desc' === $order ) { |
| 633 | return $page_no > floor( $db_records / $items_per_page ); |
| 634 | } |
| 635 | if ( 'asc' === $order ) { |
| 636 | return $page_no <= ceil( ( $expected_interval_count - $db_records ) / $items_per_page ); |
| 637 | } |
| 638 | // Invalid ordering. |
| 639 | return false; |
| 640 | } |
| 641 | |
| 642 | /** |
| 643 | * Updates the LIMIT query part for Intervals query of the report. |
| 644 | * |
| 645 | * If there are less records in the database than time intervals, then we need to remap offset in SQL query |
| 646 | * to fetch correct records. |
| 647 | * |
| 648 | * @param array $query_args Query arguments. |
| 649 | * @param int $db_interval_count Database interval count. |
| 650 | * @param int $expected_interval_count Expected interval count on the output. |
| 651 | * @param string $table_name Name of the db table relevant for the date constraint. |
| 652 | */ |
| 653 | protected function update_intervals_sql_params( &$query_args, $db_interval_count, $expected_interval_count, $table_name ) { |
| 654 | if ( $db_interval_count === $expected_interval_count ) { |
| 655 | return; |
| 656 | } |
| 657 | |
| 658 | $params = $this->get_limit_params( $query_args ); |
| 659 | $local_tz = new \DateTimeZone( wc_timezone_string() ); |
| 660 | if ( 'date' === strtolower( $query_args['orderby'] ) ) { |
| 661 | // page X in request translates to slightly different dates in the db, in case some |
| 662 | // records are missing from the db. |
| 663 | $start_iteration = 0; |
| 664 | $end_iteration = 0; |
| 665 | if ( 'asc' === strtolower( $query_args['order'] ) ) { |
| 666 | // ORDER BY date ASC. |
| 667 | $new_start_date = $query_args['after']; |
| 668 | $intervals_to_skip = ( $query_args['page'] - 1 ) * $params['per_page']; |
| 669 | $latest_end_date = $query_args['before']; |
| 670 | for ( $i = 0; $i < $intervals_to_skip; $i++ ) { |
| 671 | if ( $new_start_date > $latest_end_date ) { |
| 672 | $new_start_date = $latest_end_date; |
| 673 | $start_iteration = 0; |
| 674 | break; |
| 675 | } |
| 676 | $new_start_date = TimeInterval::iterate( $new_start_date, $query_args['interval'] ); |
| 677 | $start_iteration ++; |
| 678 | } |
| 679 | |
| 680 | $new_end_date = clone $new_start_date; |
| 681 | for ( $i = 0; $i < $params['per_page']; $i++ ) { |
| 682 | if ( $new_end_date > $latest_end_date ) { |
| 683 | break; |
| 684 | } |
| 685 | $new_end_date = TimeInterval::iterate( $new_end_date, $query_args['interval'] ); |
| 686 | $end_iteration ++; |
| 687 | } |
| 688 | if ( $new_end_date > $latest_end_date ) { |
| 689 | $new_end_date = $latest_end_date; |
| 690 | $end_iteration = 0; |
| 691 | } |
| 692 | if ( $end_iteration ) { |
| 693 | $new_end_date_timestamp = (int) $new_end_date->format( 'U' ) - 1; |
| 694 | $new_end_date->setTimestamp( $new_end_date_timestamp ); |
| 695 | } |
| 696 | } else { |
| 697 | // ORDER BY date DESC. |
| 698 | $new_end_date = $query_args['before']; |
| 699 | $intervals_to_skip = ( $query_args['page'] - 1 ) * $params['per_page']; |
| 700 | $earliest_start_date = $query_args['after']; |
| 701 | for ( $i = 0; $i < $intervals_to_skip; $i++ ) { |
| 702 | if ( $new_end_date < $earliest_start_date ) { |
| 703 | $new_end_date = $earliest_start_date; |
| 704 | $end_iteration = 0; |
| 705 | break; |
| 706 | } |
| 707 | $new_end_date = TimeInterval::iterate( $new_end_date, $query_args['interval'], true ); |
| 708 | $end_iteration ++; |
| 709 | } |
| 710 | |
| 711 | $new_start_date = clone $new_end_date; |
| 712 | for ( $i = 0; $i < $params['per_page']; $i++ ) { |
| 713 | if ( $new_start_date < $earliest_start_date ) { |
| 714 | break; |
| 715 | } |
| 716 | $new_start_date = TimeInterval::iterate( $new_start_date, $query_args['interval'], true ); |
| 717 | $start_iteration ++; |
| 718 | } |
| 719 | if ( $new_start_date < $earliest_start_date ) { |
| 720 | $new_start_date = $earliest_start_date; |
| 721 | $start_iteration = 0; |
| 722 | } |
| 723 | if ( $start_iteration ) { |
| 724 | // @todo Is this correct? should it only be added if iterate runs? other two iterate instances, too? |
| 725 | $new_start_date_timestamp = (int) $new_start_date->format( 'U' ) + 1; |
| 726 | $new_start_date->setTimestamp( $new_start_date_timestamp ); |
| 727 | } |
| 728 | } |
| 729 | // @todo - Do this without modifying $query_args? |
| 730 | $query_args['adj_after'] = $new_start_date; |
| 731 | $query_args['adj_before'] = $new_end_date; |
| 732 | $adj_after = $new_start_date->format( TimeInterval::$sql_datetime_format ); |
| 733 | $adj_before = $new_end_date->format( TimeInterval::$sql_datetime_format ); |
| 734 | $this->interval_query->clear_sql_clause( array( 'where_time', 'limit' ) ); |
| 735 | $this->interval_query->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` <= '$adj_before'" ); |
| 736 | $this->interval_query->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` >= '$adj_after'" ); |
| 737 | $this->clear_sql_clause( 'limit' ); |
| 738 | $this->add_sql_clause( 'limit', 'LIMIT 0,' . $params['per_page'] ); |
| 739 | } else { |
| 740 | if ( 'asc' === $query_args['order'] ) { |
| 741 | $offset = ( ( $query_args['page'] - 1 ) * $params['per_page'] ) - ( $expected_interval_count - $db_interval_count ); |
| 742 | $offset = $offset < 0 ? 0 : $offset; |
| 743 | $count = $query_args['page'] * $params['per_page'] - ( $expected_interval_count - $db_interval_count ); |
| 744 | if ( $count < 0 ) { |
| 745 | $count = 0; |
| 746 | } elseif ( $count > $params['per_page'] ) { |
| 747 | $count = $params['per_page']; |
| 748 | } |
| 749 | |
| 750 | $this->clear_sql_clause( 'limit' ); |
| 751 | $this->add_sql_clause( 'limit', 'LIMIT ' . $offset . ',' . $count ); |
| 752 | } |
| 753 | // Otherwise no change in limit clause. |
| 754 | // @todo - Do this without modifying $query_args? |
| 755 | $query_args['adj_after'] = $query_args['after']; |
| 756 | $query_args['adj_before'] = $query_args['before']; |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | /** |
| 761 | * Casts strings returned from the database to appropriate data types for output. |
| 762 | * |
| 763 | * @param array $array Associative array of values extracted from the database. |
| 764 | * @return array|WP_Error |
| 765 | */ |
| 766 | protected function cast_numbers( $array ) { |
| 767 | $retyped_array = array(); |
| 768 | $column_types = apply_filters( 'woocommerce_rest_reports_column_types', $this->column_types, $array ); |
| 769 | foreach ( $array as $column_name => $value ) { |
| 770 | if ( is_array( $value ) ) { |
| 771 | $value = $this->cast_numbers( $value ); |
| 772 | } |
| 773 | |
| 774 | if ( isset( $column_types[ $column_name ] ) ) { |
| 775 | $retyped_array[ $column_name ] = $column_types[ $column_name ]( $value ); |
| 776 | } else { |
| 777 | $retyped_array[ $column_name ] = $value; |
| 778 | } |
| 779 | } |
| 780 | return $retyped_array; |
| 781 | } |
| 782 | |
| 783 | /** |
| 784 | * Returns a list of columns selected by the query_args formatted as a comma separated string. |
| 785 | * |
| 786 | * @param array $query_args User-supplied options. |
| 787 | * @return string |
| 788 | */ |
| 789 | protected function selected_columns( $query_args ) { |
| 790 | $selections = $this->report_columns; |
| 791 | |
| 792 | if ( isset( $query_args['fields'] ) && is_array( $query_args['fields'] ) ) { |
| 793 | $keep = array(); |
| 794 | foreach ( $query_args['fields'] as $field ) { |
| 795 | if ( isset( $selections[ $field ] ) ) { |
| 796 | $keep[ $field ] = $selections[ $field ]; |
| 797 | } |
| 798 | } |
| 799 | $selections = implode( ', ', $keep ); |
| 800 | } else { |
| 801 | $selections = implode( ', ', $selections ); |
| 802 | } |
| 803 | return $selections; |
| 804 | } |
| 805 | |
| 806 | /** |
| 807 | * Get the excluded order statuses used when calculating reports. |
| 808 | * |
| 809 | * @return array |
| 810 | */ |
| 811 | protected static function get_excluded_report_order_statuses() { |
| 812 | $excluded_statuses = \WC_Admin_Settings::get_option( 'woocommerce_excluded_report_order_statuses', array( 'pending', 'failed', 'cancelled' ) ); |
| 813 | $excluded_statuses = array_merge( array( 'auto-draft', 'trash' ), array_map( 'esc_sql', $excluded_statuses ) ); |
| 814 | return apply_filters( 'woocommerce_analytics_excluded_order_statuses', $excluded_statuses ); |
| 815 | } |
| 816 | |
| 817 | /** |
| 818 | * Maps order status provided by the user to the one used in the database. |
| 819 | * |
| 820 | * @param string $status Order status. |
| 821 | * @return string |
| 822 | */ |
| 823 | protected static function normalize_order_status( $status ) { |
| 824 | $status = trim( $status ); |
| 825 | return 'wc-' . $status; |
| 826 | } |
| 827 | |
| 828 | /** |
| 829 | * Normalizes order_by clause to match to SQL query. |
| 830 | * |
| 831 | * @param string $order_by Order by option requested by user. |
| 832 | * @return string |
| 833 | */ |
| 834 | protected function normalize_order_by( $order_by ) { |
| 835 | if ( 'date' === $order_by ) { |
| 836 | return 'time_interval'; |
| 837 | } |
| 838 | |
| 839 | return $order_by; |
| 840 | } |
| 841 | |
| 842 | /** |
| 843 | * Updates start and end dates for intervals so that they represent intervals' borders, not times when data in db were recorded. |
| 844 | * |
| 845 | * E.g. if there are db records for only Tuesday and Thursday this week, the actual week interval is [Mon, Sun], not [Tue, Thu]. |
| 846 | * |
| 847 | * @param DateTime $start_datetime Start date. |
| 848 | * @param DateTime $end_datetime End date. |
| 849 | * @param string $time_interval Time interval, e.g. day, week, month. |
| 850 | * @param array $intervals Array of intervals extracted from SQL db. |
| 851 | */ |
| 852 | protected function update_interval_boundary_dates( $start_datetime, $end_datetime, $time_interval, &$intervals ) { |
| 853 | $local_tz = new \DateTimeZone( wc_timezone_string() ); |
| 854 | foreach ( $intervals as $key => $interval ) { |
| 855 | $datetime = new \DateTime( $interval['datetime_anchor'], $local_tz ); |
| 856 | |
| 857 | $prev_start = TimeInterval::iterate( $datetime, $time_interval, true ); |
| 858 | // @todo Not sure if the +1/-1 here are correct, especially as they are applied before the ?: below. |
| 859 | $prev_start_timestamp = (int) $prev_start->format( 'U' ) + 1; |
| 860 | $prev_start->setTimestamp( $prev_start_timestamp ); |
| 861 | if ( $start_datetime ) { |
| 862 | $date_start = $prev_start < $start_datetime ? $start_datetime : $prev_start; |
| 863 | $intervals[ $key ]['date_start'] = $date_start->format( 'Y-m-d H:i:s' ); |
| 864 | } else { |
| 865 | $intervals[ $key ]['date_start'] = $prev_start->format( 'Y-m-d H:i:s' ); |
| 866 | } |
| 867 | |
| 868 | $next_end = TimeInterval::iterate( $datetime, $time_interval ); |
| 869 | $next_end_timestamp = (int) $next_end->format( 'U' ) - 1; |
| 870 | $next_end->setTimestamp( $next_end_timestamp ); |
| 871 | if ( $end_datetime ) { |
| 872 | $date_end = $next_end > $end_datetime ? $end_datetime : $next_end; |
| 873 | $intervals[ $key ]['date_end'] = $date_end->format( 'Y-m-d H:i:s' ); |
| 874 | } else { |
| 875 | $intervals[ $key ]['date_end'] = $next_end->format( 'Y-m-d H:i:s' ); |
| 876 | } |
| 877 | |
| 878 | $intervals[ $key ]['interval'] = $time_interval; |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | /** |
| 883 | * Change structure of intervals to form a correct response. |
| 884 | * |
| 885 | * Also converts local datetimes to GMT and adds them to the intervals. |
| 886 | * |
| 887 | * @param array $intervals Time interval, e.g. day, week, month. |
| 888 | */ |
| 889 | protected function create_interval_subtotals( &$intervals ) { |
| 890 | foreach ( $intervals as $key => $interval ) { |
| 891 | $start_gmt = TimeInterval::convert_local_datetime_to_gmt( $interval['date_start'] ); |
| 892 | $end_gmt = TimeInterval::convert_local_datetime_to_gmt( $interval['date_end'] ); |
| 893 | // Move intervals result to subtotals object. |
| 894 | $intervals[ $key ] = array( |
| 895 | 'interval' => $interval['time_interval'], |
| 896 | 'date_start' => $interval['date_start'], |
| 897 | 'date_start_gmt' => $start_gmt->format( TimeInterval::$sql_datetime_format ), |
| 898 | 'date_end' => $interval['date_end'], |
| 899 | 'date_end_gmt' => $end_gmt->format( TimeInterval::$sql_datetime_format ), |
| 900 | ); |
| 901 | |
| 902 | unset( $interval['interval'] ); |
| 903 | unset( $interval['date_start'] ); |
| 904 | unset( $interval['date_end'] ); |
| 905 | unset( $interval['datetime_anchor'] ); |
| 906 | unset( $interval['time_interval'] ); |
| 907 | $intervals[ $key ]['subtotals'] = (object) $this->cast_numbers( $interval ); |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | /** |
| 912 | * Fills WHERE clause of SQL request with date-related constraints. |
| 913 | * |
| 914 | * @param array $query_args Parameters supplied by the user. |
| 915 | * @param string $table_name Name of the db table relevant for the date constraint. |
| 916 | */ |
| 917 | protected function add_time_period_sql_params( $query_args, $table_name ) { |
| 918 | $this->clear_sql_clause( array( 'from', 'where_time', 'where' ) ); |
| 919 | if ( isset( $this->subquery ) ) { |
| 920 | $this->subquery->clear_sql_clause( 'where_time' ); |
| 921 | } |
| 922 | |
| 923 | if ( isset( $query_args['before'] ) && '' !== $query_args['before'] ) { |
| 924 | if ( is_a( $query_args['before'], 'WC_DateTime' ) ) { |
| 925 | $datetime_str = $query_args['before']->date( TimeInterval::$sql_datetime_format ); |
| 926 | } else { |
| 927 | $datetime_str = $query_args['before']->format( TimeInterval::$sql_datetime_format ); |
| 928 | } |
| 929 | if ( isset( $this->subquery ) ) { |
| 930 | $this->subquery->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` <= '$datetime_str'" ); |
| 931 | } else { |
| 932 | $this->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` <= '$datetime_str'" ); |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | if ( isset( $query_args['after'] ) && '' !== $query_args['after'] ) { |
| 937 | if ( is_a( $query_args['after'], 'WC_DateTime' ) ) { |
| 938 | $datetime_str = $query_args['after']->date( TimeInterval::$sql_datetime_format ); |
| 939 | } else { |
| 940 | $datetime_str = $query_args['after']->format( TimeInterval::$sql_datetime_format ); |
| 941 | } |
| 942 | if ( isset( $this->subquery ) ) { |
| 943 | $this->subquery->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` >= '$datetime_str'" ); |
| 944 | } else { |
| 945 | $this->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` >= '$datetime_str'" ); |
| 946 | } |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | /** |
| 951 | * Fills LIMIT clause of SQL request based on user supplied parameters. |
| 952 | * |
| 953 | * @param array $query_args Parameters supplied by the user. |
| 954 | * @return array |
| 955 | */ |
| 956 | protected function get_limit_sql_params( $query_args ) { |
| 957 | global $wpdb; |
| 958 | $params = $this->get_limit_params( $query_args ); |
| 959 | |
| 960 | $this->clear_sql_clause( 'limit' ); |
| 961 | $this->add_sql_clause( 'limit', $wpdb->prepare( 'LIMIT %d, %d', $params['offset'], $params['per_page'] ) ); |
| 962 | return $params; |
| 963 | } |
| 964 | |
| 965 | /** |
| 966 | * Fills LIMIT parameters of SQL request based on user supplied parameters. |
| 967 | * |
| 968 | * @param array $query_args Parameters supplied by the user. |
| 969 | * @return array |
| 970 | */ |
| 971 | protected function get_limit_params( $query_args = array() ) { |
| 972 | if ( isset( $query_args['per_page'] ) && is_numeric( $query_args['per_page'] ) ) { |
| 973 | $this->limit_parameters['per_page'] = (int) $query_args['per_page']; |
| 974 | } else { |
| 975 | $this->limit_parameters['per_page'] = get_option( 'posts_per_page' ); |
| 976 | } |
| 977 | |
| 978 | $this->limit_parameters['offset'] = 0; |
| 979 | if ( isset( $query_args['page'] ) ) { |
| 980 | $this->limit_parameters['offset'] = ( (int) $query_args['page'] - 1 ) * $this->limit_parameters['per_page']; |
| 981 | } |
| 982 | |
| 983 | return $this->limit_parameters; |
| 984 | } |
| 985 | |
| 986 | /** |
| 987 | * Generates a virtual table given a list of IDs. |
| 988 | * |
| 989 | * @param array $ids Array of IDs. |
| 990 | * @param array $id_field Name of the ID field. |
| 991 | * @param array $other_values Other values that must be contained in the virtual table. |
| 992 | * @return array |
| 993 | */ |
| 994 | protected function get_ids_table( $ids, $id_field, $other_values = array() ) { |
| 995 | global $wpdb; |
| 996 | $selects = array(); |
| 997 | foreach ( $ids as $id ) { |
| 998 | // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 999 | $new_select = $wpdb->prepare( "SELECT %s AS {$id_field}", $id ); |
| 1000 | foreach ( $other_values as $key => $value ) { |
| 1001 | $new_select .= $wpdb->prepare( ", %s AS {$key}", $value ); |
| 1002 | } |
| 1003 | // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 1004 | array_push( $selects, $new_select ); |
| 1005 | } |
| 1006 | return join( ' UNION ', $selects ); |
| 1007 | } |
| 1008 | |
| 1009 | /** |
| 1010 | * Returns a comma separated list of the fields in the `query_args`, if there aren't, returns `report_columns` keys. |
| 1011 | * |
| 1012 | * @param array $query_args Parameters supplied by the user. |
| 1013 | * @return array |
| 1014 | */ |
| 1015 | protected function get_fields( $query_args ) { |
| 1016 | if ( isset( $query_args['fields'] ) && is_array( $query_args['fields'] ) ) { |
| 1017 | return $query_args['fields']; |
| 1018 | } |
| 1019 | return array_keys( $this->report_columns ); |
| 1020 | } |
| 1021 | |
| 1022 | /** |
| 1023 | * Returns a comma separated list of the field names prepared to be used for a selection after a join with `default_results`. |
| 1024 | * |
| 1025 | * @param array $fields Array of fields name. |
| 1026 | * @param array $default_results_fields Fields to load from `default_results` table. |
| 1027 | * @param array $outer_selections Array of fields that are not selected in the inner query. |
| 1028 | * @return string |
| 1029 | */ |
| 1030 | protected function format_join_selections( $fields, $default_results_fields, $outer_selections = array() ) { |
| 1031 | foreach ( $fields as $i => $field ) { |
| 1032 | foreach ( $default_results_fields as $default_results_field ) { |
| 1033 | if ( $field === $default_results_field ) { |
| 1034 | $field = esc_sql( $field ); |
| 1035 | $fields[ $i ] = "default_results.{$field} AS {$field}"; |
| 1036 | } |
| 1037 | } |
| 1038 | if ( in_array( $field, $outer_selections, true ) && array_key_exists( $field, $this->report_columns ) ) { |
| 1039 | $fields[ $i ] = $this->report_columns[ $field ]; |
| 1040 | } |
| 1041 | } |
| 1042 | return implode( ', ', $fields ); |
| 1043 | } |
| 1044 | |
| 1045 | /** |
| 1046 | * Fills ORDER BY clause of SQL request based on user supplied parameters. |
| 1047 | * |
| 1048 | * @param array $query_args Parameters supplied by the user. |
| 1049 | */ |
| 1050 | protected function add_order_by_sql_params( $query_args ) { |
| 1051 | if ( isset( $query_args['orderby'] ) ) { |
| 1052 | $order_by_clause = $this->normalize_order_by( esc_sql( $query_args['orderby'] ) ); |
| 1053 | } else { |
| 1054 | $order_by_clause = ''; |
| 1055 | } |
| 1056 | |
| 1057 | $this->clear_sql_clause( 'order_by' ); |
| 1058 | $this->add_sql_clause( 'order_by', $order_by_clause ); |
| 1059 | $this->add_orderby_order_clause( $query_args, $this ); |
| 1060 | } |
| 1061 | |
| 1062 | /** |
| 1063 | * Fills FROM and WHERE clauses of SQL request for 'Intervals' section of data response based on user supplied parameters. |
| 1064 | * |
| 1065 | * @param array $query_args Parameters supplied by the user. |
| 1066 | * @param string $table_name Name of the db table relevant for the date constraint. |
| 1067 | */ |
| 1068 | protected function add_intervals_sql_params( $query_args, $table_name ) { |
| 1069 | $this->clear_sql_clause( array( 'from', 'where_time', 'where' ) ); |
| 1070 | |
| 1071 | $this->add_time_period_sql_params( $query_args, $table_name ); |
| 1072 | |
| 1073 | if ( isset( $query_args['interval'] ) && '' !== $query_args['interval'] ) { |
| 1074 | $interval = $query_args['interval']; |
| 1075 | $this->clear_sql_clause( 'select' ); |
| 1076 | $this->add_sql_clause( 'select', TimeInterval::db_datetime_format( $interval, $table_name, $this->date_column_name ) ); |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | /** |
| 1081 | * Get join and where clauses for refunds based on user supplied parameters. |
| 1082 | * |
| 1083 | * @param array $query_args Parameters supplied by the user. |
| 1084 | * @return array |
| 1085 | */ |
| 1086 | protected function get_refund_subquery( $query_args ) { |
| 1087 | global $wpdb; |
| 1088 | $table_name = $wpdb->prefix . 'wc_order_stats'; |
| 1089 | $sql_query = array( |
| 1090 | 'where_clause' => '', |
| 1091 | 'from_clause' => '', |
| 1092 | ); |
| 1093 | |
| 1094 | if ( ! isset( $query_args['refunds'] ) ) { |
| 1095 | return $sql_query; |
| 1096 | } |
| 1097 | |
| 1098 | if ( 'all' === $query_args['refunds'] ) { |
| 1099 | $sql_query['where_clause'] .= 'parent_id != 0'; |
| 1100 | } |
| 1101 | |
| 1102 | if ( 'none' === $query_args['refunds'] ) { |
| 1103 | $sql_query['where_clause'] .= 'parent_id = 0'; |
| 1104 | } |
| 1105 | |
| 1106 | if ( 'full' === $query_args['refunds'] || 'partial' === $query_args['refunds'] ) { |
| 1107 | $operator = 'full' === $query_args['refunds'] ? '=' : '!='; |
| 1108 | $sql_query['from_clause'] .= " JOIN {$table_name} parent_order_stats ON {$table_name}.parent_id = parent_order_stats.order_id"; |
| 1109 | $sql_query['where_clause'] .= "parent_order_stats.status {$operator} '{$this->normalize_order_status( 'refunded' )}'"; |
| 1110 | } |
| 1111 | |
| 1112 | return $sql_query; |
| 1113 | } |
| 1114 | |
| 1115 | /** |
| 1116 | * Returns an array of products belonging to given categories. |
| 1117 | * |
| 1118 | * @param array $categories List of categories IDs. |
| 1119 | * @return array|stdClass |
| 1120 | */ |
| 1121 | protected function get_products_by_cat_ids( $categories ) { |
| 1122 | $terms = get_terms( |
| 1123 | array( |
| 1124 | 'taxonomy' => 'product_cat', |
| 1125 | 'include' => $categories, |
| 1126 | ) |
| 1127 | ); |
| 1128 | |
| 1129 | if ( is_wp_error( $terms ) || empty( $terms ) ) { |
| 1130 | return array(); |
| 1131 | } |
| 1132 | |
| 1133 | $args = array( |
| 1134 | 'category' => wc_list_pluck( $terms, 'slug' ), |
| 1135 | 'limit' => -1, |
| 1136 | 'return' => 'ids', |
| 1137 | ); |
| 1138 | return wc_get_products( $args ); |
| 1139 | } |
| 1140 | |
| 1141 | /** |
| 1142 | * Get WHERE filter by object ids subquery. |
| 1143 | * |
| 1144 | * @param string $select_table Select table name. |
| 1145 | * @param string $select_field Select table object ID field name. |
| 1146 | * @param string $filter_table Lookup table name. |
| 1147 | * @param string $filter_field Lookup table object ID field name. |
| 1148 | * @param string $compare Comparison string (IN|NOT IN). |
| 1149 | * @param string $id_list Comma separated ID list. |
| 1150 | * |
| 1151 | * @return string |
| 1152 | */ |
| 1153 | protected function get_object_where_filter( $select_table, $select_field, $filter_table, $filter_field, $compare, $id_list ) { |
| 1154 | global $wpdb; |
| 1155 | if ( empty( $id_list ) ) { |
| 1156 | return ''; |
| 1157 | } |
| 1158 | |
| 1159 | $lookup_name = isset( $wpdb->$filter_table ) ? $wpdb->$filter_table : $wpdb->prefix . $filter_table; |
| 1160 | // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 1161 | return " {$select_table}.{$select_field} {$compare} ( |
| 1162 | SELECT |
| 1163 | DISTINCT {$filter_table}.{$select_field} |
| 1164 | FROM |
| 1165 | {$filter_table} |
| 1166 | WHERE |
| 1167 | {$filter_table}.{$filter_field} IN ({$id_list}) |
| 1168 | )"; |
| 1169 | // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 1170 | } |
| 1171 | |
| 1172 | /** |
| 1173 | * Returns an array of ids of allowed products, based on query arguments from the user. |
| 1174 | * |
| 1175 | * @param array $query_args Parameters supplied by the user. |
| 1176 | * @return array |
| 1177 | */ |
| 1178 | protected function get_included_products_array( $query_args ) { |
| 1179 | $included_products = array(); |
| 1180 | $operator = $this->get_match_operator( $query_args ); |
| 1181 | |
| 1182 | if ( isset( $query_args['category_includes'] ) && is_array( $query_args['category_includes'] ) && count( $query_args['category_includes'] ) > 0 ) { |
| 1183 | $included_products = $this->get_products_by_cat_ids( $query_args['category_includes'] ); |
| 1184 | |
| 1185 | // If no products were found in the specified categories, we will force an empty set |
| 1186 | // by matching a product ID of -1, unless the filters are OR/any and products are specified. |
| 1187 | if ( empty( $included_products ) ) { |
| 1188 | $included_products = array( '-1' ); |
| 1189 | } |
| 1190 | } |
| 1191 | |
| 1192 | if ( isset( $query_args['product_includes'] ) && is_array( $query_args['product_includes'] ) && count( $query_args['product_includes'] ) > 0 ) { |
| 1193 | if ( count( $included_products ) > 0 ) { |
| 1194 | if ( 'AND' === $operator ) { |
| 1195 | // AND results in an intersection between products from selected categories and manually included products. |
| 1196 | $included_products = array_intersect( $included_products, $query_args['product_includes'] ); |
| 1197 | } elseif ( 'OR' === $operator ) { |
| 1198 | // OR results in a union of products from selected categories and manually included products. |
| 1199 | $included_products = array_merge( $included_products, $query_args['product_includes'] ); |
| 1200 | } |
| 1201 | } else { |
| 1202 | $included_products = $query_args['product_includes']; |
| 1203 | } |
| 1204 | } |
| 1205 | |
| 1206 | return $included_products; |
| 1207 | } |
| 1208 | |
| 1209 | /** |
| 1210 | * Returns comma separated ids of allowed products, based on query arguments from the user. |
| 1211 | * |
| 1212 | * @param array $query_args Parameters supplied by the user. |
| 1213 | * @return string |
| 1214 | */ |
| 1215 | protected function get_included_products( $query_args ) { |
| 1216 | $included_products = $this->get_included_products_array( $query_args ); |
| 1217 | return implode( ',', $included_products ); |
| 1218 | } |
| 1219 | |
| 1220 | /** |
| 1221 | * Returns comma separated ids of allowed variations, based on query arguments from the user. |
| 1222 | * |
| 1223 | * @param array $query_args Parameters supplied by the user. |
| 1224 | * @return string |
| 1225 | */ |
| 1226 | protected function get_included_variations( $query_args ) { |
| 1227 | return $this->get_filtered_ids( $query_args, 'variation_includes' ); |
| 1228 | } |
| 1229 | |
| 1230 | /** |
| 1231 | * Returns comma separated ids of excluded variations, based on query arguments from the user. |
| 1232 | * |
| 1233 | * @param array $query_args Parameters supplied by the user. |
| 1234 | * @return string |
| 1235 | */ |
| 1236 | protected function get_excluded_variations( $query_args ) { |
| 1237 | return $this->get_filtered_ids( $query_args, 'variation_excludes' ); |
| 1238 | } |
| 1239 | |
| 1240 | /** |
| 1241 | * Returns an array of ids of disallowed products, based on query arguments from the user. |
| 1242 | * |
| 1243 | * @param array $query_args Parameters supplied by the user. |
| 1244 | * @return array |
| 1245 | */ |
| 1246 | protected function get_excluded_products_array( $query_args ) { |
| 1247 | $excluded_products = array(); |
| 1248 | $operator = $this->get_match_operator( $query_args ); |
| 1249 | |
| 1250 | if ( isset( $query_args['category_excludes'] ) && is_array( $query_args['category_excludes'] ) && count( $query_args['category_excludes'] ) > 0 ) { |
| 1251 | $excluded_products = $this->get_products_by_cat_ids( $query_args['category_excludes'] ); |
| 1252 | } |
| 1253 | |
| 1254 | if ( isset( $query_args['product_excludes'] ) && is_array( $query_args['product_excludes'] ) && count( $query_args['product_excludes'] ) > 0 ) { |
| 1255 | $excluded_products = array_merge( $excluded_products, $query_args['product_excludes'] ); |
| 1256 | } |
| 1257 | |
| 1258 | return $excluded_products; |
| 1259 | } |
| 1260 | |
| 1261 | /** |
| 1262 | * Returns comma separated ids of excluded products, based on query arguments from the user. |
| 1263 | * |
| 1264 | * @param array $query_args Parameters supplied by the user. |
| 1265 | * @return string |
| 1266 | */ |
| 1267 | protected function get_excluded_products( $query_args ) { |
| 1268 | $excluded_products = $this->get_excluded_products_array( $query_args ); |
| 1269 | return implode( ',', $excluded_products ); |
| 1270 | } |
| 1271 | |
| 1272 | /** |
| 1273 | * Returns comma separated ids of included categories, based on query arguments from the user. |
| 1274 | * |
| 1275 | * @param array $query_args Parameters supplied by the user. |
| 1276 | * @return string |
| 1277 | */ |
| 1278 | protected function get_included_categories( $query_args ) { |
| 1279 | return $this->get_filtered_ids( $query_args, 'category_includes' ); |
| 1280 | } |
| 1281 | |
| 1282 | /** |
| 1283 | * Returns comma separated ids of included coupons, based on query arguments from the user. |
| 1284 | * |
| 1285 | * @param array $query_args Parameters supplied by the user. |
| 1286 | * @param string $field Field name in the parameter list. |
| 1287 | * @return string |
| 1288 | */ |
| 1289 | protected function get_included_coupons( $query_args, $field = 'coupon_includes' ) { |
| 1290 | return $this->get_filtered_ids( $query_args, $field ); |
| 1291 | } |
| 1292 | |
| 1293 | /** |
| 1294 | * Returns comma separated ids of excluded coupons, based on query arguments from the user. |
| 1295 | * |
| 1296 | * @param array $query_args Parameters supplied by the user. |
| 1297 | * @return string |
| 1298 | */ |
| 1299 | protected function get_excluded_coupons( $query_args ) { |
| 1300 | return $this->get_filtered_ids( $query_args, 'coupon_excludes' ); |
| 1301 | } |
| 1302 | |
| 1303 | /** |
| 1304 | * Returns comma separated ids of included orders, based on query arguments from the user. |
| 1305 | * |
| 1306 | * @param array $query_args Parameters supplied by the user. |
| 1307 | * @return string |
| 1308 | */ |
| 1309 | protected function get_included_orders( $query_args ) { |
| 1310 | return $this->get_filtered_ids( $query_args, 'order_includes' ); |
| 1311 | } |
| 1312 | |
| 1313 | /** |
| 1314 | * Returns comma separated ids of excluded orders, based on query arguments from the user. |
| 1315 | * |
| 1316 | * @param array $query_args Parameters supplied by the user. |
| 1317 | * @return string |
| 1318 | */ |
| 1319 | protected function get_excluded_orders( $query_args ) { |
| 1320 | return $this->get_filtered_ids( $query_args, 'order_excludes' ); |
| 1321 | } |
| 1322 | |
| 1323 | /** |
| 1324 | * Returns comma separated ids of included users, based on query arguments from the user. |
| 1325 | * |
| 1326 | * @param array $query_args Parameters supplied by the user. |
| 1327 | * @return string |
| 1328 | */ |
| 1329 | protected function get_included_users( $query_args ) { |
| 1330 | return $this->get_filtered_ids( $query_args, 'user_includes' ); |
| 1331 | } |
| 1332 | |
| 1333 | /** |
| 1334 | * Returns comma separated ids of excluded users, based on query arguments from the user. |
| 1335 | * |
| 1336 | * @param array $query_args Parameters supplied by the user. |
| 1337 | * @return string |
| 1338 | */ |
| 1339 | protected function get_excluded_users( $query_args ) { |
| 1340 | return $this->get_filtered_ids( $query_args, 'user_excludes' ); |
| 1341 | } |
| 1342 | |
| 1343 | /** |
| 1344 | * Returns order status subquery to be used in WHERE SQL query, based on query arguments from the user. |
| 1345 | * |
| 1346 | * @param array $query_args Parameters supplied by the user. |
| 1347 | * @param string $operator AND or OR, based on match query argument. |
| 1348 | * @return string |
| 1349 | */ |
| 1350 | protected function get_status_subquery( $query_args, $operator = 'AND' ) { |
| 1351 | global $wpdb; |
| 1352 | |
| 1353 | $subqueries = array(); |
| 1354 | $excluded_statuses = array(); |
| 1355 | if ( isset( $query_args['status_is'] ) && is_array( $query_args['status_is'] ) && count( $query_args['status_is'] ) > 0 ) { |
| 1356 | $allowed_statuses = array_map( array( $this, 'normalize_order_status' ), esc_sql( $query_args['status_is'] ) ); |
| 1357 | if ( $allowed_statuses ) { |
| 1358 | $subqueries[] = "{$wpdb->prefix}wc_order_stats.status IN ( '" . implode( "','", $allowed_statuses ) . "' )"; |
| 1359 | } |
| 1360 | } |
| 1361 | |
| 1362 | if ( isset( $query_args['status_is_not'] ) && is_array( $query_args['status_is_not'] ) && count( $query_args['status_is_not'] ) > 0 ) { |
| 1363 | $excluded_statuses = array_map( array( $this, 'normalize_order_status' ), $query_args['status_is_not'] ); |
| 1364 | } |
| 1365 | |
| 1366 | if ( ( ! isset( $query_args['status_is'] ) || empty( $query_args['status_is'] ) ) |
| 1367 | && ( ! isset( $query_args['status_is_not'] ) || empty( $query_args['status_is_not'] ) ) |
| 1368 | ) { |
| 1369 | $excluded_statuses = array_map( array( $this, 'normalize_order_status' ), $this->get_excluded_report_order_statuses() ); |
| 1370 | } |
| 1371 | |
| 1372 | if ( $excluded_statuses ) { |
| 1373 | $subqueries[] = "{$wpdb->prefix}wc_order_stats.status NOT IN ( '" . implode( "','", $excluded_statuses ) . "' )"; |
| 1374 | } |
| 1375 | |
| 1376 | return implode( " $operator ", $subqueries ); |
| 1377 | } |
| 1378 | |
| 1379 | /** |
| 1380 | * Add order status SQL clauses if included in query. |
| 1381 | * |
| 1382 | * @param array $query_args Parameters supplied by the user. |
| 1383 | * @param string $table_name Database table name. |
| 1384 | * @param SqlQuery $sql_query Query object. |
| 1385 | */ |
| 1386 | protected function add_order_status_clause( $query_args, $table_name, &$sql_query ) { |
| 1387 | global $wpdb; |
| 1388 | $order_status_filter = $this->get_status_subquery( $query_args ); |
| 1389 | if ( $order_status_filter ) { |
| 1390 | $sql_query->add_sql_clause( 'join', "JOIN {$wpdb->prefix}wc_order_stats ON {$table_name}.order_id = {$wpdb->prefix}wc_order_stats.order_id" ); |
| 1391 | $sql_query->add_sql_clause( 'where', "AND ( {$order_status_filter} )" ); |
| 1392 | } |
| 1393 | } |
| 1394 | |
| 1395 | /** |
| 1396 | * Add order by SQL clause if included in query. |
| 1397 | * |
| 1398 | * @param array $query_args Parameters supplied by the user. |
| 1399 | * @param SqlQuery $sql_query Query object. |
| 1400 | * @return string Order by clause. |
| 1401 | */ |
| 1402 | protected function add_order_by_clause( $query_args, &$sql_query ) { |
| 1403 | $order_by_clause = ''; |
| 1404 | |
| 1405 | $sql_query->clear_sql_clause( array( 'order_by' ) ); |
| 1406 | if ( isset( $query_args['orderby'] ) ) { |
| 1407 | $order_by_clause = $this->normalize_order_by( esc_sql( $query_args['orderby'] ) ); |
| 1408 | $sql_query->add_sql_clause( 'order_by', $order_by_clause ); |
| 1409 | } |
| 1410 | |
| 1411 | // Return ORDER BY clause to allow adding the sort field(s) to query via a JOIN. |
| 1412 | return $order_by_clause; |
| 1413 | } |
| 1414 | |
| 1415 | /** |
| 1416 | * Add order by order SQL clause. |
| 1417 | * |
| 1418 | * @param array $query_args Parameters supplied by the user. |
| 1419 | * @param SqlQuery $sql_query Query object. |
| 1420 | */ |
| 1421 | protected function add_orderby_order_clause( $query_args, &$sql_query ) { |
| 1422 | if ( isset( $query_args['order'] ) ) { |
| 1423 | $sql_query->add_sql_clause( 'order_by', esc_sql( $query_args['order'] ) ); |
| 1424 | } else { |
| 1425 | $sql_query->add_sql_clause( 'order_by', 'DESC' ); |
| 1426 | } |
| 1427 | } |
| 1428 | |
| 1429 | /** |
| 1430 | * Returns customer subquery to be used in WHERE SQL query, based on query arguments from the user. |
| 1431 | * |
| 1432 | * @param array $query_args Parameters supplied by the user. |
| 1433 | * @return string |
| 1434 | */ |
| 1435 | protected function get_customer_subquery( $query_args ) { |
| 1436 | global $wpdb; |
| 1437 | |
| 1438 | $customer_filter = ''; |
| 1439 | if ( isset( $query_args['customer_type'] ) ) { |
| 1440 | if ( 'new' === strtolower( $query_args['customer_type'] ) ) { |
| 1441 | $customer_filter = " {$wpdb->prefix}wc_order_stats.returning_customer = 0"; |
| 1442 | } elseif ( 'returning' === strtolower( $query_args['customer_type'] ) ) { |
| 1443 | $customer_filter = " {$wpdb->prefix}wc_order_stats.returning_customer = 1"; |
| 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | return $customer_filter; |
| 1448 | } |
| 1449 | |
| 1450 | /** |
| 1451 | * Returns product attribute subquery elements used in JOIN and WHERE clauses, |
| 1452 | * based on query arguments from the user. |
| 1453 | * |
| 1454 | * @param array $query_args Parameters supplied by the user. |
| 1455 | * @return array |
| 1456 | */ |
| 1457 | protected function get_attribute_subqueries( $query_args ) { |
| 1458 | global $wpdb; |
| 1459 | |
| 1460 | $sql_clauses = array( |
| 1461 | 'join' => array(), |
| 1462 | 'where' => array(), |
| 1463 | ); |
| 1464 | $match_operator = $this->get_match_operator( $query_args ); |
| 1465 | $post_meta_comparators = array( |
| 1466 | '=' => 'attribute_is', |
| 1467 | '!=' => 'attribute_is_not', |
| 1468 | ); |
| 1469 | |
| 1470 | foreach ( $post_meta_comparators as $comparator => $arg ) { |
| 1471 | if ( ! isset( $query_args[ $arg ] ) || ! is_array( $query_args[ $arg ] ) ) { |
| 1472 | continue; |
| 1473 | } |
| 1474 | foreach ( $query_args[ $arg ] as $attribute_term ) { |
| 1475 | // We expect tuples. |
| 1476 | if ( ! is_array( $attribute_term ) || 2 !== count( $attribute_term ) ) { |
| 1477 | continue; |
| 1478 | } |
| 1479 | |
| 1480 | $term_id = ''; |
| 1481 | // If the tuple is numeric, assume these are IDs. |
| 1482 | if ( is_numeric( $attribute_term[0] ) && is_numeric( $attribute_term[1] ) ) { |
| 1483 | $attribute_id = intval( $attribute_term[0] ); |
| 1484 | $term_id = intval( $attribute_term[1] ); |
| 1485 | |
| 1486 | // Invalid IDs. |
| 1487 | if ( 0 === $attribute_id || 0 === $term_id ) { |
| 1488 | continue; |
| 1489 | } |
| 1490 | |
| 1491 | // @todo: Use wc_get_attribute () instead ? |
| 1492 | $attr_taxonomy = wc_attribute_taxonomy_name_by_id( $attribute_id ); |
| 1493 | // Invalid attribute ID. |
| 1494 | if ( empty( $attr_taxonomy ) ) { |
| 1495 | continue; |
| 1496 | } |
| 1497 | |
| 1498 | $attr_term = get_term_by( 'id', $term_id, $attr_taxonomy ); |
| 1499 | // Invalid term ID. |
| 1500 | if ( false === $attr_term ) { |
| 1501 | continue; |
| 1502 | } |
| 1503 | |
| 1504 | $meta_key = sanitize_title( $attr_taxonomy ); |
| 1505 | $meta_value = $attr_term->slug; |
| 1506 | } else { |
| 1507 | // Assume these are a custom attribute slug/value pair. |
| 1508 | $meta_key = esc_sql( $attribute_term[0] ); |
| 1509 | $meta_value = esc_sql( $attribute_term[1] ); |
| 1510 | $attr_term = get_term_by( 'slug', $meta_value, $meta_key ); |
| 1511 | if ( false !== $attr_term ) { |
| 1512 | $term_id = $attr_term->term_id; |
| 1513 | } |
| 1514 | } |
| 1515 | |
| 1516 | $join_alias = 'orderitemmeta1'; |
| 1517 | $table_to_join_on = "{$wpdb->prefix}wc_order_product_lookup"; |
| 1518 | |
| 1519 | if ( empty( $sql_clauses['join'] ) ) { |
| 1520 | $sql_clauses['join'][] = "JOIN {$wpdb->prefix}woocommerce_order_items orderitems ON orderitems.order_id = {$table_to_join_on}.order_id"; |
| 1521 | } |
| 1522 | |
| 1523 | // If we're matching all filters (AND), we'll need multiple JOINs on postmeta. |
| 1524 | // If not, just one. |
| 1525 | if ( 'AND' === $match_operator || 1 === count( $sql_clauses['join'] ) ) { |
| 1526 | $join_idx = count( $sql_clauses['join'] ); |
| 1527 | $join_alias = 'orderitemmeta' . $join_idx; |
| 1528 | $sql_clauses['join'][] = "JOIN {$wpdb->prefix}woocommerce_order_itemmeta as {$join_alias} ON {$join_alias}.order_item_id = {$table_to_join_on}.order_item_id"; |
| 1529 | } |
| 1530 | |
| 1531 | $in_comparator = '=' === $comparator ? 'in' : 'not in'; |
| 1532 | |
| 1533 | // Add subquery for products ordered using attributes not used in variations. |
| 1534 | $term_attribute_subquery = "select product_id from {$wpdb->prefix}wc_product_attributes_lookup where is_variation_attribute=0 and term_id = %s"; |
| 1535 | // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 1536 | // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber |
| 1537 | $sql_clauses['where'][] = $wpdb->prepare( |
| 1538 | " |
| 1539 | ( ( {$join_alias}.meta_key = %s AND {$join_alias}.meta_value {$comparator} %s ) or ( |
| 1540 | {$wpdb->prefix}wc_order_product_lookup.variation_id = 0 and {$wpdb->prefix}wc_order_product_lookup.product_id {$in_comparator} ({$term_attribute_subquery}) |
| 1541 | ) )", |
| 1542 | $meta_key, |
| 1543 | $meta_value, |
| 1544 | $term_id, |
| 1545 | ); |
| 1546 | // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 1547 | // phpcs:enable WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber |
| 1548 | } |
| 1549 | } |
| 1550 | |
| 1551 | // If we're matching multiple attributes and all filters (AND), make sure |
| 1552 | // we're matching attributes on the same product. |
| 1553 | $num_attribute_filters = count( $sql_clauses['join'] ); |
| 1554 | |
| 1555 | for ( $i = 2; $i < $num_attribute_filters; $i++ ) { |
| 1556 | $join_alias = 'orderitemmeta' . $i; |
| 1557 | $sql_clauses['join'][] = "AND orderitemmeta1.order_item_id = {$join_alias}.order_item_id"; |
| 1558 | } |
| 1559 | |
| 1560 | return $sql_clauses; |
| 1561 | } |
| 1562 | |
| 1563 | /** |
| 1564 | * Returns logic operator for WHERE subclause based on 'match' query argument. |
| 1565 | * |
| 1566 | * @param array $query_args Parameters supplied by the user. |
| 1567 | * @return string |
| 1568 | */ |
| 1569 | protected function get_match_operator( $query_args ) { |
| 1570 | $operator = 'AND'; |
| 1571 | |
| 1572 | if ( ! isset( $query_args['match'] ) ) { |
| 1573 | return $operator; |
| 1574 | } |
| 1575 | |
| 1576 | if ( 'all' === strtolower( $query_args['match'] ) ) { |
| 1577 | $operator = 'AND'; |
| 1578 | } elseif ( 'any' === strtolower( $query_args['match'] ) ) { |
| 1579 | $operator = 'OR'; |
| 1580 | } |
| 1581 | return $operator; |
| 1582 | } |
| 1583 | |
| 1584 | /** |
| 1585 | * Returns filtered comma separated ids, based on query arguments from the user. |
| 1586 | * |
| 1587 | * @param array $query_args Parameters supplied by the user. |
| 1588 | * @param string $field Query field to filter. |
| 1589 | * @param string $separator Field separator. |
| 1590 | * @return string |
| 1591 | */ |
| 1592 | protected function get_filtered_ids( $query_args, $field, $separator = ',' ) { |
| 1593 | global $wpdb; |
| 1594 | |
| 1595 | $ids_str = ''; |
| 1596 | $ids = isset( $query_args[ $field ] ) && is_array( $query_args[ $field ] ) ? $query_args[ $field ] : array(); |
| 1597 | |
| 1598 | /** |
| 1599 | * Filter the IDs before retrieving report data. |
| 1600 | * |
| 1601 | * Allows filtering of the objects included or excluded from reports. |
| 1602 | * |
| 1603 | * @param array $ids List of object Ids. |
| 1604 | * @param array $query_args The original arguments for the request. |
| 1605 | * @param string $field The object type. |
| 1606 | * @param string $context The data store context. |
| 1607 | */ |
| 1608 | $ids = apply_filters( 'woocommerce_analytics_' . $field, $ids, $query_args, $field, $this->context ); |
| 1609 | |
| 1610 | if ( ! empty( $ids ) ) { |
| 1611 | $placeholders = implode( $separator, array_fill( 0, count( $ids ), '%d' ) ); |
| 1612 | /* phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared */ |
| 1613 | $ids_str = $wpdb->prepare( "{$placeholders}", $ids ); |
| 1614 | /* phpcs:enable */ |
| 1615 | } |
| 1616 | return $ids_str; |
| 1617 | } |
| 1618 | |
| 1619 | /** |
| 1620 | * Assign report columns once full table name has been assigned. |
| 1621 | */ |
| 1622 | protected function assign_report_columns() {} |
| 1623 | } |
| 1624 |