Welcome to mirror list, hosted at ThFree Co, Russian Federation.

API.php « Actions « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b40afb87e20e41f1983fc9db7bfafe5d8a438b2d (plain)
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik_Plugins
 * @package Piwik_Actions
 */
use Piwik\Archive;
use Piwik\Metrics;
use Piwik\Piwik;
use Piwik\Common;
use Piwik\Date;
use Piwik\DataTable;

/**
 * The Actions API lets you request reports for all your Visitor Actions: Page URLs, Page titles (Piwik Events),
 * File Downloads and Clicks on external websites.
 *
 * For example, "getPageTitles" will return all your page titles along with standard <a href='http://piwik.org/docs/analytics-api/reference/#toc-metric-definitions' target='_blank'>Actions metrics</a> for each row.
 *
 * It is also possible to request data for a specific Page Title with "getPageTitle"
 * and setting the parameter pageName to the page title you wish to request.
 * Similarly, you can request metrics for a given Page URL via "getPageUrl", a Download file via "getDownload"
 * and an outlink via "getOutlink".
 *
 * Note: pageName, pageUrl, outlinkUrl, downloadUrl parameters must be URL encoded before you call the API.
 * @package Piwik_Actions
 */
class Piwik_Actions_API
{
    static private $instance = null;

    /**
     * @return Piwik_Actions_API
     */
    static public function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     * Returns the list of metrics (pages, downloads, outlinks)
     *
     * @param int $idSite
     * @param string $period
     * @param string $date
     * @param bool|string $segment
     * @param bool|array $columns
     * @return DataTable
     */
    public function get($idSite, $period, $date, $segment = false, $columns = false)
    {
        Piwik::checkUserHasViewAccess($idSite);
        $archive = Archive::build($idSite, $period, $date, $segment);

        $metrics = Piwik_Actions_Archiver::$actionsAggregateMetrics;
        $metrics['Actions_avg_time_generation'] = 'avg_time_generation';

        // get requested columns
        $columns = Piwik::getArrayFromApiParameter($columns);
        if (!empty($columns)) {
            // get the columns that are available and requested
            $columns = array_intersect($columns, array_values($metrics));
            $columns = array_values($columns); // make sure indexes are right
            $nameReplace = array();
            foreach ($columns as $i => $column) {
                $fullColumn = array_search($column, $metrics);
                $columns[$i] = $fullColumn;
                $nameReplace[$fullColumn] = $column;
            }

            if (false !== ($avgGenerationTimeRequested = array_search('Actions_avg_time_generation', $columns))) {
                unset($columns[$avgGenerationTimeRequested]);
                $avgGenerationTimeRequested = true;
            }
        } else {
            // get all columns
            unset($metrics['Actions_avg_time_generation']);
            $columns = array_keys($metrics);
            $nameReplace = & $metrics;
            $avgGenerationTimeRequested = true;
        }

        if ($avgGenerationTimeRequested) {
			$tempColumns[] = Piwik_Actions_Archiver::METRIC_SUM_TIME_RECORD_NAME;
			$tempColumns[] = Piwik_Actions_Archiver::METRIC_HITS_TIMED_RECORD_NAME;
            $columns = array_merge($columns, $tempColumns);
            $columns = array_unique($columns);

            $nameReplace[Piwik_Actions_Archiver::METRIC_SUM_TIME_RECORD_NAME] = 'sum_time_generation';
            $nameReplace[Piwik_Actions_Archiver::METRIC_HITS_TIMED_RECORD_NAME] = 'nb_hits_with_time_generation';
        }

        $table = $archive->getDataTableFromNumeric($columns);

        // replace labels (remove Actions_)
        $table->filter('ReplaceColumnNames', array($nameReplace));

        // compute avg generation time
        if ($avgGenerationTimeRequested) {
            $table->filter('ColumnCallbackAddColumnQuotient', array('avg_time_generation', 'sum_time_generation', 'nb_hits_with_time_generation', 3));
            $table->deleteColumns(array('sum_time_generation', 'nb_hits_with_time_generation'));
        }

        return $table;
    }

