/**
  * @group Plugins
  */
 public function test_AddAndGet_AnotherSegment()
 {
     $name = 'name';
     $definition = 'searches>1,visitIp!=127.0.0.1';
     $idSegment = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1);
     $this->assertEquals($idSegment, 1);
     // Testing get()
     $segment = API::getInstance()->get($idSegment);
     $expected = array('idsegment' => '1', 'name' => $name, 'definition' => $definition, 'login' => 'superUserLogin', 'enable_all_users' => '1', 'enable_only_idsite' => '1', 'auto_archive' => '1', 'ts_last_edit' => null, 'deleted' => '0');
     unset($segment['ts_created']);
     $this->assertEquals($segment, $expected);
     // There is a segment to process for this particular site
     $model = Factory::getModel('Piwik\\Plugins\\SegmentEditor');
     $segments = $model->getSegmentsToAutoArchive($idSite);
     unset($segments[0]['ts_created']);
     $this->assertEquals($segments, array($expected));
     // There is no segment to process for a non existing site
     try {
         $model->getSegmentsToAutoArchive(33);
         $this->fail();
     } catch (Exception $e) {
         // expected
     }
     // There is no segment to process across all sites
     $segments = $model->getSegmentsToAutoArchive($idSite = false);
     $this->assertEquals($segments, array());
 }
Beispiel #2
0
    public function test_makeLogVisitsQueryString_whenSegment()
    {
        $model = Factory::getModel('Piwik\\Plugins\\Live');
        list($sql, $bind) = $model->makeLogVisitsQueryString($idSite = 1, $period = 'month', $date = '2010-01-01', $segment = 'customVariablePageName1==Test', $offset = 0, $limit = 100, $visitorId = 'abc', $minTimestamp = false, $filterSortOrder = false);
        $expectedSql = ' SELECT sub.* FROM
                (

                    SELECT log_inner.*
                    FROM (
                        SELECT log_visit.*
                        FROM ' . Common::prefixTable('log_visit') . ' AS log_visit
                          LEFT JOIN ' . Common::prefixTable('log_link_visit_action') . ' AS log_link_visit_action
                          ON log_link_visit_action.idvisit = log_visit.idvisit
                        WHERE ( log_visit.idsite in (?)
                          AND log_visit.idvisitor = ?
                          AND log_visit.visit_last_action_time >= ?
                          AND log_visit.visit_last_action_time <= ? )
                          AND ( log_link_visit_action.custom_var_k1 = ? )
                        ORDER BY idsite, visit_last_action_time DESC
                        LIMIT 100
                        ) AS log_inner
                    ORDER BY idsite, visit_last_action_time DESC
                    LIMIT 100
                 ) AS sub
                 GROUP BY sub.idvisit
                 ORDER BY sub.visit_last_action_time DESC
        ';
        $expectedBind = array('1', Common::hex2bin('abc'), '2010-01-01 00:00:00', '2010-02-01 00:00:00', 'Test');
        $this->assertEquals(SegmentTest::removeExtraWhiteSpaces($expectedSql), SegmentTest::removeExtraWhiteSpaces($sql));
        $this->assertEquals(SegmentTest::removeExtraWhiteSpaces($expectedBind), SegmentTest::removeExtraWhiteSpaces($bind));
    }
