/var/www/html_us/wp-content/plugins/woocommerce/src/Admin/API/Reports/Downloads/DataStore.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
/**
 * API\Reports\Downloads\DataStore class file.
 */

namespace Automattic\WooCommerce\Admin\API\Reports\Downloads;

defined'ABSPATH' ) || exit;

use 
Automattic\WooCommerce\Admin\API\Reports\DataStore as ReportsDataStore;
use 
Automattic\WooCommerce\Admin\API\Reports\DataStoreInterface;
use 
Automattic\WooCommerce\Admin\API\Reports\TimeInterval;
use 
Automattic\WooCommerce\Admin\API\Reports\SqlQuery;

/**
 * API\Reports\Downloads\DataStore.
 */
class DataStore extends ReportsDataStore implements DataStoreInterface {

    
/**
     * Table used to get the data.
     *
     * @override ReportsDataStore::$table_name
     *
     * @var string
     */
    
protected static $table_name 'wc_download_log';

    
/**
     * Cache identifier.
     *
     * @override ReportsDataStore::$cache_key
     *
     * @var string
     */
    
protected $cache_key 'downloads';

    
/**
     * Mapping columns to data type to return correct response types.
     *
     * @override ReportsDataStore::$column_types
     *
     * @var array
     */
    
protected $column_types = array(
        
'id'          => 'intval',
        
'date'        => 'strval',
        
'date_gmt'    => 'strval',
        
'download_id' => 'strval'// String because this can sometimes be a hash.
        
'file_name'   => 'strval',
        
'product_id'  => 'intval',
        
'order_id'    => 'intval',
        
'user_id'     => 'intval',
        
'ip_address'  => 'strval',
    );

    
/**
     * Data store context used to pass to filters.
     *
     * @override ReportsDataStore::$context
     *
     * @var string
     */
    
protected $context 'downloads';

    
/**
     * Assign report columns once full table name has been assigned.
     *
     * @override ReportsDataStore::assign_report_columns()
     */
    
protected function assign_report_columns() {
        
$this->report_columns = array(
            
'id'          => 'download_log_id as id',
            
'date'        => 'timestamp as date_gmt',
            
'download_id' => 'product_permissions.download_id',
            
'product_id'  => 'product_permissions.product_id',
            
'order_id'    => 'product_permissions.order_id',
            
'user_id'     => 'product_permissions.user_id',
            
'ip_address'  => 'user_ip_address as ip_address',
        );
    }

    
/**
     * Updates the database query with parameters used for downloads report.
     *
     * @param array $query_args Query arguments supplied by the user.
     */
    
protected function add_sql_query_params$query_args ) {
        global 
$wpdb;

        
$lookup_table     self::get_db_table_name();
        
$permission_table $wpdb->prefix 'woocommerce_downloadable_product_permissions';
        
$operator         $this->get_match_operator$query_args );
        
$where_filters    = array();
        
$join             "JOIN {$permission_table} as product_permissions ON {$lookup_table}.permission_id = product_permissions.permission_id";

        
$where_time $this->add_time_period_sql_params$query_args$lookup_table );
        if ( 
$where_time ) {
            if ( isset( 
$this->subquery ) ) {
                
$this->subquery->add_sql_clause'where_time'$where_time );
            } else {
                
$this->interval_query->add_sql_clause'where_time'$where_time );
            }
        }
        
$this->get_limit_sql_params$query_args );

        
$where_filters[] = $this->get_object_where_filter(
            
$lookup_table,
            
'permission_id',
            
$permission_table,
            
'product_id',
            
'IN',
            
$this->get_included_products$query_args )
        );
        
$where_filters[] = $this->get_object_where_filter(
            
$lookup_table,
            
'permission_id',
            
$permission_table,
            
'product_id',
            
'NOT IN',
            
$this->get_excluded_products$query_args )
        );
        
$where_filters[] = $this->get_object_where_filter(
            
$lookup_table,
            
'permission_id',
            
$permission_table,
            
'order_id',
            
'IN',
            
$this->get_included_orders$query_args )
        );
        
$where_filters[] = $this->get_object_where_filter(
            
$lookup_table,
            
'permission_id',
            
$permission_table,
            
'order_id',
            
'NOT IN',
            
$this->get_excluded_orders$query_args )
        );

        
$customer_lookup_table $wpdb->prefix 'wc_customer_lookup';
        
$customer_lookup       "SELECT {$customer_lookup_table}.user_id FROM {$customer_lookup_table} WHERE {$customer_lookup_table}.customer_id IN (%s)";
        