    /**
     * @param int $idSite
     * @param string $period
     * @param Date $date
     * @param bool $segment
     * @param bool $expanded
     * @param bool $idSubtable
     *
     * @return DataTable|DataTable\Map
     */
    public function getPageUrls($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = Archive::getDataTableFromArchive('Actions_actions_url', $idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterPageDatatable($dataTable);
        $this->filterActionsDataTable($dataTable, $expanded);
        return $dataTable;
    }

    /**
     * @param int $idSite
     * @param string $period
     * @param Date $date
     * @param bool $segment
     * @param bool $expanded
     * @param bool $idSubtable
     *
     * @return DataTable|DataTable\Map
     */
    public function getPageUrlsFollowingSiteSearch($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->keepPagesFollowingSearch($dataTable);
        return $dataTable;
    }

    /**
     * @param int $idSite
     * @param string $period
     * @param Date $date
     * @param bool $segment
     * @param bool $expanded
     * @param bool $idSubtable
     *
     * @return DataTable|DataTable\Map
     */
    public function getPageTitlesFollowingSiteSearch($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->keepPagesFollowingSearch($dataTable);
        return $dataTable;
    }

    /**
     * @param DataTable $dataTable
     */
    protected function keepPagesFollowingSearch($dataTable)
    {
        // Keep only pages which are following site search
        $dataTable->filter('ColumnCallbackDeleteRow', array(
                                                           'nb_hits_following_search',
                                                           create_function('$value', 'return $value > 0;')
                                                      ));
    }

    /**
     * Returns a DataTable with analytics information for every unique entry page URL, for
     * the specified site, period & segment.
     */
    public function getEntryPageUrls($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterNonEntryActions($dataTable);
        return $dataTable;
    }

    /**
     * Returns a DataTable with analytics information for every unique exit page URL, for
     * the specified site, period & segment.
     */
    public function getExitPageUrls($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterNonExitActions($dataTable);
        return $dataTable;
    }

    public function getPageUrl($pageUrl, $idSite, $period, $date, $segment = false)
    {
        $callBackParameters = array('Actions_actions_url', $idSite, $period, $date, $segment, $expanded = false, $idSubtable = false);
        $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $pageUrl, Piwik_Tracker_Action::TYPE_ACTION_URL);
        $this->filterPageDatatable($dataTable);
        $this->filterActionsDataTable($dataTable);
        return $dataTable;
    }

    public function getPageTitles($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = Archive::getDataTableFromArchive('Actions_actions', $idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterPageDatatable($dataTable);
        $this->filterActionsDataTable($dataTable, $expanded);
        return $dataTable;
    }

    /**
     * Returns a DataTable with analytics information for every unique entry page title
     * for the given site, time period & segment.
     */
    public function getEntryPageTitles($idSite, $period, $date, $segment = false, $expanded = false,
                                       $idSubtable = false)
    {
        $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterNonEntryActions($dataTable);
        return $dataTable;
    }

    /**
     * Returns a DataTable with analytics information for every unique exit page title
     * for the given site, time period & segment.
     */
    public function getExitPageTitles($idSite, $period, $date, $segment = false, $expanded = false,
                                      $idSubtable = false)
    {
        $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterNonExitActions($dataTable);
        return $dataTable;
    }

    public function getPageTitle($pageName, $idSite, $period, $date, $segment = false)
    {
        $callBackParameters = array('Actions_actions', $idSite, $period, $date, $segment, $expanded = false, $idSubtable = false);
        $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $pageName, Piwik_Tracker_Action::TYPE_ACTION_NAME);
        $this->filterPageDatatable($dataTable);
        $this->filterActionsDataTable($dataTable);
        return $dataTable;
    }

