} elseif ( ! array_key_exists( $time_id, $db_intervals ) ) {
// For intervals present in the db outside of this time frame, do nothing.
// For intervals not present in the db, fabricate it.
$record_arr['time_interval'] = $time_id;
$record_arr['date_start'] = $start_datetime->format( 'Y-m-d H:i:s' );
$record_arr['date_end'] = $interval_end;
$data->intervals[] = array_merge( $record_arr, $totals_arr );
$start_datetime = $next_start;
* Converts input datetime parameters to local timezone. If there are no inputs from the user in query_args,
* uses default from $defaults.
* @param array $query_args Array of query arguments.
* @param array $defaults Array of default values.
protected function normalize_timezones( &$query_args, $defaults ) {
$local_tz = new \DateTimeZone( wc_timezone_string() );
foreach ( array( 'before', 'after' ) as $query_arg_key ) {
if ( isset( $query_args[ $query_arg_key ] ) && is_string( $query_args[ $query_arg_key ] ) ) {
// Assume that unspecified timezone is a local timezone.
$datetime = new \DateTime( $query_args[ $query_arg_key ], $local_tz );
// In case timezone was forced by using +HH:MM, convert to local timezone.
$datetime->setTimezone( $local_tz );
$query_args[ $query_arg_key ] = $datetime;
} elseif ( isset( $query_args[ $query_arg_key ] ) && is_a( $query_args[ $query_arg_key ], 'DateTime' ) ) {
// In case timezone is in other timezone, convert to local timezone.
$query_args[ $query_arg_key ]->setTimezone( $local_tz );
$query_args[ $query_arg_key ] = isset( $defaults[ $query_arg_key ] ) ? $defaults[ $query_arg_key ] : null;
* Removes extra records from intervals so that only requested number of records get returned.
* @param stdClass $data Data from whose intervals the records get removed.
* @param int $page_no Offset requested by the user.
* @param int $items_per_page Number of records requested by the user.
* @param int $db_interval_count Database interval count.
* @param int $expected_interval_count Expected interval count on the output.
* @param string $order_by Order by field.
* @param string $order ASC or DESC.
protected function remove_extra_records( &$data, $page_no, $items_per_page, $db_interval_count, $expected_interval_count, $order_by, $order ) {
if ( 'date' === strtolower( $order_by ) ) {
if ( 'asc' === strtolower( $order ) ) {
$offset = ( $page_no - 1 ) * $items_per_page;
$offset = ( $page_no - 1 ) * $items_per_page - $db_interval_count;
$offset = $offset < 0 ? 0 : $offset;
$count = $expected_interval_count - ( $page_no - 1 ) * $items_per_page;
} elseif ( $count > $items_per_page ) {
$count = $items_per_page;
$data->intervals = array_slice( $data->intervals, $offset, $count );
* Returns expected number of items on the page in case of date ordering.
* @param int $expected_interval_count Expected number of intervals in total.
* @param int $items_per_page Number of items per page.
* @param int $page_no Page number.
protected function expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no ) {
$total_pages = (int) ceil( $expected_interval_count / $items_per_page );
if ( $page_no < $total_pages ) {
} elseif ( $page_no === $total_pages ) {
return $expected_interval_count - ( $page_no - 1 ) * $items_per_page;
* Returns true if there are any intervals that need to be filled in the response.
* @param int $expected_interval_count Expected number of intervals in total.
* @param int $db_records Total number of records for given period in the database.
* @param int $items_per_page Number of items per page.
* @param int $page_no Page number.
* @param string $order asc or desc.
* @param string $order_by Column by which the result will be sorted.
* @param int $intervals_count Number of records for given (possibly shortened) time interval.
protected function intervals_missing( $expected_interval_count, $db_records, $items_per_page, $page_no, $order, $order_by, $intervals_count ) {
if ( $expected_interval_count <= $db_records ) {
if ( 'date' === $order_by ) {
$expected_intervals_on_page = $this->expected_intervals_on_page( $expected_interval_count, $items_per_page, $page_no );
return $intervals_count < $expected_intervals_on_page;
if ( 'desc' === $order ) {
return $page_no > floor( $db_records / $items_per_page );
if ( 'asc' === $order ) {
return $page_no <= ceil( ( $expected_interval_count - $db_records ) / $items_per_page );
* Updates the LIMIT query part for Intervals query of the report.
* If there are less records in the database than time intervals, then we need to remap offset in SQL query
* to fetch correct records.
* @param array $query_args Query arguments.
* @param int $db_interval_count Database interval count.
* @param int $expected_interval_count Expected interval count on the output.
* @param string $table_name Name of the db table relevant for the date constraint.
protected function update_intervals_sql_params( &$query_args, $db_interval_count, $expected_interval_count, $table_name ) {
if ( $db_interval_count === $expected_interval_count ) {
$params = $this->get_limit_params( $query_args );
$local_tz = new \DateTimeZone( wc_timezone_string() );
if ( 'date' === strtolower( $query_args['orderby'] ) ) {
// page X in request translates to slightly different dates in the db, in case some
// records are missing from the db.
if ( 'asc' === strtolower( $query_args['order'] ) ) {
$new_start_date = $query_args['after'];
$intervals_to_skip = ( $query_args['page'] - 1 ) * $params['per_page'];
$latest_end_date = $query_args['before'];
for ( $i = 0; $i < $intervals_to_skip; $i++ ) {
if ( $new_start_date > $latest_end_date ) {
$new_start_date = $latest_end_date;
$new_start_date = TimeInterval::iterate( $new_start_date, $query_args['interval'] );
$new_end_date = clone $new_start_date;
for ( $i = 0; $i < $params['per_page']; $i++ ) {
if ( $new_end_date > $latest_end_date ) {
$new_end_date = TimeInterval::iterate( $new_end_date, $query_args['interval'] );
if ( $new_end_date > $latest_end_date ) {
$new_end_date = $latest_end_date;
$new_end_date_timestamp = (int) $new_end_date->format( 'U' ) - 1;
$new_end_date->setTimestamp( $new_end_date_timestamp );
$new_end_date = $query_args['before'];
$intervals_to_skip = ( $query_args['page'] - 1 ) * $params['per_page'];
$earliest_start_date = $query_args['after'];
for ( $i = 0; $i < $intervals_to_skip; $i++ ) {
if ( $new_end_date < $earliest_start_date ) {
$new_end_date = $earliest_start_date;
$new_end_date = TimeInterval::iterate( $new_end_date, $query_args['interval'], true );
$new_start_date = clone $new_end_date;
for ( $i = 0; $i < $params['per_page']; $i++ ) {
if ( $new_start_date < $earliest_start_date ) {
$new_start_date = TimeInterval::iterate( $new_start_date, $query_args['interval'], true );
if ( $new_start_date < $earliest_start_date ) {
$new_start_date = $earliest_start_date;
if ( $start_iteration ) {
// @todo Is this correct? should it only be added if iterate runs? other two iterate instances, too?
$new_start_date_timestamp = (int) $new_start_date->format( 'U' ) + 1;
$new_start_date->setTimestamp( $new_start_date_timestamp );
// @todo - Do this without modifying $query_args?
$query_args['adj_after'] = $new_start_date;
$query_args['adj_before'] = $new_end_date;
$adj_after = $new_start_date->format( TimeInterval::$sql_datetime_format );
$adj_before = $new_end_date->format( TimeInterval::$sql_datetime_format );
$this->interval_query->clear_sql_clause( array( 'where_time', 'limit' ) );
$this->interval_query->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` <= '$adj_before'" );
$this->interval_query->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` >= '$adj_after'" );
$this->clear_sql_clause( 'limit' );
$this->add_sql_clause( 'limit', 'LIMIT 0,' . $params['per_page'] );
if ( 'asc' === $query_args['order'] ) {
$offset = ( ( $query_args['page'] - 1 ) * $params['per_page'] ) - ( $expected_interval_count - $db_interval_count );
$offset = $offset < 0 ? 0 : $offset;
$count = $query_args['page'] * $params['per_page'] - ( $expected_interval_count - $db_interval_count );
} elseif ( $count > $params['per_page'] ) {
$count = $params['per_page'];
$this->clear_sql_clause( 'limit' );
$this->add_sql_clause( 'limit', 'LIMIT ' . $offset . ',' . $count );
// Otherwise no change in limit clause.
// @todo - Do this without modifying $query_args?
$query_args['adj_after'] = $query_args['after'];
$query_args['adj_before'] = $query_args['before'];
* Casts strings returned from the database to appropriate data types for output.
* @param array $array Associative array of values extracted from the database.
protected function cast_numbers( $array ) {
$retyped_array = array();
$column_types = apply_filters( 'woocommerce_rest_reports_column_types', $this->column_types, $array );
foreach ( $array as $column_name => $value ) {
if ( is_array( $value ) ) {
$value = $this->cast_numbers( $value );
if ( isset( $column_types[ $column_name ] ) ) {
$retyped_array[ $column_name ] = $column_types[ $column_name ]( $value );
$retyped_array[ $column_name ] = $value;
* Returns a list of columns selected by the query_args formatted as a comma separated string.
* @param array $query_args User-supplied options.
protected function selected_columns( $query_args ) {
$selections = $this->report_columns;
if ( isset( $query_args['fields'] ) && is_array( $query_args['fields'] ) ) {
foreach ( $query_args['fields'] as $field ) {
if ( isset( $selections[ $field ] ) ) {
$keep[ $field ] = $selections[ $field ];
$selections = implode( ', ', $keep );
$selections = implode( ', ', $selections );
* Get the excluded order statuses used when calculating reports.
protected static function get_excluded_report_order_statuses() {
$excluded_statuses = \WC_Admin_Settings::get_option( 'woocommerce_excluded_report_order_statuses', array( 'pending', 'failed', 'cancelled' ) );
$excluded_statuses = array_merge( array( 'auto-draft', 'trash' ), array_map( 'esc_sql', $excluded_statuses ) );
return apply_filters( 'woocommerce_analytics_excluded_order_statuses', $excluded_statuses );
* Maps order status provided by the user to the one used in the database.
* @param string $status Order status.
protected static function normalize_order_status( $status ) {
$status = trim( $status );
* Normalizes order_by clause to match to SQL query.
* @param string $order_by Order by option requested by user.
protected function normalize_order_by( $order_by ) {
if ( 'date' === $order_by ) {
* Updates start and end dates for intervals so that they represent intervals' borders, not times when data in db were recorded.
* E.g. if there are db records for only Tuesday and Thursday this week, the actual week interval is [Mon, Sun], not [Tue, Thu].
* @param DateTime $start_datetime Start date.
* @param DateTime $end_datetime End date.
* @param string $time_interval Time interval, e.g. day, week, month.
* @param array $intervals Array of intervals extracted from SQL db.
protected function update_interval_boundary_dates( $start_datetime, $end_datetime, $time_interval, &$intervals ) {
$local_tz = new \DateTimeZone( wc_timezone_string() );
foreach ( $intervals as $key => $interval ) {
$datetime = new \DateTime( $interval['datetime_anchor'], $local_tz );
$prev_start = TimeInterval::iterate( $datetime, $time_interval, true );
// @todo Not sure if the +1/-1 here are correct, especially as they are applied before the ?: below.
$prev_start_timestamp = (int) $prev_start->format( 'U' ) + 1;
$prev_start->setTimestamp( $prev_start_timestamp );
$date_start = $prev_start < $start_datetime ? $start_datetime : $prev_start;
$intervals[ $key ]['date_start'] = $date_start->format( 'Y-m-d H:i:s' );
$intervals[ $key ]['date_start'] = $prev_start->format( 'Y-m-d H:i:s' );
$next_end = TimeInterval::iterate( $datetime, $time_interval );
$next_end_timestamp = (int) $next_end->format( 'U' ) - 1;
$next_end->setTimestamp( $next_end_timestamp );
$date_end = $next_end > $end_datetime ? $end_datetime : $next_end;
$intervals[ $key ]['date_end'] = $date_end->format( 'Y-m-d H:i:s' );
$intervals[ $key ]['date_end'] = $next_end->format( 'Y-m-d H:i:s' );
$intervals[ $key ]['interval'] = $time_interval;
* Change structure of intervals to form a correct response.
* Also converts local datetimes to GMT and adds them to the intervals.
* @param array $intervals Time interval, e.g. day, week, month.
protected function create_interval_subtotals( &$intervals ) {
foreach ( $intervals as $key => $interval ) {
$start_gmt = TimeInterval::convert_local_datetime_to_gmt( $interval['date_start'] );
$end_gmt = TimeInterval::convert_local_datetime_to_gmt( $interval['date_end'] );
// Move intervals result to subtotals object.
$intervals[ $key ] = array(
'interval' => $interval['time_interval'],
'date_start' => $interval['date_start'],
'date_start_gmt' => $start_gmt->format( TimeInterval::$sql_datetime_format ),
'date_end' => $interval['date_end'],
'date_end_gmt' => $end_gmt->format( TimeInterval::$sql_datetime_format ),
unset( $interval['interval'] );
unset( $interval['date_start'] );
unset( $interval['date_end'] );
unset( $interval['datetime_anchor'] );
unset( $interval['time_interval'] );
$intervals[ $key ]['subtotals'] = (object) $this->cast_numbers( $interval );
* Fills WHERE clause of SQL request with date-related constraints.
* @param array $query_args Parameters supplied by the user.
* @param string $table_name Name of the db table relevant for the date constraint.
protected function add_time_period_sql_params( $query_args, $table_name ) {
$this->clear_sql_clause( array( 'from', 'where_time', 'where' ) );
if ( isset( $this->subquery ) ) {
$this->subquery->clear_sql_clause( 'where_time' );
if ( isset( $query_args['before'] ) && '' !== $query_args['before'] ) {
if ( is_a( $query_args['before'], 'WC_DateTime' ) ) {
$datetime_str = $query_args['before']->date( TimeInterval::$sql_datetime_format );
$datetime_str = $query_args['before']->format( TimeInterval::$sql_datetime_format );
if ( isset( $this->subquery ) ) {
$this->subquery->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` <= '$datetime_str'" );
$this->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` <= '$datetime_str'" );
if ( isset( $query_args['after'] ) && '' !== $query_args['after'] ) {
if ( is_a( $query_args['after'], 'WC_DateTime' ) ) {
$datetime_str = $query_args['after']->date( TimeInterval::$sql_datetime_format );
$datetime_str = $query_args['after']->format( TimeInterval::$sql_datetime_format );
if ( isset( $this->subquery ) ) {
$this->subquery->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` >= '$datetime_str'" );
$this->add_sql_clause( 'where_time', "AND {$table_name}.`{$this->date_column_name}` >= '$datetime_str'" );
* Fills LIMIT clause of SQL request based on user supplied parameters.
* @param array $query_args Parameters supplied by the user.
protected function get_limit_sql_params( $query_args ) {
$params = $this->get_limit_params( $query_args );
$this->clear_sql_clause( 'limit' );
$this->add_sql_clause( 'limit', $wpdb->prepare( 'LIMIT %d, %d', $params['offset'], $params['per_page'] ) );
* Fills LIMIT parameters of SQL request based on user supplied parameters.
* @param array $query_args Parameters supplied by the user.
protected function get_limit_params( $query_args = array() ) {
if ( isset( $query_args['per_page'] ) && is_numeric( $query_args['per_page'] ) ) {
$this->limit_parameters['per_page'] = (int) $query_args['per_page'];
$this->limit_parameters['per_page'] = get_option( 'posts_per_page' );
$this->limit_parameters['offset'] = 0;
if ( isset( $query_args['page'] ) ) {
$this->limit_parameters['offset'] = ( (int) $query_args['page'] - 1 ) * $this->limit_parameters['per_page'];
return $this->limit_parameters;
* Generates a virtual table given a list of IDs.
* @param array $ids Array of IDs.
* @param array $id_field Name of the ID field.
* @param array $other_values Other values that must be contained in the virtual table.
protected function get_ids_table( $ids, $id_field, $other_values = array() ) {
foreach ( $ids as $id ) {
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$new_select = $wpdb->prepare( "SELECT %s AS {$id_field}", $id );
foreach ( $other_values as $key => $value ) {
$new_select .= $wpdb->prepare( ", %s AS {$key}", $value );
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
array_push( $selects, $new_select );
return join( ' UNION ', $selects );
* Returns a comma separated list of the fields in the `query_args`, if there aren't, returns `report_columns` keys.
* @param array $query_args Parameters supplied by the user.
protected function get_fields( $query_args ) {
if ( isset( $query_args['fields'] ) && is_array( $query_args['fields'] ) ) {
return $query_args['fields'];
return array_keys( $this->report_columns );