Beispiel #3
0
 /**
  * @param array $config
  */
 public function __construct($config)
 {
     $this->config = $config;
     $this->maxLifetime = ini_get('session.gc_maxlifetime');
     $this->model = Factory::getModel(__NAMESPACE__);
     $this->model->setConfig($config);
 }
 public function __construct($processNewSegmentsFrom, Model $segmentEditorModel = null, Cache $segmentListCache = null, Date $now = null, LoggerInterface $logger = null)
 {
     $this->processNewSegmentsFrom = $processNewSegmentsFrom;
     $this->segmentEditorModel = $segmentEditorModel ?: Factory::getModel('Piwik\\Plugins\\SegmentEditor');
     $this->segmentListCache = $segmentListCache ?: new Transient();
     $this->now = $now ?: Date::factory('now');
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
 public function getCronArchiveTokenAuth(&$tokens)
 {
     $model = Factory::getModel(__NAMESPACE__);
     $superUsers = $model->getUsersHavingSuperUserAccess();
     foreach ($superUsers as $superUser) {
         $tokens[] = $superUser['token_auth'];
     }
 }
 /**
  * Constructor.
  *
  * @param ArchiveInvalidator $invalidator
  * @param DuplicateActionRemover $duplicateActionRemover
  * @param Actions $actionsAccess
  * @param LoggerInterface $logger
  */
 public function __construct(ArchiveInvalidator $invalidator = null, DuplicateActionRemover $duplicateActionRemover = null, Actions $actionsAccess = null, LoggerInterface $logger = null)
 {
     parent::__construct();
     $this->archiveInvalidator = $invalidator ?: new ArchiveInvalidator();
     $this->duplicateActionRemover = $duplicateActionRemover ?: Factory::getModel('Piwik\\Plugins\\CoreAdminHome\\Model', 'DuplicateActionRemover');
     $this->actionsAccess = $actionsAccess ?: new Actions();
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
 public function __construct(Model $model = null, Date $purgeCustomRangesOlderThan = null, LoggerInterface $logger = null)
 {
     # Overriding the $model object injected by the DI container.
     # DI Container injects the Model class irrespective of the database used
     # (Mysql or Pgsql). Also, it doesn't set the Db object on the Model
     # class.
     $this->model = Factory::getModel('Piwik\\DataAccess');
     $this->purgeCustomRangesOlderThan = $purgeCustomRangesOlderThan ?: self::getDefaultCustomRangeToPurgeAgeThreshold();
     $this->yesterday = Date::factory('yesterday');
     $this->today = Date::factory('today');
     $this->now = time();
     $this->logger = $logger ?: StaticContainer::get('Psr\\Log\\LoggerInterface');
 }
Beispiel #8
0
 public function getAllSiteUrls()
 {
     $model = Factory::getModel(__NAMESPACE__);
     $siteIds = $model->getSitesId();
     $siteUrls = array();
     if (empty($siteIds)) {
         return array();
     }
     foreach ($siteIds as $siteId) {
         $siteId = (int) $siteId;
         $siteUrls[$siteId] = $model->getSiteUrlsFromId($siteId);
     }
     return $siteUrls;
 }
 public function setUp()
 {
     parent::setUp();
     \Piwik\Plugin\Manager::getInstance()->loadPlugin('UsersManager');
     \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
     // setup the access layer
     FakeAccess::setIdSitesView(array(1, 2));
     FakeAccess::setIdSitesAdmin(array(3, 4));
     //finally we set the user as a Super User by default
     FakeAccess::$superUser = true;
     FakeAccess::$superUserLogin = '******';
     $this->api = API::getInstance();
     $this->model = Factory::getModel('Piwik\\Plugins\\UsersManager');
 }
Beispiel #10
0
 private function getFirstTypeIfOnlyOneIsInUse()
 {
     $types = $this->typeManager->getAllTypes();
     if (count($types) === 1) {
         // only one type is in use, use this one for the wording
         return reset($types);
     } else {
         // multiple types are activated, check whether only one is actually in use
         $model = Factory::getModel(__NAMESPACE__);
         $typeIds = $model->getUsedTypeIds();
         if (count($typeIds) === 1) {
             $typeManager = new TypeManager();
             return $typeManager->getType(reset($typeIds));
         }
     }
 }
Beispiel #11
0
 public function setUp()
 {
     parent::setUp();
     $this->model = Factory::getModel('Piwik\\DataAccess');
     $this->model->createArchiveTable($this->tableName, 'archive_numeric');
 }
 protected function setReplyToAsSender(Mail $mail, array $report)
 {
     if (Config::getInstance()->General['scheduled_reports_replyto_is_user_email_and_alias']) {
         if (isset($report['login'])) {
             $userModel = Factory::getModel('Piwik\\Plugins\\UsersManager');
             $user = $userModel->getUser($report['login']);
             $mail->setReplyTo($user['email'], $user['alias']);
         }
     }
 }
Beispiel #13
0
 public function __construct()
 {
     $this->userModel = Factory::getModel('Piwik\\Plugins\\UsersManager');
 }
Beispiel #14
0
 /**
  * For each website ID, returns the access level of the given $userLogin.
  * If the user doesn't have any access to a website ('noaccess'),
  * this website will not be in the returned array.
  * If the user doesn't have any access, the returned array will be an empty array.
  *
  * @param string $userLogin User that has to be valid
  *
  * @return array    The returned array has the format
  *                    array(
  *                        idsite1 => 'view',
  *                        idsite2 => 'admin',
  *                        idsite3 => 'view',
  *                        ...
  *                    )
  */
 public function getSitesAccessFromUser($userLogin)
 {
     Piwik::checkUserHasSuperUserAccess();
     $this->checkUserExists($userLogin);
     // Super users have 'admin' access for every site
     if (Piwik::hasTheUserSuperUserAccess($userLogin)) {
         $return = array();
         $siteManagerModel = Factory::getModel('Piwik\\Plugins\\SitesManager');
         $sites = $siteManagerModel->getAllSites();
         foreach ($sites as $site) {
             $return[] = array('site' => $site['idsite'], 'access' => 'admin');
         }
         return $return;
     }
     return $this->model->getSitesAccessFromUser($userLogin);
 }
Beispiel #15
0
 private function createAdminUserForSite($idSite)
 {
     $login = '******';
     $passwordHash = UsersManager::getPasswordHash('password');
     $token = API::getInstance()->getTokenAuth($login, $passwordHash);
     $user = Factory::getModel('Piwik\\Plugins\\UsersManager');
     $user->addUser($login, $passwordHash, 'admin@piwik', 'alias', $token, '2014-01-01 00:00:00');
     $user->addUserAccess($login, 'admin', array($idSite));
     return $token;
 }
Beispiel #16
0
 private function loadLastVisitorDetailsFromDatabase($idSite, $period, $date, $segment = false, $offset = 0, $limit = 100, $minTimestamp = false, $filterSortOrder = false, $visitorId = false)
 {
     $model = Factory::getModel(__NAMESPACE__);
     $data = $model->queryLogVisits($idSite, $period, $date, $segment, $offset, $limit, $visitorId, $minTimestamp, $filterSortOrder);
     return $this->makeVisitorTableFromArray($data);
 }
Beispiel #17
0
 /**
  * Delete goals recorded for this site
  */
 public function deleteSiteGoals($idSite)
 {
     $model = Factory::getModel(__NAMESPACE__);
     $model->deleteGoalsForSite($idSite);
 }
Beispiel #18
0
 private function assertHasNotSite($idSite)
 {
     $model = Factory::getModel('Piwik\\Plugins\\SitesManager');
     $siteInfo = $model->getSiteFromId($idSite);
     $this->assertEmpty($siteInfo);
 }
Beispiel #19
0
 /**
  * @param int[] $idSegments
  */
 public function setSegmentsToForceFromSegmentIds($idSegments)
 {
     /** @var SegmentEditorModel $segmentEditorModel */
     # Generating model from the factory as the injected model will not take into
     # account the database while generating the model object.
     #$segmentEditorModel = StaticContainer::get('Piwik\Plugins\SegmentEditor\Model');
     $segmentEditorModel = Factory::getModel('Piwik\\Plugins\\SegmentEditor');
     $segments = $segmentEditorModel->getAllSegmentsAndIgnoreVisibility();
     $segments = array_filter($segments, function ($segment) use($idSegments) {
         return in_array($segment['idsegment'], $idSegments);
     });
     $segments = array_map(function ($segment) {
         return $segment['definition'];
     }, $segments);
     $this->segmentsToForce = $segments;
 }
 /**
  * @throws Exception if non-recoverable error
  */
 public function uninstall()
 {
     $model = Factory::getModel(__NAMESPACE__);
     $model->uninstall();
 }
Beispiel #21
0
 public static function createSuperUser($removeExisting = true)
 {
     $login = self::ADMIN_USER_LOGIN;
     $password = UsersManager::getPasswordHash(self::ADMIN_USER_PASSWORD);
     $token = self::getTokenAuth();
     $model = Factory::getModel('Piwik\\Plugins\\UsersManager');
     if ($removeExisting) {
         $model->deleteUserOnly($login);
     }
     $user = $model->getUser($login);
     if (empty($user)) {
         $model->addUser($login, $password, '*****@*****.**', $login, $token, Date::now()->getDatetime());
     } else {
         $model->updateUser($login, $password, '*****@*****.**', $login, $token);
     }
     if (empty($user['superuser_access'])) {
         $model->setSuperUserAccess($login, true);
     }
     return $model->getUserByTokenAuth($token);
 }
 private static function getModel()
 {
     return Factory::getModel('Piwik\\DataAccess');
 }
Beispiel #23
0
 public function setUp()
 {
     parent::setUp();
     $this->model = Factory::getModel('Piwik\\Plugins\\SitesManager');
 }
Beispiel #24
0
 /**
  * @param $visitorDetailsArray
  * @param $actionsLimit
  * @param $timezone
  * @return array
  */
 public static function enrichVisitorArrayWithActions($visitorDetailsArray, $actionsLimit, $timezone)
 {
     $idVisit = $visitorDetailsArray['idVisit'];
     $model = Factory::getModel(__NAMESPACE__);
     $actionDetails = $model->queryActionsForVisit($idVisit, $actionsLimit);
     $formatter = new Formatter();
     $maxCustomVariables = CustomVariables::getNumUsableCustomVariables();
     foreach ($actionDetails as $actionIdx => &$actionDetail) {
         $actionDetail =& $actionDetails[$actionIdx];
         $customVariablesPage = array();
         for ($i = 1; $i <= $maxCustomVariables; $i++) {
             if (!empty($actionDetail['custom_var_k' . $i])) {
                 $cvarKey = $actionDetail['custom_var_k' . $i];
                 $cvarKey = static::getCustomVariablePrettyKey($cvarKey);
                 $customVariablesPage[$i] = array('customVariablePageName' . $i => $cvarKey, 'customVariablePageValue' . $i => $actionDetail['custom_var_v' . $i]);
             }
             unset($actionDetail['custom_var_k' . $i]);
             unset($actionDetail['custom_var_v' . $i]);
         }
         if (!empty($customVariablesPage)) {
             $actionDetail['customVariables'] = $customVariablesPage;
         }
         if ($actionDetail['type'] == Action::TYPE_CONTENT) {
             unset($actionDetails[$actionIdx]);
             continue;
         } elseif ($actionDetail['type'] == Action::TYPE_EVENT_CATEGORY) {
             // Handle Event
             if (strlen($actionDetail['pageTitle']) > 0) {
                 $actionDetail['eventName'] = $actionDetail['pageTitle'];
             }
             unset($actionDetail['pageTitle']);
         } else {
             if ($actionDetail['type'] == Action::TYPE_SITE_SEARCH) {
                 // Handle Site Search
                 $actionDetail['siteSearchKeyword'] = $actionDetail['pageTitle'];
                 unset($actionDetail['pageTitle']);
             }
         }
         // Event value / Generation time
         if ($actionDetail['type'] == Action::TYPE_EVENT_CATEGORY) {
             if (strlen($actionDetail['custom_float']) > 0) {
                 $actionDetail['eventValue'] = round($actionDetail['custom_float'], self::EVENT_VALUE_PRECISION);
             }
         } elseif ($actionDetail['custom_float'] > 0) {
             $actionDetail['generationTime'] = $formatter->getPrettyTimeFromSeconds($actionDetail['custom_float'] / 1000, true);
         }
         unset($actionDetail['custom_float']);
         if ($actionDetail['type'] != Action::TYPE_EVENT_CATEGORY) {
             unset($actionDetail['eventCategory']);
             unset($actionDetail['eventAction']);
         }
         // Reconstruct url from prefix
         $url = Tracker\PageUrl::reconstructNormalizedUrl($actionDetail['url'], $actionDetail['url_prefix']);
         $url = Common::unsanitizeInputValue($url);
         $actionDetail['url'] = $url;
         unset($actionDetail['url_prefix']);
     }
     // If the visitor converted a goal, we shall select all Goals
     $goalDetails = $model->queryGoalConversionsForVisit($idVisit, $actionsLimit);
     $ecommerceDetails = $model->queryEcommerceConversionsForVisit($idVisit, $actionsLimit);
     foreach ($ecommerceDetails as &$ecommerceDetail) {
         if ($ecommerceDetail['type'] == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART) {
             unset($ecommerceDetail['orderId']);
             unset($ecommerceDetail['revenueSubTotal']);
             unset($ecommerceDetail['revenueTax']);
             unset($ecommerceDetail['revenueShipping']);
             unset($ecommerceDetail['revenueDiscount']);
         }
         // 25.00 => 25
         foreach ($ecommerceDetail as $column => $value) {
             if (strpos($column, 'revenue') !== false) {
                 if ($value == round($value)) {
                     $ecommerceDetail[$column] = round($value);
                 }
             }
         }
     }
     // Enrich ecommerce carts/orders with the list of products
     usort($ecommerceDetails, array('static', 'sortByServerTime'));
     foreach ($ecommerceDetails as &$ecommerceConversion) {
         $idOrder = isset($ecommerceConversion['orderId']) ? $ecommerceConversion['orderId'] : GoalManager::ITEM_IDORDER_ABANDONED_CART;
         $itemsDetails = $model->queryEcommerceItemsForOrder($idVisit, $idOrder, $actionsLimit);
         foreach ($itemsDetails as &$detail) {
             if ($detail['price'] == round($detail['price'])) {
                 $detail['price'] = round($detail['price']);
             }
         }
         $ecommerceConversion['itemDetails'] = $itemsDetails;
     }
     // Enrich with time spent per action
     foreach ($actionDetails as $actionIdx => &$actionDetail) {
         // Set the time spent for this action (which is the timeSpentRef of the next action)
         $nextActionFound = isset($actionDetails[$actionIdx + 1]);
         if ($nextActionFound) {
             $actionDetail['timeSpent'] = $actionDetails[$actionIdx + 1]['timeSpentRef'];
         } else {
             // Last action of a visit.
             // By default, Piwik does not know how long the user stayed on the page
             // If enableHeartBeatTimer() is used in piwik.js then we can find the accurate time on page for the last pageview
             $timeOfLastActionOrPingInVisitRow = $visitorDetailsArray['lastActionTimestamp'];
             $timeOfLastAction = Date::factory($actionDetail['serverTimePretty'])->getTimestamp();
             $timeSpentOnPage = $timeOfLastActionOrPingInVisitRow - $timeOfLastAction;
             // Safe net, we assume the time is correct when it's more than 10 seconds
             if ($timeSpentOnPage > 10) {
                 $actionDetail['timeSpent'] = $timeSpentOnPage;
             }
         }
         if (isset($actionDetail['timeSpent'])) {
             $actionDetail['timeSpentPretty'] = $formatter->getPrettyTimeFromSeconds($actionDetail['timeSpent'], true);
         }
         unset($actionDetails[$actionIdx]['timeSpentRef']);
         // not needed after timeSpent is added
     }
     $actions = array_merge($actionDetails, $goalDetails, $ecommerceDetails);
     usort($actions, array('static', 'sortByServerTime'));
     foreach ($actions as &$action) {
         unset($action['idlink_va']);
     }
     $visitorDetailsArray['goalConversions'] = count($goalDetails);
     $visitorDetailsArray['actionDetails'] = $actions;
     foreach ($visitorDetailsArray['actionDetails'] as &$details) {
         switch ($details['type']) {
             case 'goal':
                 $details['icon'] = 'plugins/Morpheus/images/goal.png';
                 break;
             case Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER:
             case Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART:
                 $details['icon'] = 'plugins/Morpheus/images/' . $details['type'] . '.gif';
                 break;
             case Action::TYPE_DOWNLOAD:
                 $details['type'] = 'download';
                 $details['icon'] = 'plugins/Morpheus/images/download.png';
                 break;
             case Action::TYPE_OUTLINK:
                 $details['type'] = 'outlink';
                 $details['icon'] = 'plugins/Morpheus/images/link.gif';
                 break;
             case Action::TYPE_SITE_SEARCH:
                 $details['type'] = 'search';
                 $details['icon'] = 'plugins/Morpheus/images/search_ico.png';
                 break;
             case Action::TYPE_EVENT_CATEGORY:
                 $details['type'] = 'event';
                 $details['icon'] = 'plugins/Morpheus/images/event.png';
                 break;
             default:
                 $details['type'] = 'action';
                 $details['icon'] = null;
                 break;
         }
         // Convert datetimes to the site timezone
         $dateTimeVisit = Date::factory($details['serverTimePretty'], $timezone);
         $details['serverTimePretty'] = $dateTimeVisit->getLocalized(Piwik::translate('CoreHome_ShortDateFormat') . ' %time%');
         $details['timestamp'] = $dateTimeVisit->getTimestamp();
     }
     return $visitorDetailsArray;
 }
 private static function getModel()
 {
     return Factory::getModel(__NAMESPACE__);
 }
 /**
  * @param DataTable $visits
  * @param $visitorId
  * @param $segment
  */
 private function handleAdjacentVisitorIds(DataTable $visits, $visitorId, $segment)
 {
     // get visitor IDs that are adjacent to this one in log_visit
     // TODO: make sure order of visitor ids is not changed if a returning visitor visits while the user is
     //       looking at the popup.
     $rows = $visits->getRows();
     $latestVisitTime = reset($rows)->getColumn('lastActionDateTime');
     $model = Factory::getModel(__NAMESPACE__);
     $this->profile['nextVisitorId'] = $model->queryAdjacentVisitorId($this->idSite, $visitorId, $latestVisitTime, $segment, $getNext = true);
     $this->profile['previousVisitorId'] = $model->queryAdjacentVisitorId($this->idSite, $visitorId, $latestVisitTime, $segment, $getNext = false);
 }