    public function getDownloads($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = Archive::getDataTableFromArchive('Actions_downloads', $idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterActionsDataTable($dataTable, $expanded);
        return $dataTable;
    }

    public function getDownload($downloadUrl, $idSite, $period, $date, $segment = false)
    {
        $callBackParameters = array('Actions_downloads', $idSite, $period, $date, $segment, $expanded = false, $idSubtable = false);
        $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $downloadUrl, Piwik_Tracker_Action::TYPE_DOWNLOAD);
        $this->filterActionsDataTable($dataTable);
        return $dataTable;
    }

    public function getOutlinks($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        $dataTable = Archive::getDataTableFromArchive('Actions_outlink', $idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->filterActionsDataTable($dataTable, $expanded);
        return $dataTable;
    }

    public function getOutlink($outlinkUrl, $idSite, $period, $date, $segment = false)
    {
        $callBackParameters = array('Actions_outlink', $idSite, $period, $date, $segment, $expanded = false, $idSubtable = false);
        $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $outlinkUrl, Piwik_Tracker_Action::TYPE_OUTLINK);
        $this->filterActionsDataTable($dataTable);
        return $dataTable;
    }

    public function getSiteSearchKeywords($idSite, $period, $date, $segment = false)
    {
        $dataTable = $this->getSiteSearchKeywordsRaw($idSite, $period, $date, $segment);
        $dataTable->deleteColumn(Metrics::INDEX_SITE_SEARCH_HAS_NO_RESULT);
        $this->filterPageDatatable($dataTable);
        $this->filterActionsDataTable($dataTable);
        $this->addPagesPerSearchColumn($dataTable);
        return $dataTable;
    }

    //Visitors can search, and then click "next" to view more results. This is the average number of search results pages viewed for this keyword.
    protected function addPagesPerSearchColumn($dataTable, $columnToRead = 'nb_hits')
    {
        $dataTable->filter('ColumnCallbackAddColumnQuotient', array('nb_pages_per_search', $columnToRead, 'nb_visits', $precision = 1));
    }

    protected function getSiteSearchKeywordsRaw($idSite, $period, $date, $segment)
    {
        $dataTable = Archive::getDataTableFromArchive('Actions_sitesearch', $idSite, $period, $date, $segment, $expanded = false);
        return $dataTable;
    }

    public function getSiteSearchNoResultKeywords($idSite, $period, $date, $segment = false)
    {
        $dataTable = $this->getSiteSearchKeywordsRaw($idSite, $period, $date, $segment);
        // Delete all rows that have some results
        $dataTable->filter('ColumnCallbackDeleteRow',
            array(
                 Metrics::INDEX_SITE_SEARCH_HAS_NO_RESULT,
                 create_function('$value', 'return $value >= 1;')
            ));
        $dataTable->deleteRow(DataTable::ID_SUMMARY_ROW);
        $dataTable->deleteColumn(Metrics::INDEX_SITE_SEARCH_HAS_NO_RESULT);
        $this->filterPageDatatable($dataTable);
        $this->filterActionsDataTable($dataTable);
        $this->addPagesPerSearchColumn($dataTable);
        return $dataTable;
    }

