public function test_makeLogVisitsQueryString_withMultipleIdSites() { Piwik::addAction('Live.API.getIdSitesString', function (&$idSites) { $idSites = array(2, 3, 4); }); $model = new Model(); list($sql, $bind) = $model->makeLogVisitsQueryString($idSite = 1, $period = 'month', $date = '2010-01-01', $segment = false, $offset = 0, $limit = 100, $visitorId = false, $minTimestamp = false, $filterSortOrder = false); $expectedSql = ' SELECT sub.* FROM ( SELECT log_visit.* FROM ' . Common::prefixTable('log_visit') . ' AS log_visit WHERE log_visit.idsite in (?,?,?) AND log_visit.visit_last_action_time >= ? AND log_visit.visit_last_action_time <= ? ORDER BY visit_last_action_time DESC LIMIT 0, 100 ) AS sub GROUP BY sub.idvisit ORDER BY sub.visit_last_action_time DESC LIMIT 100 '; $expectedBind = array('2', '3', '4', '2010-01-01 00:00:00', '2010-02-01 00:00:00'); $this->assertEquals(SegmentTest::removeExtraWhiteSpaces($expectedSql), SegmentTest::removeExtraWhiteSpaces($sql)); $this->assertEquals(SegmentTest::removeExtraWhiteSpaces($expectedBind), SegmentTest::removeExtraWhiteSpaces($bind)); }
public function setupTestEnvironment($environment) { Piwik::addAction("MySQLMetadataProvider.createDao", function (&$dao) { require_once dirname(__FILE__) . "/tests/Mocks/MockDataAccess.php"; $dao = new Mocks\MockDataAccess(); }); }
public function setUp() { parent::setUp(); $self = $this; Piwik::addAction('API.Request.dispatch.end', function (&$return, $extra) use($self) { if ($extra['module'] !== 'Events') { return; } /** @var DataTable $return*/ // we make sure processed result is the same at any time foreach ($return as &$value) { $value->setColumn('sum_event_value', '2'); $value->setColumn('max_event_value', '2'); $value->setColumn('min_event_value', '2'); $value->setColumn('sum_daily_nb_uniq_visitors', '2'); $value->setColumn('avg_event_value', '2'); if ($value->isSubtableLoaded()) { $subtable = $value->getSubtable(); foreach ($subtable->getRows() as $row) { $row->setColumn('sum_event_value', '2'); $row->setColumn('max_event_value', '2'); $row->setColumn('min_event_value', '2'); $row->setColumn('sum_daily_nb_uniq_visitors', '2'); $row->setColumn('avg_event_value', '2'); } } } }); }
/** * @expectedException \Exception * @expectedExceptionMessage The Visit object set in the plugin */ public function test_make_shouldTriggerExceptionInCaseWrongInstanceCreatedInHandler() { Piwik::addAction('Tracker.makeNewVisitObject', function (&$visit) { $visit = new Tracker(); }); Factory::make(); }
/** * @expectedException \Exception * @expectedExceptionMessage The Handler object set in the plugin */ public function test_make_shouldTriggerExceptionInCaseWrongInstanceCreatedInHandler() { Piwik::addAction('Tracker.newHandler', function (&$handler) { $handler = new Tracker(); }); Factory::make(); }
public static function setUp() { Piwik::addAction('Log.formatFileMessage', array('\\Piwik\\ExceptionHandler', 'formatFileAndDBLogMessage')); Piwik::addAction('Log.formatDatabaseMessage', array('\\Piwik\\ExceptionHandler', 'formatFileAndDBLogMessage')); Piwik::addAction('Log.formatScreenMessage', array('\\Piwik\\ExceptionHandler', 'formatScreenMessage')); set_exception_handler(array('\\Piwik\\ExceptionHandler', 'logException')); }
public function postLoad() { if (PluginManager::getInstance()->isPluginActivated('UserCountry')) { WidgetsList::add('General_Visitors', Piwik::translate('UserCountryMap_VisitorMap'), 'UserCountryMap', 'visitorMap'); WidgetsList::add('Live!', Piwik::translate('UserCountryMap_RealTimeMap'), 'UserCountryMap', 'realtimeMap'); } Piwik::addAction('Template.leftColumnUserCountry', array('Piwik\\Plugins\\UserCountryMap\\UserCountryMap', 'insertMapInLocationReport')); }
public function test_setUserAccess_ShouldNotTriggerRemoveSiteAccessEvent_IfAccessIsAdded() { $eventTriggered = false; Piwik::addAction('UsersManager.removeSiteAccess', function () use(&$eventTriggered) { $eventTriggered = true; }); $this->api->setUserAccess($this->login, 'admin', array(1, 2)); $this->assertFalse($eventTriggered, 'UsersManager.removeSiteAccess event was triggered but should not'); }
/** * Tests the generated JS code with options before tracker url */ public function testJavascriptTrackingCode_withAllOptionsAndOptionsBeforeTrackerUrl() { $generator = new TrackerCodeGenerator(); Piwik::addAction('Piwik.getJavascriptCode', function (&$codeImpl) { $codeImpl['optionsBeforeTrackerUrl'] .= "_paq.push(['setAPIUrl', 'http://localhost/statistics']);\n "; }); $jsTag = $generator->generate($idSite = 1, $piwikUrl = 'http://localhost/piwik', $mergeSubdomains = true, $groupPageTitlesByDomain = true, $mergeAliasUrls = true, $visitorCustomVariables = array(array("name", "value"), array("name 2", "value 2")), $pageCustomVariables = array(array("page cvar", "page cvar value")), $customCampaignNameQueryParam = "campaignKey", $customCampaignKeywordParam = "keywordKey", $doNotTrack = true); $expected = "<!-- Piwik -->\n<script type="text/javascript">\n var _paq = _paq || [];\n _paq.push([\"setDocumentTitle\", document.domain + \"/\" + document.title]);\n // you can set up to 5 custom variables for each visitor\n _paq.push([\"setCustomVariable\", 1, \"name\", \"value\", \"visit\"]);\n _paq.push([\"setCustomVariable\", 2, \"name 2\", \"value 2\", \"visit\"]);\n // you can set up to 5 custom variables for each action (page view, download, click, site search)\n _paq.push([\"setCustomVariable\", 1, \"page cvar\", \"page cvar value\", \"page\"]);\n _paq.push([\"setCampaignNameKey\", \"campaignKey\"]);\n _paq.push([\"setCampaignKeywordKey\", \"keywordKey\"]);\n _paq.push([\"setDoNotTrack\", true]);\n _paq.push(['trackPageView']);\n _paq.push(['enableLinkTracking']);\n (function() {\n var u="//localhost/piwik/";\n _paq.push(['setAPIUrl', 'http://localhost/statistics']);\n _paq.push(['setTrackerUrl', u+'piwik.php']);\n _paq.push(['setSiteId', 1]);\n var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);\n })();\n</script>\n<noscript><p><img src="//localhost/piwik/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>\n<!-- End Piwik Code -->\n"; $this->assertEquals($expected, $jsTag); }
public function test_getMenu_shouldTriggerAddItemsEvent_toBeBackwardsCompatible() { $this->loadSomePlugins(); $triggered = false; Piwik::addAction('Menu.Reporting.addItems', function () use(&$triggered) { $triggered = true; }); $this->menu->getMenu(); $this->assertTrue($triggered); }
public static function setUpBeforeClass() { parent::setUpBeforeClass(); $extraSite = Fixture::createWebsite(self::$fixture->dateTime, $ecommerce = 1, "the site"); Piwik::addAction("ArchiveProcessor.Parameters.getIdSites", function (&$sites, $period) use($extraSite) { if (reset($sites) == $extraSite) { $sites = array(1, 2, 3); } }); Config::getInstance()->General['enable_processing_unique_visitors_multiple_sites'] = 1; }
private static function populateCache() { if (Development::isEnabled()) { return; } if (SettingsServer::isTrackerApiRequest()) { $eventToPersist = 'Tracker.end'; $mode = '-tracker'; } else { $eventToPersist = 'Request.dispatch.end'; $mode = '-ui'; } $cache = self::getStorage()->get(self::getCacheFilename() . $mode); if (is_array($cache)) { self::$content = $cache; } Piwik::addAction($eventToPersist, array(__CLASS__, 'persistCache')); }
public function test_initRequestsAndTokednAuth_shouldInitializeFromGetAndPostIfEventDoesNotHandleRequests() { $_GET = array('idsite' => 1); $_POST = array('c_i' => 'click'); Piwik::addAction('Tracker.initRequestSet', function (RequestSet $requestSet) { $requestSet->setRequests(array(array('idsite' => '2'), array('idsite' => '3'))); }); $requestSet = $this->buildNewRequestSetThatIsNotInitializedYet(); $requestSet->initRequestsAndTokenAuth(); $requests = $requestSet->getRequests(); $this->assertCount(2, $requests); $this->assertEquals(array('idsite' => '2'), $requests[0]->getParams()); $this->assertEquals(array('idsite' => '3'), $requests[1]->getParams()); }
/** * @group Core * * @dataProvider testRunTasksTestCases */ public function testRunTasks($expectedTimetable, $expectedExecutedTasks, $timetableBeforeTaskExecution, $configuredTasks) { // temporarily unload plugins $plugins = \Piwik\Plugin\Manager::getInstance()->getLoadedPlugins(); $plugins = array_map(function ($p) { return $p->getPluginName(); }, $plugins); \Piwik\Plugin\Manager::getInstance()->unloadPlugins(); // make sure the get tasks event returns our configured tasks \Piwik\Piwik::addAction(TaskScheduler::GET_TASKS_EVENT, function (&$tasks) use($configuredTasks) { $tasks = $configuredTasks; }); // stub the piwik option object to control the returned option value self::stubPiwikOption(serialize($timetableBeforeTaskExecution)); TaskScheduler::unsetInstance(); // execute tasks $executionResults = TaskScheduler::runTasks(); // assert methods are executed $executedTasks = array(); foreach ($executionResults as $executionResult) { $executedTasks[] = $executionResult['task']; $this->assertNotEmpty($executionResult['output']); } $this->assertEquals($expectedExecutedTasks, $executedTasks); // assert the timetable is correctly updated $timetable = new ScheduledTaskTimetable(); $this->assertEquals($expectedTimetable, $timetable->getTimetable()); // restore loaded plugins & piwik options EventDispatcher::getInstance()->clearObservers(TaskScheduler::GET_TASKS_EVENT); \Piwik\Plugin\Manager::getInstance()->loadPlugins($plugins); self::resetPiwikOption(); }
function postLoad() { Piwik::addAction('Template.footerVisitsFrequency', array('Piwik\\Plugins\\VisitorInterest\\VisitorInterest', 'footerVisitsFrequency')); }
public function setupTestEnvironment($environment) { Piwik::addAction("MySQLMetadataProvider.createDao", function (&$dao) { $dao = new MockDataAccess(); }); }
public function postLoad() { Piwik::addAction('Template.leftColumnUserCountry', array('Piwik\\Plugins\\UserCountryMap\\UserCountryMap', 'insertMapInLocationReport')); }
/** * Test no concurrency issues when deleting log data from log_action table. * * @group Integration */ public function testPurgeLogDataConcurrency() { \Piwik\Piwik::addAction("LogDataPurger.ActionsToKeepInserted.olderThan", array($this, 'addReferenceToUnusedAction')); $purger = LogDataPurger::make($this->settings, true); $this->unusedIdAction = Db::fetchOne("SELECT idaction FROM " . Common::prefixTable('log_action') . " WHERE name = ?", array('whatever.com/_40')); $this->assertTrue($this->unusedIdAction > 0); // purge data $purger->purgeData(); // check that actions were purged $this->assertEquals(22 + $this->getCountEventIdsNotPurged(), $this->_getTableCount('log_action')); // January // check that the unused action still exists $count = Db::fetchOne("SELECT COUNT(*) FROM " . Common::prefixTable('log_action') . " WHERE idaction = ?", array($this->unusedIdAction)); $this->assertEquals(1, $count); $this->unusedIdAction = null; // so the hook won't get executed twice }
$instanceId = $instanceId ? '/' . $instanceId : ''; } else { $instanceId = ''; } return $root . '/tmp' . $instanceId; }, 'path.cache' => DI\string('{path.tmp}/cache/tracker/'), 'Piwik\\Cache\\Eager' => function (ContainerInterface $c) { $backend = $c->get('Piwik\\Cache\\Backend'); $cacheId = $c->get('cache.eager.cache_id'); if (SettingsServer::isTrackerApiRequest()) { $eventToPersist = 'Tracker.end'; $cacheId .= 'tracker'; } else { $eventToPersist = 'Request.dispatch.end'; $cacheId .= 'ui'; } $cache = new Eager($backend, $cacheId); \Piwik\Piwik::addAction($eventToPersist, function () use($cache) { $cache->persistCacheIfNeeded(43200); }); return $cache; }, 'Piwik\\Cache\\Backend' => function (ContainerInterface $c) { try { $backend = $c->get('ini.Cache.backend'); } catch (NotFoundException $ex) { $backend = 'chained'; // happens if global.ini.php is not available } return \Piwik\Cache::buildBackend($backend); }, 'cache.eager.cache_id' => function () { return 'eagercache-' . str_replace(array('.', '-'), '', \Piwik\Version::VERSION) . '-'; }, 'Psr\\Log\\LoggerInterface' => DI\object('Psr\\Log\\NullLogger'), 'Piwik\\Translation\\Loader\\LoaderInterface' => DI\object('Piwik\\Translation\\Loader\\LoaderCache')->constructor(DI\get('Piwik\\Translation\\Loader\\JsonFileLoader')), 'observers.global' => array(), 'Piwik\\EventDispatcher' => DI\object()->constructorParameter('observers', DI\get('observers.global')));
public static function addSendMailHook() { Piwik::addAction('Test.Mail.send', function ($mail) { $outputFile = PIWIK_INCLUDE_PATH . '/tmp/' . Common::getRequestVar('module', '') . '.' . Common::getRequestVar('action', '') . '.mail.json'; $outputContent = str_replace("=\n", "", $mail->getBodyText($textOnly = true)); $outputContent = str_replace("=0A", "\n", $outputContent); $outputContent = str_replace("=3D", "=", $outputContent); $outputContents = array('from' => $mail->getFrom(), 'to' => $mail->getRecipients(), 'subject' => $mail->getSubject(), 'contents' => $outputContent); file_put_contents($outputFile, Common::json_encode($outputContents)); }); }
public function setUp() { parent::setUp(); Fixture::createWebsite('2014-01-01 00:00:00'); Piwik::addAction('Tracker.Request.getIdSite', function (&$idSite) { $idSite = 1; }); }
public function test_main_shouldPostEndEvent_EvenIfThereIsAnException() { $called = false; Piwik::addAction('Tracker.end', function () use(&$called) { $called = true; }); $handler = new Handler(); $handler->enableTriggerExceptionInProcess(); $requestSet = new RequestSet(); $requestSet->setRequests(array($this->buildRequest(1), $this->buildRequest(1))); $this->tracker->main($handler, $requestSet); $this->assertTrue($handler->isOnException); $this->assertTrue($called); }
public function postLoad() { Piwik::addAction('Template.footerUserCountry', array('Piwik\\Plugins\\UserLanguage\\UserLanguage', 'footerUserCountry')); }
public function test_getIdSite_shouldTriggerEventAndReturnThatIdSite() { $self = $this; Piwik::addAction('Tracker.Request.getIdSite', function (&$idSite, $params) use($self) { $self->assertSame(14, $idSite); $self->assertEquals(array('idsite' => '14'), $params); $idSite = 12; }); $request = $this->buildRequest(array('idsite' => '14')); $this->assertSame(12, $request->getIdSite()); }
public function postLoad() { Piwik::addAction('Template.footerUserCountry', array('Piwik\\Plugins\\Provider\\Provider', 'footerUserCountry')); }
public function test_delete_ShouldTriggerAnEventOnceSiteWasActuallyDeleted() { $called = 0; $deletedSiteId = null; Piwik::addAction('SitesManager.deleteSite.end', function ($param) use(&$called, &$deletedSiteId) { $called++; $deletedSiteId = $param; }); $this->_addSite(); $siteId1 = $this->_addSite(); API::getInstance()->deleteSite($siteId1); $this->assertSame(1, $called); $this->assertSame($siteId1, $deletedSiteId); }
public static function setErrorHandler() { Piwik::addAction('Log.formatFileMessage', array('\\Piwik\\Error', 'formatFileAndDBLogMessage')); Piwik::addAction('Log.formatDatabaseMessage', array('\\Piwik\\Error', 'formatFileAndDBLogMessage')); Piwik::addAction('Log.formatScreenMessage', array('\\Piwik\\Error', 'formatScreenMessage')); set_error_handler(array('\\Piwik\\Error', 'errorHandler')); }