$included_customers    $this->get_included_customers$query_args );
        
$excluded_customers    $this->get_excluded_customers$query_args );
        if ( 
$included_customers ) {
            
$where_filters[] = $this->get_object_where_filter(
                
$lookup_table,
                
'permission_id',
                
$permission_table,
                
'user_id',
                
'IN',
                
sprintf$customer_lookup$included_customers )
            );
        }

        if ( 
$excluded_customers ) {
            
$where_filters[] = $this->get_object_where_filter(
                
$lookup_table,
                
'permission_id',
                
$permission_table,
                
'user_id',
                
'NOT IN',
                
sprintf$customer_lookup$excluded_customers )
            );
        }

        
$included_ip_addresses $this->get_included_ip_addresses$query_args );
        
$excluded_ip_addresses $this->get_excluded_ip_addresses$query_args );
        if ( 
$included_ip_addresses ) {
            
$where_filters[] = "{$lookup_table}.user_ip_address IN ('{$included_ip_addresses}')";
        }

        if ( 
$excluded_ip_addresses ) {
            
$where_filters[] = "{$lookup_table}.user_ip_address NOT IN ('{$excluded_ip_addresses}')";
        }

        
$where_filters   array_filter$where_filters );
        
$where_subclause implode$operator "$where_filters );
        if ( 
$where_subclause ) {
            if ( isset( 
$this->subquery ) ) {
                
$this->subquery->add_sql_clause'where'"AND ( $where_subclause )" );
            } else {
                
$this->interval_query->add_sql_clause'where'"AND ( $where_subclause )" );
            }
        }

        if ( isset( 
$this->subquery ) ) {
            
$this->subquery->add_sql_clause'join'$join );
        } else {
            
$this->interval_query->add_sql_clause'join'$join );
        }
        
$this->add_order_by$query_args );
    }

    
/**
     * Returns comma separated ids of included ip address, based on query arguments from the user.
     *
     * @param array $query_args Parameters supplied by the user.
     * @return string
     */
    
protected function get_included_ip_addresses$query_args ) {
        return 
$this->get_filtered_ip_addresses$query_args'ip_address_includes' );
    }

    
/**
     * Returns comma separated ids of excluded ip address, based on query arguments from the user.
     *
     * @param array $query_args Parameters supplied by the user.
     * @return string
     */
    
protected function get_excluded_ip_addresses$query_args ) {
        return 
$this->get_filtered_ip_addresses$query_args'ip_address_excludes' );
    }

    
/**
     * Returns filtered comma separated ids, based on query arguments from the user.
     *
     * @param array  $query_args  Parameters supplied by the user.
     * @param string $field       Query field to filter.
     * @return string
     */
    
protected function get_filtered_ip_addresses$query_args$field ) {
        if ( isset( 
$query_args$field ] ) && is_array$query_args$field ] ) && count$query_args$field ] ) > ) {
            
$ip_addresses array_map'esc_sql'$query_args$field ] );

            
/**
             * Filter the IDs before retrieving report data.
             *
             * Allows filtering of the objects included or excluded from reports.
             *
             * @param array  $ids        List of object Ids.
             * @param array  $query_args The original arguments for the request.
             * @param string $field      The object type.
             * @param string $context    The data store context.
             */
            
$ip_addresses apply_filters'woocommerce_analytics_' $field$ip_addresses$query_args$field$this->context );

            return 
implode"','"$ip_addresses );
        }
        return 
'';
    }

    
/**
     * Returns comma separated ids of included customers, based on query arguments from the user.
     *
     * @param array $query_args Parameters supplied by the user.
     * @return string
     */
    
protected function get_included_customers$query_args ) {
        return 
self::get_filtered_ids$query_args'customer_includes' );
    }

    
/**
     * Returns comma separated ids of excluded customers, based on query arguments from the user.
     *
     * @param array $query_args Parameters supplied by the user.
     * @return string
     */
    
protected function get_excluded_customers$query_args ) {
        return 
self::get_filtered_ids$query_args'customer_excludes' );
    }

    
/**
     * Gets WHERE time clause of SQL request with date-related constraints.
     *
     * @override ReportsDataStore::add_time_period_sql_params()
     *
     * @param array  $query_args Parameters supplied by the user.
     * @param string $table_name Name of the db table relevant for the date constraint.
     * @return string
     */
    
protected function add_time_period_sql_params$query_args$table_name ) {
        
$where_time '';
        if ( 
$query_args['before'] ) {
            
$datetime_str $query_args['before']->formatTimeInterval::$sql_datetime_format );
            
$where_time  .= " AND {$table_name}.timestamp <= '$datetime_str'";

        }

        if ( 
$query_args['after'] ) {
            
$datetime_str $query_args['after']->formatTimeInterval::$sql_datetime_format );
            
