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 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\Transitions;
use Exception;
use Piwik\ArchiveProcessor;
use Piwik\Common;
use Piwik\Config;
use Piwik\DataAccess\LogAggregator;
use Piwik\DataArray;
use Piwik\DataTable;
use Piwik\DataTable\Row;
use Piwik\Db;
use Piwik\Metrics;
use Piwik\Period;
use Piwik\Piwik;
use Piwik\Plugins\Actions\ArchivingHelper;
use Piwik\Plugins\Live\Model;
use Piwik\RankingQuery;
use Piwik\Segment;
use Piwik\Segment\SegmentExpression;
use Piwik\Site;
use Piwik\Tracker\Action;
use Piwik\Tracker\PageUrl;
use Piwik\Tracker\TableLogAction;
/**
* @method static \Piwik\Plugins\Transitions\API getInstance()
*/
class API extends \Piwik\Plugin\API
{
public function getTransitionsForPageTitle(string $pageTitle, int $idSite, $period, $date, $segment = false, $limitBeforeGrouping = 0)
{
return $this->getTransitionsForAction($pageTitle, 'title', $idSite, $period, $date, $segment, $limitBeforeGrouping);
}
public function getTransitionsForPageUrl(string $pageUrl, int $idSite, $period, $date, $segment = false, $limitBeforeGrouping = 0)
{
return $this->getTransitionsForAction($pageUrl, 'url', $idSite, $period, $date, $segment, $limitBeforeGrouping);
}
/**
* General method to get transitions for an action
*
* @param string $actionType "url"|"title"
* @param $idSite
* @param $period
* @param $date
* @param bool $segment
* @param int $limitBeforeGrouping
* @param string $parts
* @return array
* @throws Exception
*/
public function getTransitionsForAction(
string $actionName,
string $actionType,
int $idSite,
$period,
$date,
$segment = false,
$limitBeforeGrouping = 0,
$parts = 'all'
) {
Piwik::checkUserHasViewAccess($idSite);
if (!$this->isPeriodAllowed($idSite, $period, $date)) {
throw new Exception('PeriodNotAllowed');
}
if ($limitBeforeGrouping && !is_numeric($limitBeforeGrouping)) {
throw new Exception('limitBeforeGrouping has to be an integer.');
}
//convert string to int
$limitBeforeGrouping = (int)$limitBeforeGrouping;
// get idaction of the requested action
$idaction = $this->deriveIdAction($actionName, $actionType);
if ($idaction < 0) {
throw new Exception('NoDataForAction');
}
// prepare log aggregator
$site = new Site($idSite);
$period = Period\Factory::build($period, $date);
$segment = new Segment(
$segment,
[$idSite],
$period->getDateTimeStart()->setTimezone($site->getTimezone()),
$period->getDateTimeEnd()->setTimezone($site->getTimezone())
);
$params = new ArchiveProcessor\Parameters($site, $period, $segment);
$logAggregator = new LogAggregator($params);
// prepare the report
$report = array(
'date' => Period\Factory::build($period->getLabel(), $date)->getLocalizedShortString(),
);
try {
$partsArray = explode(',', $parts);
if ($parts == 'all' || in_array('internalReferrers', $partsArray)) {
$this->addInternalReferrers($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping);
}
if ($parts == 'all' || in_array('followingActions', $partsArray)) {
$includeLoops = $parts != 'all' && !in_array('internalReferrers', $partsArray);
$this->addFollowingActions($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping, $includeLoops);
}
if ($parts == 'all' || in_array('externalReferrers', $partsArray)) {
$this->addExternalReferrers($logAggregator, $report, $idaction, $actionType, $limitBeforeGrouping);
}
// derive the number of exits from the other metrics
if ($parts == 'all') {
$report['pageMetrics']['exits'] = $report['pageMetrics']['pageviews']
- $this->getTotalTransitionsToFollowingActions()
- $report['pageMetrics']['loops'];
}
} catch (\Exception $e) {
Model::handleMaxExecutionTimeError(
Db::getReader(),
$e,
$segment->getString(),
$period->getDateStart(),
$period->getDateEnd(),
0,
Config::getInstance()->General['live_query_max_execution_time'],
['method' => 'Transitions.getTransitionsForAction', 'actionName' => $actionName, 'actionType' => $actionType]
);
throw $e;
}
// replace column names in the data tables
$reportNames = array(
'previousPages' => true,
'previousSiteSearches' => false,
'followingPages' => true,
'followingSiteSearches' => false,
'outlinks' => true,
'downloads' => true,
);
foreach ($reportNames as $reportName => $replaceLabel) {
if (isset($report[$reportName])) {
$columnNames = array(Metrics::INDEX_NB_ACTIONS => 'referrals');
if ($replaceLabel) {
$columnNames[Metrics::INDEX_NB_ACTIONS] = 'referrals';
}
$report[$reportName]->filter('ReplaceColumnNames', array($columnNames));
}
}
return $report;
}
/**
* Derive the action ID from the request action name and type.
*
*
* @return array|int|string
*/
private function deriveIdAction(string $actionName, string $actionType)
{
switch ($actionType) {
case 'url':
$originalActionName = $actionName;
$actionName = Common::unsanitizeInputValue($actionName);
$id = TableLogAction::getIdActionFromSegment($actionName, 'idaction_url', SegmentExpression::MATCH_EQUAL, 'pageUrl');
if ($id < 0) {
// an example where this is needed is urls containing < or >
$actionName = $originalActionName;
$id = TableLogAction::getIdActionFromSegment($actionName, 'idaction_url', SegmentExpression::MATCH_EQUAL, 'pageUrl');
}
return $id;
case 'title':
$id = TableLogAction::getIdActionFromSegment($actionName, 'idaction_name', SegmentExpression::MATCH_EQUAL, 'pageTitle');
if ($id < 0) {
$unknown = ArchivingHelper::getUnknownActionName(Action::TYPE_PAGE_TITLE);
if (trim($actionName) == trim($unknown)) {
$id = TableLogAction::getIdActionFromSegment('', 'idaction_name', SegmentExpression::MATCH_EQUAL, 'pageTitle');
}
}
return $id;
default:
throw new Exception('Unknown action type');
}
}
/**
* Add the internal referrers to the report:
* previous pages and previous site searches
*
* @param LogAggregator $logAggregator
* @param $report
* @param $idaction
* @param string $actionType
* @param $limitBeforeGrouping
* @throws Exception
*/
private function addInternalReferrers($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping)
{
$data = $this->queryInternalReferrers($idaction, $actionType, $logAggregator, $limitBeforeGrouping);
if ($data['pageviews'] == 0) {
throw new Exception('NoDataForAction');
}
$report['previousPages'] = & $data['previousPages'];
$report['previousSiteSearches'] = & $data['previousSiteSearches'];
$report['pageMetrics']['loops'] = $data['loops'];
$report['pageMetrics']['pageviews'] = $data['pageviews'];
}
/**
* Add the following actions to the report:
* following pages, downloads, outlinks
*
* @param LogAggregator $logAggregator
* @param $report
* @param $idaction
* @param string $actionType
* @param int $limitBeforeGrouping
* @param boolean $includeLoops
*/
private function addFollowingActions($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping = 0, $includeLoops = false)
{
$data = $this->queryFollowingActions(
$idaction,
$actionType,
$logAggregator,
$limitBeforeGrouping,
$includeLoops
);
foreach ($data as $tableName => $table) {
$report[$tableName] = $table;
}
}
/**
* Get information about the following actions (following pages, site searches, outlinks, downloads)
*
* @param $idaction
* @param $actionType
* @param $limitBeforeGrouping
* @param $includeLoops
* @return array(followingPages:DataTable, outlinks:DataTable, downloads:DataTable)
*/
protected function queryFollowingActions(
$idaction,
$actionType,
LogAggregator $logAggregator,
$limitBeforeGrouping = 0,
$includeLoops = false
) {
$types = array();
if ($actionType != 'title') {
// specific setup for page urls
$types[Action::TYPE_PAGE_URL] = 'followingPages';
$dimension = 'if ( %1$s.idaction_url IS NULL, %1$s.idaction_name, %1$s.idaction_url )';
$dimension = sprintf($dimension, 'log_link_visit_action');
// site search referrers are logged with url=NULL
// when we find one, we have to join on name
$joinLogActionColumn = $dimension;
$selects = array('log_action.name', 'log_action.url_prefix', 'log_action.type');
} else {
// specific setup for page titles:
$types[Action::TYPE_PAGE_TITLE] = 'followingPages';
// join log_action on name and url and pick depending on url type
// the table joined on url is log_action1
$joinLogActionColumn = array('idaction_url', 'idaction_name');
$dimension = '
CASE
' /* following site search */ . '
WHEN log_link_visit_action.idaction_url IS NULL THEN log_action2.idaction
' /* following page view: use page title */ . '
WHEN log_action1.type = ' . Action::TYPE_PAGE_URL . ' THEN log_action2.idaction
' /* following download or outlink: use url */ . '
ELSE log_action1.idaction
END
';
$selects = array(
'CASE
' /* following site search */ . '
WHEN log_link_visit_action.idaction_url IS NULL THEN log_action2.name
' /* following page view: use page title */ . '
WHEN log_action1.type = ' . Action::TYPE_PAGE_URL . ' THEN log_action2.name
' /* following download or outlink: use url */ . '
ELSE log_action1.name
END AS `name`',
'CASE
' /* following site search */ . '
WHEN log_link_visit_action.idaction_url IS NULL THEN log_action2.type
' /* following page view: use page title */ . '
WHEN log_action1.type = ' . Action::TYPE_PAGE_URL . ' THEN log_action2.type
' /* following download or outlink: use url */ . '
ELSE log_action1.type
END AS `type`',
'NULL AS `url_prefix`',
);
}
// these types are available for both titles and urls
$types[Action::TYPE_SITE_SEARCH] = 'followingSiteSearches';
$types[Action::TYPE_OUTLINK] = 'outlinks';
$types[Action::TYPE_DOWNLOAD] = 'downloads';
$rankingQuery = new RankingQuery($limitBeforeGrouping ? $limitBeforeGrouping : $this->limitBeforeGrouping);
$rankingQuery->setOthersLabel('Others');
$rankingQuery->addLabelColumn(array('name', 'url_prefix'));
$rankingQuery->partitionResultIntoMultipleGroups('type', array_keys($types));
$type = $this->getColumnTypeSuffix($actionType);
$where = 'log_link_visit_action.idaction_' . $type . '_ref = ' . intval($idaction);
if (!$includeLoops) {
$where .= ' AND (log_link_visit_action.idaction_' . $type . ' IS NULL OR '
. 'log_link_visit_action.idaction_' . $type . ' != ' . intval($idaction) . ')';
}
$metrics = array(Metrics::INDEX_NB_ACTIONS);
$data = $logAggregator->queryActionsByDimension(
array($dimension),
$where,
$selects,
$metrics,
$rankingQuery,
$joinLogActionColumn,
$secondaryOrderBy = "`name`",
Config::getInstance()->General['live_query_max_execution_time']
);
$dataTables = $this->makeDataTablesFollowingActions($types, $data);
return $dataTables;
}
/**
* Get information about external referrers (i.e. search engines, websites & campaigns)
*
* @param $idaction
* @param $actionType
* @param LogAggregator $logAggregator
* @param int $limitBeforeGrouping
* @return DataTable
* @throws Exception
*/
protected function queryExternalReferrers($idaction, $actionType, $logAggregator, $limitBeforeGrouping = 0)
{
$rankingQuery = new RankingQuery($limitBeforeGrouping ?: $this->limitBeforeGrouping);
$rankingQuery->setOthersLabel('Others');
// we generate a single column that contains the interesting data for each referrer.
// the reason we cannot group by referer_* becomes clear when we look at search engine keywords.
// referer_url contains the url from the search engine, referer_keyword the keyword we want to
// group by. when we group by both, we don't get a single column for the keyword but instead
// one column per keyword + search engine url. this way, we could not get the top keywords using
// the ranking query.
$dimensions = array('referrer_data' => 'CASE log_visit.referer_type
WHEN ' . Common::REFERRER_TYPE_DIRECT_ENTRY . ' THEN \'\'
WHEN ' . Common::REFERRER_TYPE_SEARCH_ENGINE . ' THEN log_visit.referer_name
WHEN ' . Common::REFERRER_TYPE_SOCIAL_NETWORK . ' THEN log_visit.referer_name
WHEN ' . Common::REFERRER_TYPE_AI_ASSISTANT . ' THEN log_visit.referer_name
WHEN ' . Common::REFERRER_TYPE_WEBSITE . ' THEN log_visit.referer_url
WHEN ' . Common::REFERRER_TYPE_CAMPAIGN . ' THEN CONCAT_WS(\' \', log_visit.referer_name, log_visit.referer_keyword)
END', 'referer_type');
$rankingQuery->addLabelColumn('referrer_data');
// get one limited group per referrer type
$rankingQuery->partitionResultIntoMultipleGroups('referer_type', array(
Common::REFERRER_TYPE_DIRECT_ENTRY,
Common::REFERRER_TYPE_SEARCH_ENGINE,
Common::REFERRER_TYPE_SOCIAL_NETWORK,
Common::REFERRER_TYPE_AI_ASSISTANT,
Common::REFERRER_TYPE_WEBSITE,
Common::REFERRER_TYPE_CAMPAIGN,
));
$type = $this->getColumnTypeSuffix($actionType);
$where = 'visit_entry_idaction_' . $type . ' = ' . intval($idaction);
$metrics = array(Metrics::INDEX_NB_VISITS);
$data = $logAggregator->queryVisitsByDimension($dimensions, $where, [], $metrics, $rankingQuery, false, Config::getInstance()->General['live_query_max_execution_time']);
// array is prefilled with available keys and empty values are removed in the end to ensure the order is static
$referrerData = [
Common::REFERRER_TYPE_DIRECT_ENTRY => [],
Common::REFERRER_TYPE_SEARCH_ENGINE => [],
Common::REFERRER_TYPE_SOCIAL_NETWORK => [],
Common::REFERRER_TYPE_AI_ASSISTANT => [],
Common::REFERRER_TYPE_WEBSITE => [],
Common::REFERRER_TYPE_CAMPAIGN => [],
];
$referrerSubData = array();
foreach ($data as $referrerType => &$subData) {
$referrerData[$referrerType] = array(Metrics::INDEX_NB_VISITS => 0);
if ($referrerType != Common::REFERRER_TYPE_DIRECT_ENTRY) {
$referrerSubData[$referrerType] = array();
}
foreach ($subData as &$row) {
if ($referrerType == Common::REFERRER_TYPE_SEARCH_ENGINE && empty($row['referrer_data'])) {
$row['referrer_data'] = Piwik::translate('General_Unknown');
}
$referrerData[$referrerType][Metrics::INDEX_NB_VISITS] += $row[Metrics::INDEX_NB_VISITS];
$label = $row['referrer_data'];
if ($label) {
$referrerSubData[$referrerType][$label] = array(
Metrics::INDEX_NB_VISITS => $row[Metrics::INDEX_NB_VISITS],
);
}
}
}
// remove empty records
$referrerData = array_filter($referrerData);
$array = new DataArray($referrerData, $referrerSubData);
return $array->asDataTable();
}
/**
* Get information about internal referrers (previous pages & loops, i.e. page refreshes)
*
* @param $idaction
* @param $actionType
* @param LogAggregator $logAggregator
* @param int $limitBeforeGrouping
* @return array(previousPages:DataTable, loops:integer)
*/
protected function queryInternalReferrers($idaction, $actionType, $logAggregator, $limitBeforeGrouping = 0)
{
$keyIsOther = 0;
$keyIsPageUrlAction = 1;
$keyIsSiteSearchAction = 2;
$rankingQuery = new RankingQuery($limitBeforeGrouping ? $limitBeforeGrouping : $this->limitBeforeGrouping);
$rankingQuery->setOthersLabel('Others');
$rankingQuery->addLabelColumn(array('name', 'url_prefix'));
$rankingQuery->setColumnToMarkExcludedRows('is_self');
$rankingQuery->partitionResultIntoMultipleGroups('action_partition', array($keyIsOther, $keyIsPageUrlAction, $keyIsSiteSearchAction));
$type = $this->getColumnTypeSuffix($actionType);
$mainActionType = Action::TYPE_PAGE_URL;
$dimension = 'idaction_url_ref';
if ($actionType == 'title') {
$mainActionType = Action::TYPE_PAGE_TITLE;
$dimension = 'idaction_name_ref';
}
$selects = array(
'log_action.name',
'log_action.url_prefix',
'CASE WHEN log_link_visit_action.idaction_' . $type . '_ref = ' . intval($idaction) . ' THEN 1 ELSE 0 END AS `is_self`',
'CASE
WHEN log_action.type = ' . $mainActionType . ' THEN ' . $keyIsPageUrlAction . '
WHEN log_action.type = ' . Action::TYPE_SITE_SEARCH . ' THEN ' . $keyIsSiteSearchAction . '
ELSE ' . $keyIsOther . '
END AS `action_partition`',
);
$where = ' log_link_visit_action.idaction_' . $type . ' = ' . intval($idaction);
if ($dimension == 'idaction_url_ref') {
// site search referrers are logged with url_ref=NULL
// when we find one, we have to join on name_ref
$dimension = 'if ( %1$s.idaction_url_ref IS NULL, %1$s.idaction_name_ref, %1$s.idaction_url_ref )';
$dimension = sprintf($dimension, 'log_link_visit_action');
$joinLogActionOn = $dimension;
} else {
$joinLogActionOn = $dimension;
}
$metrics = array(Metrics::INDEX_NB_ACTIONS);
$data = $logAggregator->queryActionsByDimension(
array($dimension),
$where,
$selects,
$metrics,
$rankingQuery,
$joinLogActionOn,
$secondaryOrderBy = "`name`",
Config::getInstance()->General['live_query_max_execution_time']
);
$loops = 0;
$nbPageviews = 0;
$previousPagesDataTable = new DataTable();
if (isset($data['result'][$keyIsPageUrlAction])) {
foreach ($data['result'][$keyIsPageUrlAction] as &$page) {
$nbActions = intval($page[Metrics::INDEX_NB_ACTIONS]);
$previousPagesDataTable->addRow(new Row(array(
Row::COLUMNS => array(
'label' => $this->getPageLabel($page, Action::TYPE_PAGE_URL),
Metrics::INDEX_NB_ACTIONS => $nbActions,
),
)));
$nbPageviews += $nbActions;
}
}
$previousSearchesDataTable = new DataTable();
if (isset($data['result'][$keyIsSiteSearchAction])) {
foreach ($data['result'][$keyIsSiteSearchAction] as &$search) {
$nbActions = intval($search[Metrics::INDEX_NB_ACTIONS]);
$previousSearchesDataTable->addRow(new Row(array(
Row::COLUMNS => array(
'label' => $search['name'],
Metrics::INDEX_NB_ACTIONS => $nbActions,
),
)));
$nbPageviews += $nbActions;
}
}
if (isset($data['result'][0])) {
foreach ($data['result'][0] as &$referrer) {
$nbPageviews += intval($referrer[Metrics::INDEX_NB_ACTIONS]);
}
}
if (count($data['excludedFromLimit'])) {
$loops += intval($data['excludedFromLimit'][0][Metrics::INDEX_NB_ACTIONS]);
$nbPageviews += $loops;
}
return array(
'pageviews' => $nbPageviews,
'previousPages' => $previousPagesDataTable,
'previousSiteSearches' => $previousSearchesDataTable,
'loops' => $loops,
);
}
private function getPageLabel(&$pageRecord, $type)
{
if ($type == Action::TYPE_PAGE_TITLE) {
$label = $pageRecord['name'];
if (empty($label)) {
$label = ArchivingHelper::getUnknownActionName(Action::TYPE_PAGE_TITLE);
}
return $label;
}
if ($type == Action::TYPE_OUTLINK || $type == Action::TYPE_DOWNLOAD) {
return PageUrl::reconstructNormalizedUrl($pageRecord['name'], $pageRecord['url_prefix']);
}
return $pageRecord['name'];
}
private function getColumnTypeSuffix($actionType)
{
if ($actionType == 'title') {
return 'name';
}
return 'url';
}
private $limitBeforeGrouping = 5;
private $totalTransitionsToFollowingPages = 0;
/**
* Get the sum of all transitions to following actions (pages, outlinks, downloads).
* Only works if queryFollowingActions() has been used directly before.
*/
protected function getTotalTransitionsToFollowingActions()
{
return $this->totalTransitionsToFollowingPages;
}
/**
* Add the external referrers to the report:
* direct entries, websites, campaigns, search engines
*
* @param LogAggregator $logAggregator
* @param $report
* @param $idaction
* @param string $actionType
* @param $limitBeforeGrouping
*/
private function addExternalReferrers($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping)
{
$data = $this->queryExternalReferrers(
$idaction,
$actionType,
$logAggregator,
$limitBeforeGrouping
);
$report['pageMetrics']['entries'] = 0;
$report['referrers'] = array();
foreach ($data->getRows() as $row) {
$referrerId = $row->getColumn('label');
$visits = $row->getColumn(Metrics::INDEX_NB_VISITS);
if ($visits) {
// load details (i.e. subtables)
$details = array();
$subTable = $row->getSubtable();
if ($subTable) {
foreach ($subTable->getRows() as $subRow) {
$details[] = array(
'label' => $subRow->getColumn('label'),
'referrals' => $subRow->getColumn(Metrics::INDEX_NB_VISITS),
);
}
}
$report['referrers'][] = array(
'label' => $this->getReferrerLabel($referrerId),
'shortName' => \Piwik\Plugins\Referrers\getReferrerTypeFromShortName($referrerId),
'visits' => $visits,
'details' => $details,
);
$report['pageMetrics']['entries'] += $visits;
}
}
// if there's no data for referrers, ResponseBuilder::handleMultiDimensionalArray
// does not detect the multi dimensional array and the data is rendered differently, which
// causes an exception.
if (count($report['referrers']) == 0) {
$report['referrers'][] = array(
'label' => $this->getReferrerLabel(Common::REFERRER_TYPE_DIRECT_ENTRY),
'shortName' => \Piwik\Plugins\Referrers\getReferrerTypeLabel(Common::REFERRER_TYPE_DIRECT_ENTRY),
'visits' => 0,
);
}
}
private function getReferrerLabel($referrerId)
{
switch ($referrerId) {
case Common::REFERRER_TYPE_DIRECT_ENTRY:
return Controller::getTranslation('directEntries');
case Common::REFERRER_TYPE_SEARCH_ENGINE:
return Controller::getTranslation('fromSearchEngines');
case Common::REFERRER_TYPE_SOCIAL_NETWORK:
return Controller::getTranslation('fromSocialNetworks');
case Common::REFERRER_TYPE_AI_ASSISTANT:
return Controller::getTranslation('fromAIAssistants');
case Common::REFERRER_TYPE_WEBSITE:
return Controller::getTranslation('fromWebsites');
case Common::REFERRER_TYPE_CAMPAIGN:
return Controller::getTranslation('fromCampaigns');
default:
return Piwik::translate('General_Others');
}
}
public function getTranslations()
{
$controller = new Controller();
return $controller->getTranslations();
}
protected function makeDataTablesFollowingActions($types, $data)
{
$this->totalTransitionsToFollowingPages = 0;
$dataTables = array();
foreach ($types as $type => $recordName) {
$dataTable = new DataTable();
if (isset($data[$type])) {
foreach ($data[$type] as &$record) {
$actions = intval($record[Metrics::INDEX_NB_ACTIONS]);
$dataTable->addRow(new Row(array(
Row::COLUMNS => array(
'label' => $this->getPageLabel($record, $type),
Metrics::INDEX_NB_ACTIONS => $actions,
),
)));
$this->processTransitionsToFollowingPages($type, $actions);
}
}
$dataTables[$recordName] = $dataTable;
}
return $dataTables;
}
protected function processTransitionsToFollowingPages($type, $actions)
{
// Downloads and Outlinks are not included as these actions count towards a Visit Exit
$actionTypesNotExitActions = array(
Action::TYPE_SITE_SEARCH,
Action::TYPE_PAGE_TITLE,
Action::TYPE_PAGE_URL,
);
if (in_array($type, $actionTypesNotExitActions)) {
$this->totalTransitionsToFollowingPages += $actions;
}
}
/**
* Check if a period is allowed by config settings
*
* @param $idSite
* @param $period
* @param $date
*
*/
public function isPeriodAllowed($idSite, $period, $date): bool
{
$maxPeriodAllowed = Transitions::getPeriodAllowedConfig($idSite);
if ($maxPeriodAllowed === 'all') {
return true;
}
// If the period is a range then the number of days in the range must be less or equal to the max period allowed
if ($period === 'range') {
$range = new Period\Range($period, $date);
$rangeDays = $range->getDayCount();
switch ($maxPeriodAllowed) {
case 'day':
return $rangeDays == 1;
case 'week':
return $rangeDays <= 7;
case 'month':
return $rangeDays <= 31;
case 'year':
return $rangeDays <= 365;
}
}
switch ($maxPeriodAllowed) {
case 'day':
return $period === 'day';
case 'week':
return in_array($period, ['day', 'week']);
case 'month':
return in_array($period, ['day', 'week', 'month']);
case 'year':
return in_array($period, ['day', 'week', 'month', 'year']);
}
return false;
}
}
|