    /**
     * @param int $idSite
     * @param string $period
     * @param Date $date
     * @param bool $segment
     *
     * @return DataTable|DataTable\Map
     */
    public function getSiteSearchCategories($idSite, $period, $date, $segment = false)
    {
        Piwik_Actions::checkCustomVariablesPluginEnabled();
        $customVariables = Piwik_CustomVariables_API::getInstance()->getCustomVariables($idSite, $period, $date, $segment, $expanded = false, $_leavePiwikCoreVariables = true);

        $customVarNameToLookFor = Piwik_Tracker_Action::CVAR_KEY_SEARCH_CATEGORY;

        $dataTable = new DataTable();
        // Handle case where date=last30&period=day
        // FIXMEA: this logic should really be refactored somewhere, this is ugly!
        if ($customVariables instanceof DataTable\Map) {
            $dataTable = $customVariables->getEmptyClone();

            $customVariableDatatables = $customVariables->getArray();
            $dataTables = $dataTable->getArray();
            foreach ($customVariableDatatables as $key => $customVariableTableForDate) {
                // we do not enter the IF, in the case idSite=1,3 AND period=day&date=datefrom,dateto,
                if (isset($customVariableTableForDate->metadata['period'])) {
                    $row = $customVariableTableForDate->getRowFromLabel($customVarNameToLookFor);
                    if ($row) {
                        $dateRewrite = $customVariableTableForDate->metadata['period']->getDateStart()->toString();
                        $idSubtable = $row->getIdSubDataTable();
                        $categories = Piwik_CustomVariables_API::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $dateRewrite, $idSubtable, $segment);
                        $dataTable->addTable($categories, $key);
                    }
                }
            }
        } elseif ($customVariables instanceof DataTable) {
            $row = $customVariables->getRowFromLabel($customVarNameToLookFor);
            if ($row) {
                $idSubtable = $row->getIdSubDataTable();
                $dataTable = Piwik_CustomVariables_API::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $date, $idSubtable, $segment);
            }
        }
        $this->filterActionsDataTable($dataTable);
        $this->addPagesPerSearchColumn($dataTable, $columnToRead = 'nb_actions');
        return $dataTable;
    }

    /**
     * Will search in the DataTable for a Label matching the searched string
     * and return only the matching row, or an empty datatable
     */
    protected function getFilterPageDatatableSearch($callBackParameters, $search, $actionType, $table = false,
                                                    $searchTree = false)
    {
        if ($searchTree === false) {
            // build the query parts that are searched inside the tree
            if ($actionType == Piwik_Tracker_Action::TYPE_ACTION_NAME) {
                $searchedString = Common::unsanitizeInputValue($search);
            } else {
                $idSite = $callBackParameters[1];
                try {
                    $searchedString = Piwik_Tracker_Action::excludeQueryParametersFromUrl($search, $idSite);
                } catch (Exception $e) {
                    $searchedString = $search;
                }
            }
            Piwik_Actions_ArchivingHelper::reloadConfig();
            $searchTree = Piwik_Actions_ArchivingHelper::getActionExplodedNames($searchedString, $actionType);
        }

        if ($table === false) {
            // fetch the data table
            $table = call_user_func_array(array('Piwik\Archive', 'getDataTableFromArchive'), $callBackParameters);

            if ($table instanceof DataTable\Map) {
                // search an array of tables, e.g. when using date=last30
                // note that if the root is an array, we filter all children
                // if an array occurs inside the nested table, we only look for the first match (see below)
                $newTableArray = $table->getEmptyClone();

                foreach ($table->getArray() as $label => $subTable) {
                    $newSubTable = $this->doFilterPageDatatableSearch($callBackParameters, $subTable, $searchTree);

                    $newTableArray->addTable($newSubTable, $label);
                }

                return $newTableArray;
            }

        }

        return $this->doFilterPageDatatableSearch($callBackParameters, $table, $searchTree);
    }

    /**
     * This looks very similar to LabelFilter.php should it be refactored somehow? FIXME
     */
    protected function doFilterPageDatatableSearch($callBackParameters, $table, $searchTree)
    {
        // filter a data table array
        if ($table instanceof DataTable\Map) {
            foreach ($table->getArray() as $subTable) {
                $filteredSubTable = $this->doFilterPageDatatableSearch($callBackParameters, $subTable, $searchTree);

                if ($filteredSubTable->getRowsCount() > 0) {
                    // match found in a sub table, return and stop searching the others
                    return $filteredSubTable;
                }
            }

            // nothing found in all sub tables
            return new DataTable;
        }

        // filter regular data table
        if ($table instanceof DataTable) {
            // search for the first part of the tree search
            $search = array_shift($searchTree);
            $row = $table->getRowFromLabel($search);
            if ($row === false) {
                // not found
                $result = new DataTable;
                $result->metadata = $table->metadata;
                return $result;
            }

            // end of tree search reached
            if (count($searchTree) == 0) {
                $result = new DataTable();
                $result->addRow($row);
                $result->metadata = $table->metadata;
                return $result;
            }

            // match found on this level and more levels remaining: go deeper
            $idSubTable = $row->getIdSubDataTable();
            $callBackParameters[6] = $idSubTable;
            $table = call_user_func_array(array('Piwik\Archive', 'getDataTableFromArchive'), $callBackParameters);
            return $this->doFilterPageDatatableSearch($callBackParameters, $table, $searchTree);
        }

        throw new Exception("For this API function, DataTable " . get_class($table) . " is not supported");
    }

    /**
     * Common filters for Page URLs and Page Titles
     */
    protected function filterPageDatatable($dataTable)
    {
        // Average time on page = total time on page / number visits on that page
        $dataTable->queueFilter('ColumnCallbackAddColumnQuotient', array('avg_time_on_page', 'sum_time_spent', 'nb_visits', 0));

        // Bounce rate = single page visits on this page / visits started on this page
        $dataTable->queueFilter('ColumnCallbackAddColumnPercentage', array('bounce_rate', 'entry_bounce_count', 'entry_nb_visits', 0));

        // % Exit = Number of visits that finished on this page / visits on this page
        $dataTable->queueFilter('ColumnCallbackAddColumnPercentage', array('exit_rate', 'exit_nb_visits', 'nb_visits', 0));

        // Handle performance analytics
        $hasTimeGeneration = (array_sum($dataTable->getColumn(Metrics::INDEX_PAGE_SUM_TIME_GENERATION)) > 0);
        if ($hasTimeGeneration) {
            // Average generation time = total generation time / number of pageviews
            $precisionAvgTimeGeneration = 3;
            $dataTable->queueFilter('ColumnCallbackAddColumnQuotient', array('avg_time_generation', 'sum_time_generation', 'nb_hits_with_time_generation', $precisionAvgTimeGeneration));
            $dataTable->queueFilter('ColumnDelete', array(array('sum_time_generation')));
        } else {
            // No generation time: remove it from the API output and add it to empty_columns metadata, so that
            // the columns can also be removed from the view
            $dataTable->filter('ColumnDelete', array(array(
                                                         Metrics::INDEX_PAGE_SUM_TIME_GENERATION,
                                                         Metrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION,
                                                         Metrics::INDEX_PAGE_MIN_TIME_GENERATION,
                                                         Metrics::INDEX_PAGE_MAX_TIME_GENERATION
                                                     )));

            if ($dataTable instanceof DataTable) {
                $emptyColumns = $dataTable->getMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME);
                if (!is_array($emptyColumns)) {
                    $emptyColumns = array();
                }
                $emptyColumns[] = 'sum_time_generation';
                $emptyColumns[] = 'avg_time_generation';
                $emptyColumns[] = 'min_time_generation';
                $emptyColumns[] = 'max_time_generation';
                $dataTable->setMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME, $emptyColumns);
            }
        }
    }

    /**
     * Common filters for all Actions API getters
     */
    protected function filterActionsDataTable($dataTable, $expanded = false)
    {
        // Must be applied before Sort in this case, since the DataTable can contain both int and strings indexes
        // (in the transition period between pre 1.2 and post 1.2 datatable structure)
        $dataTable->filter('ReplaceColumnNames');
        $dataTable->filter('Sort', array('nb_visits', 'desc', $naturalSort = false, $expanded));

        $dataTable->queueFilter('ReplaceSummaryRowLabel');
    }

    /**
     * Removes DataTable rows referencing actions that were never the first action of a visit.
     *
     * @param DataTable $dataTable
     */
    private function filterNonEntryActions($dataTable)
    {
        $dataTable->filter('ColumnCallbackDeleteRow', array('entry_nb_visits', 'strlen'));
    }

    /**
     * Removes DataTable rows referencing actions that were never the last action of a visit.
     *
     * @param DataTable $dataTable
     */
    private function filterNonExitActions($dataTable)
    {
        $dataTable->filter('ColumnCallbackDeleteRow', array('exit_nb_visits', 'strlen'));
    }
}