$where_time  .= " AND {$table_name}.timestamp >= '$datetime_str'";
        }

        return 
$where_time;
    }

    
/**
     * Fills ORDER BY clause of SQL request based on user supplied parameters.
     *
     * @param array $query_args Parameters supplied by the user.
     */
    
protected function add_order_by$query_args ) {
        global 
$wpdb;
        
$this->clear_sql_clause'order_by' );
        
$order_by '';
        if ( isset( 
$query_args['orderby'] ) ) {
            
$order_by $this->normalize_order_byesc_sql$query_args['orderby'] ) );
            
$this->add_sql_clause'order_by'$order_by );
        }

        if ( 
false !== strpos$order_by'_products' ) ) {
            
$this->subquery->add_sql_clause'join'"JOIN {$wpdb->posts} AS _products ON product_permissions.product_id = _products.ID" );
        }

        
$this->add_orderby_order_clause$query_args$this );
    }

    
/**
     * Get the default query arguments to be used by get_data().
     * These defaults are only partially applied when used via REST API, as that has its own defaults.
     *
     * @override ReportsDataStore::get_default_query_vars()
     *
     * @return array Query parameters.
     */
    
public function get_default_query_vars() {
        
$defaults            parent::get_default_query_vars();
        
$defaults['orderby'] = 'timestamp';

        return 
$defaults;
    }

    
/**
     * Returns the report data based on normalized parameters.
     * Will be called by `get_data` if there is no data in cache.
     *
     * @override ReportsDataStore::get_noncached_data()
     *
     * @see get_data
     * @param array $query_args Query parameters.
     * @return stdClass|WP_Error Data object `{ totals: *, intervals: array, total: int, pages: int, page_no: int }`, or error.
     */
    
public function get_noncached_data$query_args ) {
        global 
$wpdb;

        
$this->initialize_queries();

        
$data = (object) array(
            
'data'    => array(),
            
'total'   => 0,
            
'pages'   => 0,
            
'page_no' => 0,
        );

        
$selections $this->selected_columns$query_args );
        
$this->add_sql_query_params$query_args );

        
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
$db_records_count = (int) $wpdb->get_var(
            
"SELECT COUNT(*) FROM (
                
{$this->subquery->get_query_statement()}
            ) AS tt"
        
);
        
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        
$params      $this->get_limit_params$query_args );
        
$total_pages = (int) ceil$db_records_count $params['per_page'] );
        if ( 
$query_args['page'] < || $query_args['page'] > $total_pages ) {
            return 
$data;
        }

        
$this->subquery->clear_sql_clause'select' );
        
$this->subquery->add_sql_clause'select'$selections );
        
$this->subquery->add_sql_clause'order_by'$this->get_sql_clause'order_by' ) );
        
$this->subquery->add_sql_clause'limit'$this->get_sql_clause'limit' ) );

        
$download_data $wpdb->get_results(
            
$this->subquery->get_query_statement(), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            
ARRAY_A
        
);

        if ( 
null === $download_data ) {
            return 
$data;
        }

        
$download_data array_map( array( $this'cast_numbers' ), $download_data );
        
$data          = (object) array(
            
'data'    => $download_data,
            
'total'   => $db_records_count,
            
'pages'   => $total_pages,
            
'page_no' => (int) $query_args['page'],
        );

        return 
$data;
    }

    
/**
     * Maps ordering specified by the user to columns in the database/fields in the data.
     *
     * @override ReportsDataStore::normalize_order_by()
     *
     * @param string $order_by Sorting criterion.
     * @return string
     */
    
protected function normalize_order_by$order_by ) {
        global 
$wpdb;

        if ( 
'date' === $order_by ) {
            return 
$wpdb->prefix 'wc_download_log.timestamp';
        }

        if ( 
'product' === $order_by ) {
            return 
'_products.post_title';
        }

        return 
$order_by;
    }

    
/**
     * Initialize query objects.
     */
    
protected function initialize_queries() {
        
$this->clear_all_clauses();
        
$table_name     self::get_db_table_name();
        
$this->subquery = new SqlQuery$this->context '_subquery' );
        
$this->subquery->add_sql_clause'from'$table_name );
        
$this->subquery->add_sql_clause'select'"{$table_name}.download_log_id" );
        
$this->subquery->add_sql_clause'group_by'"{$table_name}.download_log_id" );
    }
}