now() public static method

Returns a date object set to now in UTC (same as {@link today()}, except that the time is also set).
public static now ( ) : Date
return Date
Ejemplo n.º 1
0
 /**
  * @group Core
  */
 public function testFactoryTimezone()
 {
     // now in UTC converted to UTC+10 means adding 10 hours
     $date = Date::factory('now', 'UTC+10');
     $dateExpected = Date::now()->addHour(10);
     $this->assertEquals($dateExpected->getDatetime(), $date->getDatetime());
     // Congo is in UTC+1 all year long (no DST)
     $dateExpected = Date::factory('now')->addHour(1);
     $date = Date::factory('now', 'Africa/Brazzaville');
     $this->assertEquals($dateExpected->getDatetime(), $date->getDatetime());
     // yesterday same time in Congo is the same as today in Congo - 24 hours
     $date = Date::factory('yesterdaySameTime', 'Africa/Brazzaville');
     $dateExpected = Date::factory('now', 'Africa/Brazzaville')->subHour(24);
     $this->assertEquals($dateExpected->getDatetime(), $date->getDatetime());
     if (SettingsServer::isTimezoneSupportEnabled()) {
         // convert to/from local time
         $now = time();
         $date = Date::factory($now, 'America/New_York');
         $time = $date->getTimestamp();
         $this->assertTrue($time < $now);
         $date = Date::factory($time)->setTimezone('America/New_York');
         $time = $date->getTimestamp();
         $this->assertEquals($now, $time);
     }
 }
Ejemplo n.º 2
0
 private static function migrateConfigSuperUserToDb()
 {
     $config = Config::getInstance();
     if (!$config->existsLocalConfig()) {
         return;
     }
     try {
         $superUser = $config->superuser;
     } catch (\Exception $e) {
         $superUser = null;
     }
     if (!empty($superUser['bridge']) || empty($superUser) || empty($superUser['login'])) {
         // there is a super user which is not from the config but from the bridge, that means we already have
         // a super user in the database
         return;
     }
     $userApi = UsersManagerApi::getInstance();
     try {
         Db::get()->insert(Common::prefixTable('user'), array('login' => $superUser['login'], 'password' => $superUser['password'], 'alias' => $superUser['login'], 'email' => $superUser['email'], 'token_auth' => $userApi->getTokenAuth($superUser['login'], $superUser['password']), 'date_registered' => Date::now()->getDatetime(), 'superuser_access' => 1));
     } catch (\Exception $e) {
         echo "There was an issue, but we proceed: " . $e->getMessage();
     }
     if (array_key_exists('salt', $superUser)) {
         $salt = $superUser['salt'];
     } else {
         $salt = Common::generateUniqId();
     }
     $config->General['salt'] = $salt;
     $config->superuser = array();
     $config->forceSave();
 }
Ejemplo n.º 3
0
 public function index()
 {
     Piwik::checkUserHasSuperUserAccess();
     $view = new View('@TasksTimetable/index.twig');
     $this->setGeneralVariablesView($view);
     $tasks = Option::get('TaskScheduler.timetable');
     if (!empty($tasks)) {
         $tasks = unserialize($tasks);
     }
     if (empty($tasks)) {
         $tasks = array();
     } else {
         asort($tasks);
     }
     $tsNow = Date::now()->getTimestamp();
     $dateFormat = Piwik::translate(Date::DATE_FORMAT_LONG) . ' h:mm:ss';
     $formatter = new Formatter();
     $tasksFormatted = array();
     foreach ($tasks as $name => $timestamp) {
         $tasksFormatted[] = array('name' => $name, 'executionDate' => Date::factory($timestamp)->getLocalized($dateFormat), 'ts_difference' => $formatter->getPrettyTimeFromSeconds($timestamp - $tsNow));
     }
     $view->currentTime = Date::now()->getLocalized($dateFormat);
     $view->tasks = $tasksFormatted;
     return $view->render();
 }
 public function test_deleteAlertsForWebsite()
 {
     $this->createAlert('Initial1', array(), array(2));
     $this->createAlert('Initial2', array(), array(1, 2, 3));
     $this->createAlert('Initial3', array(), array(1));
     $this->createAlert('Initial4', array(), array(1, 3));
     $this->createAlert('Initial5', array(), array(2));
     $this->createAlert('Initial6', array(), array(2));
     $this->model->triggerAlert(1, 1, 99, 48, Date::now()->getDatetime());
     $this->model->triggerAlert(1, 2, 99, 48, Date::now()->getDatetime());
     $this->model->triggerAlert(2, 3, 99, 48, Date::now()->getDatetime());
     $this->model->triggerAlert(3, 2, 99, 48, Date::now()->getDatetime());
     $alerts = $this->model->getTriggeredAlerts(array(1, 2, 3), 'superUserLogin');
     $this->assertCount(4, $alerts);
     $this->plugin->deleteAlertsForSite(2);
     $alerts = $this->model->getAllAlerts();
     $this->assertCount(6, $alerts);
     $this->assertEquals($alerts[0]['id_sites'], array());
     $this->assertEquals($alerts[1]['id_sites'], array(1, 3));
     $this->assertEquals($alerts[2]['id_sites'], array(1));
     $this->assertEquals($alerts[3]['id_sites'], array(1, 3));
     $this->assertEquals($alerts[4]['id_sites'], array());
     $this->assertEquals($alerts[5]['id_sites'], array());
     $alerts = $this->model->getTriggeredAlerts(array(1, 2, 3), 'superUserLogin');
     $this->assertCount(2, $alerts);
 }
Ejemplo n.º 5
0
 /**
  * Caches the intermediate DataTables used in the getIndividualReportsSummary and
  * getIndividualMetricsSummary reports in the option table.
  */
 public function cacheDataByArchiveNameReports()
 {
     $api = API::getInstance();
     $api->getIndividualReportsSummary(true);
     $api->getIndividualMetricsSummary(true);
     $now = Date::now()->getLocalized("%longYear%, %shortMonth% %day%");
     Option::set(DBStats::TIME_OF_LAST_TASK_RUN_OPTION, $now);
 }
Ejemplo n.º 6
0
 /**
  * Caches the intermediate DataTables used in the getIndividualReportsSummary and
  * getIndividualMetricsSummary reports in the option table.
  */
 public function cacheDataByArchiveNameReports()
 {
     $api = API::getInstance();
     $api->getIndividualReportsSummary(true);
     $api->getIndividualMetricsSummary(true);
     $now = Date::now()->getLocalized(Date::DATE_FORMAT_SHORT);
     Option::set(DBStats::TIME_OF_LAST_TASK_RUN_OPTION, $now);
 }
Ejemplo n.º 7
0
 public function testRangeTodayUtcPlus12()
 {
     // rather ugly test, UTC+23 doesn't exist, but it's a way to test that last1 in UTC+23 will be "our" UTC tomorrow
     $range = new Range('day', 'last1', 'UTC+23');
     $today = Date::now()->addHour(23);
     $correct = array($today->toString());
     $correct = array_reverse($correct);
     $this->assertEquals(1, $range->getNumberOfSubperiods());
     $this->assertEquals($correct, $range->toString());
 }
 private function assertDeprecatedClassIsRemoved($className, $removalDate)
 {
     $now = Date::now();
     $removalDate = Date::factory($removalDate);
     $classExists = class_exists($className);
     if (!$now->isLater($removalDate)) {
         $errorMessage = $className . ' should still exists until ' . $removalDate . ' although it is deprecated.';
         $this->assertTrue($classExists, $errorMessage);
         return;
     }
     $errorMessage = $className . ' should be removed as the method is deprecated but it is not.';
     $this->assertFalse($classExists, $errorMessage);
 }
Ejemplo n.º 9
0
 private function assertDeprecatedMethodIsRemoved($className, $method, $removalDate)
 {
     $now = \Piwik\Date::now();
     $removalDate = \Piwik\Date::factory($removalDate);
     $class = new ReflectionClass($className);
     $methodExists = $class->hasMethod($method);
     if (!$now->isLater($removalDate)) {
         $errorMessage = $className . '::' . $method . ' should still exists until ' . $removalDate . ' although it is deprecated.';
         $this->assertTrue($methodExists, $errorMessage);
         return;
     }
     $errorMessage = $className . '::' . $method . ' should be removed as the method is deprecated but it is not.';
     $this->assertFalse($methodExists, $errorMessage);
 }
Ejemplo n.º 10
0
 /**
  * @param array $dimension
  * @param int $idSite
  * @param int $maxValuesToReturn
  * @return array
  */
 public function getMostUsedActionDimensionValues($dimension, $idSite, $maxValuesToReturn)
 {
     $maxValuesToReturn = (int) $maxValuesToReturn;
     $idSite = (int) $idSite;
     $startDate = Date::now()->subDay(60)->toString();
     $name = LogTable::buildCustomDimensionColumnName($dimension);
     $table = Common::prefixTable('log_link_visit_action');
     $query = "SELECT {$name}, count({$name}) as countName FROM {$table}\n                  WHERE idsite = ? and server_time > {$startDate} and {$name} is not null\n                  GROUP by {$name}\n                  ORDER BY countName DESC LIMIT {$maxValuesToReturn}";
     $rows = Db::get()->fetchAll($query, array($idSite));
     $values = array();
     foreach ($rows as $row) {
         $values[] = $row[$name];
     }
     return $values;
 }
Ejemplo n.º 11
0
 /**
  * Main view showing listing of websites and settings
  */
 public function index()
 {
     $view = new View('@SitesManager/index');
     Site::clearCache();
     if (Piwik::isUserIsSuperUser()) {
         $sitesRaw = API::getInstance()->getAllSites();
     } else {
         $sitesRaw = API::getInstance()->getSitesWithAdminAccess();
     }
     // Gets sites after Site.setSite hook was called
     $sites = array_values(Site::getSites());
     if (count($sites) != count($sitesRaw)) {
         throw new Exception("One or more website are missing or invalid.");
     }
     foreach ($sites as &$site) {
         $site['alias_urls'] = API::getInstance()->getSiteUrlsFromId($site['idsite']);
         $site['excluded_ips'] = explode(',', $site['excluded_ips']);
         $site['excluded_parameters'] = explode(',', $site['excluded_parameters']);
         $site['excluded_user_agents'] = explode(',', $site['excluded_user_agents']);
     }
     $view->adminSites = $sites;
     $view->adminSitesCount = count($sites);
     $timezones = API::getInstance()->getTimezonesList();
     $view->timezoneSupported = SettingsServer::isTimezoneSupportEnabled();
     $view->timezones = Common::json_encode($timezones);
     $view->defaultTimezone = API::getInstance()->getDefaultTimezone();
     $view->currencies = Common::json_encode(API::getInstance()->getCurrencyList());
     $view->defaultCurrency = API::getInstance()->getDefaultCurrency();
     $view->utcTime = Date::now()->getDatetime();
     $excludedIpsGlobal = API::getInstance()->getExcludedIpsGlobal();
     $view->globalExcludedIps = str_replace(',', "\n", $excludedIpsGlobal);
     $excludedQueryParametersGlobal = API::getInstance()->getExcludedQueryParametersGlobal();
     $view->globalExcludedQueryParameters = str_replace(',', "\n", $excludedQueryParametersGlobal);
     $globalExcludedUserAgents = API::getInstance()->getExcludedUserAgentsGlobal();
     $view->globalExcludedUserAgents = str_replace(',', "\n", $globalExcludedUserAgents);
     $view->globalSearchKeywordParameters = API::getInstance()->getSearchKeywordParametersGlobal();
     $view->globalSearchCategoryParameters = API::getInstance()->getSearchCategoryParametersGlobal();
     $view->isSearchCategoryTrackingEnabled = \Piwik\Plugin\Manager::getInstance()->isPluginActivated('CustomVariables');
     $view->allowSiteSpecificUserAgentExclude = API::getInstance()->isSiteSpecificUserAgentExcludeEnabled();
     $view->globalKeepURLFragments = API::getInstance()->getKeepURLFragmentsGlobal();
     $view->currentIpAddress = IP::getIpFromHeader();
     $view->showAddSite = (bool) Common::getRequestVar('showaddsite', false);
     $this->setBasicVariablesView($view);
     return $view->render();
 }
Ejemplo n.º 12
0
 /**
  * Returns the user on hand the settings done
  * in the config.ini.php.
  */
 public function getUser()
 {
     $auth = new Auth();
     $login = $auth->getLogin();
     $alias = $auth->getAlias();
     $websites = $auth->getWebsites();
     $email = $auth->getEmail();
     $token = $auth->getToken();
     $superuser = $auth->getSuperuser();
     if (!$this->userExists($login)) {
         $this->addUser($login, md5($auth->getPassword()), $email, $alias, $token, Date::now()->getDatetime(), 0);
         foreach ($websites as $w) {
             $this->addUserAccess($login, $w['access'], $w['ids']);
         }
         if ($superuser) {
             $this->setSuperUserAccess($login, $superuser);
         }
     } else {
         if ($superuser) {
             $this->setSuperUserAccess($login, $superuser);
         }
         if ($this->getSitesAccessFromUser($login) != 0) {
             $localSiteIds = array();
             foreach ($this->getSitesAccessFromUser($login) as $siteAccess) {
                 if (!in_array($siteAccess['site'], $websites[0]['ids']) || !in_array($siteAccess['site'], $websites[1]['ids'])) {
                     $this->deleteUserAccess($login, $siteAccess['site']);
                 } else {
                     array_push($localSiteIds, $siteAccess['site']);
                 }
             }
             foreach ($websites[0]['ids'] as $si) {
                 if (!in_array($si, $localSiteIds)) {
                     $this->addUserAccess($login, $websites[0]['access'], $si);
                 }
             }
             foreach ($websites[1]['ids'] as $si) {
                 if (!in_array($si, $localSiteIds)) {
                     $this->addUserAccess($login, $websites[1]['access'], $si);
                 }
             }
         }
     }
     return array('login' => $login, 'alias' => $alias, 'email' => $email, 'token_auth' => $token, 'superuser_access' => $superuser);
 }
 /**
  * Authenticates user
  *
  * @return AuthResult
  */
 public function authenticate()
 {
     $logger = StaticContainer::get('Psr\\Log\\LoggerInterface');
     $model = new Model();
     $user = $model->getUser($this->login);
     if (!$user) {
         $user = $model->getUserByTokenAuth($this->token_auth);
         if (!$user) {
             $logger->info("Creating user " . $this->login);
             $model->addUser($this->login, $this->getTokenAuthSecret(), $this->email, $this->alias, $this->token_auth, Date::now()->getDatetime());
             $user = $model->getUser($this->login);
         }
     }
     $accessCode = $user['superuser_access'] ? AuthResult::SUCCESS_SUPERUSER_AUTH_CODE : AuthResult::SUCCESS;
     $this->login = $user['login'];
     if ($this->getViewableUserStatus() || $this->getSuperUserStatus()) {
         $site_ids = $this->getDefaultSiteIds();
         $current_accesses = array();
         foreach ($site_ids as $site_id) {
             $accesses = $model->getUsersAccessFromSite($site_id);
             foreach ($accesses as $user => $access) {
                 if ($this->login == $user && ($access == "view" || $access == 'admin')) {
                     $current_accesses[] = $site_id;
                 }
             }
         }
         $new_accesses = array();
         foreach ($site_ids as $site_id) {
             if (!in_array($site_id, $current_accesses)) {
                 $new_accesses[] = $site_id;
             }
         }
         if (count($new_accesses) > 0) {
             $logger->info("Adding default site ids to " . $this->login);
             $model->addUserAccess($this->login, "view", $new_accesses);
         }
     }
     $is_superuser = $this->getSuperUserStatus();
     $model->setSuperUserAccess($this->login, $is_superuser);
     return new AuthResult($accessCode, $this->login, $this->token_auth);
 }
 public function trackApiCall(&$return, $endHookParams)
 {
     $endTime = microtime(true);
     $name = $endHookParams['module'];
     $method = $name . '.' . $endHookParams['action'];
     $neededTimeInMs = 0;
     do {
         $call = array_pop($this->profilingStack);
         // we need to make sure the call was actually for this method to not send wrong data.
         if ($method === $call['method']) {
             $neededTimeInMs = ceil(($endTime - $call['time']) * 1000);
             break;
         }
     } while (!empty($this->profilingStack));
     if (empty($neededTimeInMs)) {
         return;
     }
     $profiles = StaticContainer::get('Piwik\\Plugins\\AnonymousPiwikUsageMeasurement\\Tracker\\Profiles');
     $now = Date::now()->getDatetime();
     $category = 'API';
     $profiles->pushProfile($now, $category, $name, $method, $count = 1, (int) $neededTimeInMs);
 }
Ejemplo n.º 15
0
Archivo: API.php Proyecto: bnkems/piwik
 /**
  * Create a user upon call from frontend
  * This API method will be called from Controller of this module
  * 
  * @param String    $userLogin
  * @param String    $userPassword
  * @param String    $userEmail                         
  * @return Boolean
  */
 public function createUser($userLogin, $userPassword, $userEmail)
 {
     if ($userLogin and $userPassword) {
         $userManager = UserManagerAPI::getInstance();
         if (!$this->userManagerModel->userEmailExists($userEmail) and !$this->userManagerModel->userExists($userLogin)) {
             $password = Common::unsanitizeInputValue($userPassword);
             UserManager::checkPassword($password);
             $passwordTransformed = UserManager::getPasswordHash($password);
             $token_auth = $userManager->getTokenAuth($userEmail, $passwordTransformed);
             try {
                 $this->userManagerModel->addUser($userEmail, $passwordTransformed, $userEmail, $userLogin, $token_auth, Date::now()->getDatetime());
                 return true;
             } catch (Exception $e) {
                 //throw new Exception($e->getMessage());
                 $this->__errors[] = 'Error in creating the user in database.';
             }
         } else {
             $this->__errors[] = 'User email already exists or the login name already exists';
         }
     }
     return false;
 }
Ejemplo n.º 16
0
 /**
  * Add a website.
  * Requires Super User access.
  *
  * The website is defined by a name and an array of URLs.
  * @param string $siteName Site name
  * @param array|string $urls The URLs array must contain at least one URL called the 'main_url' ;
  *                        if several URLs are provided in the array, they will be recorded
  *                        as Alias URLs for this website.
  * @param int $ecommerce Is Ecommerce Reporting enabled for this website?
  * @param null $siteSearch
  * @param string $searchKeywordParameters Comma separated list of search keyword parameter names
  * @param string $searchCategoryParameters Comma separated list of search category parameter names
  * @param string $excludedIps Comma separated list of IPs to exclude from the reports (allows wildcards)
  * @param null $excludedQueryParameters
  * @param string $timezone Timezone string, eg. 'Europe/London'
  * @param string $currency Currency, eg. 'EUR'
  * @param string $group Website group identifier
  * @param string $startDate Date at which the statistics for this website will start. Defaults to today's date in YYYY-MM-DD format
  * @param null|string $excludedUserAgents
  * @param int $keepURLFragments If 1, URL fragments will be kept when tracking. If 2, they
  *                              will be removed. If 0, the default global behavior will be used.
  * @see getKeepURLFragmentsGlobal.
  * @param string $type The website type, defaults to "website" if not set.
  *
  * @return int the website ID created
  */
 public function addSite($siteName, $urls, $ecommerce = null, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = null, $keepURLFragments = null, $type = null)
 {
     Piwik::checkUserHasSuperUserAccess();
     $this->checkName($siteName);
     $urls = $this->cleanParameterUrls($urls);
     $this->checkUrls($urls);
     $this->checkAtLeastOneUrl($urls);
     $siteSearch = $this->checkSiteSearch($siteSearch);
     list($searchKeywordParameters, $searchCategoryParameters) = $this->checkSiteSearchParameters($searchKeywordParameters, $searchCategoryParameters);
     $keepURLFragments = (int) $keepURLFragments;
     self::checkKeepURLFragmentsValue($keepURLFragments);
     $timezone = trim($timezone);
     if (empty($timezone)) {
         $timezone = $this->getDefaultTimezone();
     }
     $this->checkValidTimezone($timezone);
     if (empty($currency)) {
         $currency = $this->getDefaultCurrency();
     }
     $this->checkValidCurrency($currency);
     $db = Db::get();
     $url = $urls[0];
     $urls = array_slice($urls, 1);
     $bind = array('name' => $siteName, 'main_url' => $url);
     $bind['excluded_ips'] = $this->checkAndReturnExcludedIps($excludedIps);
     $bind['excluded_parameters'] = $this->checkAndReturnCommaSeparatedStringList($excludedQueryParameters);
     $bind['excluded_user_agents'] = $this->checkAndReturnCommaSeparatedStringList($excludedUserAgents);
     $bind['keep_url_fragment'] = $keepURLFragments;
     $bind['timezone'] = $timezone;
     $bind['currency'] = $currency;
     $bind['ecommerce'] = (int) $ecommerce;
     $bind['sitesearch'] = $siteSearch;
     $bind['sitesearch_keyword_parameters'] = $searchKeywordParameters;
     $bind['sitesearch_category_parameters'] = $searchCategoryParameters;
     $bind['ts_created'] = !is_null($startDate) ? Date::factory($startDate)->getDatetime() : Date::now()->getDatetime();
     $bind['type'] = $this->checkAndReturnType($type);
     if (!empty($group) && Piwik::hasUserSuperUserAccess()) {
         $bind['group'] = trim($group);
     } else {
         $bind['group'] = "";
     }
     $db->insert(Common::prefixTable("site"), $bind);
     $idSite = $db->lastInsertId();
     $this->insertSiteUrls($idSite, $urls);
     // we reload the access list which doesn't yet take in consideration this new website
     Access::getInstance()->reloadAccess();
     $this->postUpdateWebsite($idSite);
     /**
      * Triggered after a site has been added.
      *
      * @param int $idSite The ID of the site that was added.
      */
     Piwik::postEvent('SitesManager.addSite.end', array($idSite));
     return (int) $idSite;
 }
Ejemplo n.º 17
0
 public static function createSuperUser($removeExisting = true)
 {
     $login = self::ADMIN_USER_LOGIN;
     $password = UsersManager::getPasswordHash(self::ADMIN_USER_PASSWORD);
     $token = self::getTokenAuth();
     $model = new \Piwik\Plugins\UsersManager\Model();
     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);
 }
Ejemplo n.º 18
0
 /**
  * Returns the visitor ID of the most recent visit.
  *
  * @param int $idSite
  * @param bool|string $segment
  * @return string
  */
 public function getMostRecentVisitorId($idSite, $segment = false)
 {
     Piwik::checkUserHasViewAccess($idSite);
     // for faster performance search for a visitor within the last 7 days first
     $minTimestamp = Date::now()->subDay(7)->getTimestamp();
     $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp);
     if (0 >= $dataTable->getRowsCount()) {
         $minTimestamp = Date::now()->subYear(1)->getTimestamp();
         // no visitor found in last 7 days, look further back for up to 1 year. This query will be slower
         $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp);
     }
     if (0 >= $dataTable->getRowsCount()) {
         // no visitor found in last year, look over all logs. This query might be quite slow
         $dataTable = $this->loadLastVisitorDetailsFromDatabase($idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1);
     }
     if (0 >= $dataTable->getRowsCount()) {
         return false;
     }
     $visitorFactory = new VisitorFactory();
     $visitDetails = $dataTable->getFirstRow()->getColumns();
     $visitor = $visitorFactory->create($visitDetails);
     return $visitor->getVisitorId();
 }
Ejemplo n.º 19
0
 /**
  * Adds a new stored segment.
  *
  * @param string $name The new name of the segment.
  * @param string $definition The new definition of the segment.
  * @param bool $idSite If supplied, associates the stored segment with as single site.
  * @param bool $autoArchive Whether to automatically archive data with the segment or not.
  * @param bool $enabledAllUsers Whether the stored segment is viewable by all users or just the one that created it.
  *
  * @return int The newly created segment Id
  */
 public function add($name, $definition, $idSite = false, $autoArchive = false, $enabledAllUsers = false)
 {
     $this->checkUserCanAddNewSegment($idSite);
     $idSite = $this->checkIdSite($idSite);
     $this->checkSegmentName($name);
     $definition = $this->checkSegmentValue($definition, $idSite);
     $enabledAllUsers = $this->checkEnabledAllUsers($enabledAllUsers);
     $autoArchive = $this->checkAutoArchive($autoArchive, $idSite);
     $db = Db::get();
     $bind = array('name' => $name, 'definition' => $definition, 'login' => Piwik::getCurrentUserLogin(), 'enable_all_users' => $enabledAllUsers, 'enable_only_idsite' => $idSite, 'auto_archive' => $autoArchive, 'ts_created' => Date::now()->getDatetime(), 'deleted' => 0);
     $db->insert(Common::prefixTable("segment"), $bind);
     return $db->lastInsertId();
 }
Ejemplo n.º 20
0
 /**
  * Add a user in the database.
  * A user is defined by
  * - a login that has to be unique and valid
  * - a password that has to be valid
  * - an alias
  * - an email that has to be in a correct format
  *
  * @see userExists()
  * @see isValidLoginString()
  * @see isValidPasswordString()
  * @see isValidEmailString()
  *
  * @exception in case of an invalid parameter
  */
 public function addUser($userLogin, $password, $email, $alias = false)
 {
     Piwik::checkUserIsSuperUser();
     $this->checkLogin($userLogin);
     $this->checkUserIsNotSuperUser($userLogin);
     $this->checkEmail($email);
     $password = Common::unsanitizeInputValue($password);
     UsersManager::checkPassword($password);
     $alias = $this->getCleanAlias($alias, $userLogin);
     $passwordTransformed = UsersManager::getPasswordHash($password);
     $token_auth = $this->getTokenAuth($userLogin, $passwordTransformed);
     $db = Db::get();
     $db->insert(Common::prefixTable("user"), array('login' => $userLogin, 'password' => $passwordTransformed, 'alias' => $alias, 'email' => $email, 'token_auth' => $token_auth, 'date_registered' => Date::now()->getDatetime()));
     // we reload the access list which doesn't yet take in consideration this new user
     Access::getInstance()->reloadAccess();
     Cache::deleteTrackerCache();
     /**
      * Triggered after a new user is created.
      * 
      * @param string $userLogin The new user's login handle.
      */
     Piwik::postEvent('UsersManager.addUser.end', array($userLogin));
 }
Ejemplo n.º 21
0
 public function test_getTriggeredAlerts_ShouldReturnAllThatMatchesLoginAndIdSite()
 {
     $idSite = 1;
     $this->setSuperUser();
     $this->model->triggerAlert(2, $idSite, 99, 48, Date::now()->getDatetime());
     $triggeredAlerts = $this->api->getTriggeredAlerts(array($idSite));
     $this->assertCount(1, $triggeredAlerts);
     $triggeredAlerts = $this->api->getTriggeredAlerts(array($idSite, 2));
     $this->assertCount(1, $triggeredAlerts);
     // no matching site
     $triggeredAlerts = $this->api->getTriggeredAlerts(array(2));
     $this->assertCount(0, $triggeredAlerts);
     // different login
     FakeAccess::$identity = 'differentLoginButStillSuperuser';
     $triggeredAlerts = $this->api->getTriggeredAlerts(array($idSite, 2));
     $this->assertCount(0, $triggeredAlerts);
     // different login
     $this->setUser();
     FakeAccess::$idSitesView = array(1);
     $triggeredAlerts = $this->api->getTriggeredAlerts(array(1));
     $this->assertCount(0, $triggeredAlerts);
 }
Ejemplo n.º 22
0
 /**
  * Add a user in the database.
  * A user is defined by
  * - a login that has to be unique and valid
  * - a password that has to be valid
  * - an alias
  * - an email that has to be in a correct format
  *
  * @see userExists()
  * @see isValidLoginString()
  * @see isValidPasswordString()
  * @see isValidEmailString()
  *
  * @exception in case of an invalid parameter
  */
 public function addUser($userLogin, $password, $email, $alias = false, $_isPasswordHashed = false)
 {
     Piwik::checkUserHasSuperUserAccess();
     $this->checkLogin($userLogin);
     $this->checkEmail($email);
     $password = Common::unsanitizeInputValue($password);
     if (!$_isPasswordHashed) {
         UsersManager::checkPassword($password);
         $passwordTransformed = UsersManager::getPasswordHash($password);
     } else {
         $passwordTransformed = $password;
     }
     $alias = $this->getCleanAlias($alias, $userLogin);
     $token_auth = $this->getTokenAuth($userLogin, $passwordTransformed);
     $this->model->addUser($userLogin, $passwordTransformed, $email, $alias, $token_auth, Date::now()->getDatetime());
     // we reload the access list which doesn't yet take in consideration this new user
     Access::getInstance()->reloadAccess();
     Cache::deleteTrackerCache();
     /**
      * Triggered after a new user is created.
      *
      * @param string $userLogin The new user's login handle.
      */
     Piwik::postEvent('UsersManager.addUser.end', array($userLogin, $email, $password, $alias));
 }
Ejemplo n.º 23
0
 public function sendReport($idReport, $period = false, $date = false)
 {
     Piwik::checkUserIsNotAnonymous();
     $reports = $this->getReports($idSite = false, false, $idReport);
     $report = reset($reports);
     if ($report['period'] == 'never') {
         $report['period'] = 'day';
     }
     if (!empty($period)) {
         $report['period'] = $period;
     }
     if (empty($date)) {
         $date = Date::now()->subPeriod(1, $report['period'])->toString();
     }
     $language = \Piwik\Plugins\LanguagesManager\API::getInstance()->getLanguageForUser($report['login']);
     // generate report
     list($outputFilename, $prettyDate, $reportSubject, $reportTitle, $additionalFiles) = $this->generateReport($idReport, $date, $language, self::OUTPUT_SAVE_ON_DISK, $report['period']);
     if (!file_exists($outputFilename)) {
         throw new Exception("The report file wasn't found in {$outputFilename}");
     }
     $filename = basename($outputFilename);
     $handle = fopen($outputFilename, "r");
     $contents = fread($handle, filesize($outputFilename));
     fclose($handle);
     /**
      * Triggered when sending scheduled reports.
      *
      * Plugins that provide new scheduled report transport mediums should use this event to
      * send the scheduled report.
      * 
      * @param string $reportType A string ID describing how the report is sent, eg,
      *                           `'sms'` or `'email'`.
      * @param array $report An array describing the scheduled report that is being
      *                      generated.
      * @param string $contents The contents of the scheduled report that was generated
      *                         and now should be sent.
      * @param string $filename The path to the file where the scheduled report has
      *                         been saved.
      * @param string $prettyDate A prettified date string for the data within the
      *                           scheduled report.
      * @param string $reportSubject A string describing what's in the scheduled
      *                              report.
      * @param string $reportTitle The scheduled report's given title (given by a Piwik user).
      * @param array $additionalFiles The list of additional files that should be
      *                               sent with this report.
      */
     Piwik::postEvent(self::SEND_REPORT_EVENT, array($report['type'], $report, $contents, $filename, $prettyDate, $reportSubject, $reportTitle, $additionalFiles));
     // Update flag in DB
     Db::get()->update(Common::prefixTable('report'), array('ts_last_sent' => Date::now()->getDatetime()), "idreport = " . $report['idreport']);
     // If running from piwik.php with debug, do not delete the PDF after sending the email
     if (!isset($GLOBALS['PIWIK_TRACKER_DEBUG']) || !$GLOBALS['PIWIK_TRACKER_DEBUG']) {
         @chmod($outputFilename, 0600);
     }
 }
Ejemplo n.º 24
0
 private function getSuggestedValuesForSegmentName($idSite, $segment, $maxSuggestionsToReturn)
 {
     $startDate = Date::now()->subDay(60)->toString();
     $requestLastVisits = "method=Live.getLastVisitsDetails\n        &idSite={$idSite}\n        &period=range\n        &date={$startDate},today\n        &format=original\n        &serialize=0\n        &flat=1";
     $segmentName = $segment['segment'];
     // Select non empty fields only
     // Note: this optimization has only a very minor impact
     $requestLastVisits .= "&segment={$segmentName}" . urlencode('!=');
     // By default Live fetches all actions for all visitors, but we'd rather do this only when required
     if ($this->doesSegmentNeedActionsData($segmentName)) {
         $requestLastVisits .= "&filter_limit=400";
     } else {
         $requestLastVisits .= "&doNotFetchActions=1";
         $requestLastVisits .= "&filter_limit=800";
     }
     $request = new Request($requestLastVisits);
     $table = $request->process();
     if (empty($table)) {
         throw new \Exception("There was no data to suggest for {$segmentName}");
     }
     if (isset($segment['suggestedValuesCallback']) && $this->doesSuggestedValuesCallbackNeedData($segment['suggestedValuesCallback'])) {
         $values = call_user_func($segment['suggestedValuesCallback'], $idSite, $maxSuggestionsToReturn, $table);
     } else {
         $values = $this->getSegmentValuesFromVisitorLog($segmentName, $table);
     }
     return $values;
 }
Ejemplo n.º 25
0
 /**
  * Detects whether a site had visits since midnight in the websites timezone
  *
  * @return bool
  */
 private function hadWebsiteTrafficSinceMidnightInTimezone($idSite)
 {
     $timezone = Site::getTimezoneFor($idSite);
     $nowInTimezone = Date::factory('now', $timezone);
     $midnightInTimezone = $nowInTimezone->setTime('00:00:00');
     $secondsSinceMidnight = $nowInTimezone->getTimestamp() - $midnightInTimezone->getTimestamp();
     $secondsSinceLastArchive = $this->getSecondsSinceLastArchive();
     if ($secondsSinceLastArchive < $secondsSinceMidnight) {
         $secondsSinceMidnight = $secondsSinceLastArchive;
     }
     $from = Date::now()->subSeconds($secondsSinceMidnight)->getDatetime();
     $to = Date::now()->addHour(1)->getDatetime();
     $dao = new RawLogDao();
     $hasVisits = $dao->hasSiteVisitsBetweenTimeframe($from, $to, $idSite);
     if ($hasVisits) {
         $this->logger->info("{$idSite} has visits between {$from} and {$to}");
     } else {
         $this->logger->info("{$idSite} has no visits between {$from} and {$to}");
     }
     return $hasVisits;
 }
Ejemplo n.º 26
0
 public function test_deleteTriggeredAlertsForSite()
 {
     $this->model->triggerAlert(1, 1, 99, 48, Date::now()->getDatetime());
     $this->model->triggerAlert(1, 2, 99, 48, Date::now()->getDatetime());
     $this->model->triggerAlert(1, 3, 99, 48, Date::now()->getDatetime());
     $this->model->triggerAlert(1, 2, 99, 48, Date::now()->getDatetime());
     $alerts = $this->model->getTriggeredAlerts(array(1, 2, 3), 'superUserLogin');
     $this->assertCount(4, $alerts);
     $this->model->deleteTriggeredAlertsForSite(2);
     // verify actually removed the correct ones
     $alerts = $this->model->getTriggeredAlerts(array(1, 2, 3), 'superUserLogin');
     $this->assertCount(2, $alerts);
     $this->assertEquals(1, $alerts[0]['idtriggered']);
     $this->assertEquals(3, $alerts[1]['idtriggered']);
 }
Ejemplo n.º 27
0
 /**
  * The Multisites reports displays the first calendar date as the earliest day available for all websites.
  * Also, today is the later "today" available across all timezones.
  * @param array $siteIds Array of IDs for each site being displayed.
  * @return Date[] of two Date instances. First is the min-date & the second
  *               is the max date.
  * @ignore
  */
 public static function getMinMaxDateAcrossWebsites($siteIds)
 {
     $siteIds = self::getIdSitesFromIdSitesString($siteIds);
     $now = Date::now();
     $minDate = null;
     $maxDate = $now->subDay(1)->getTimestamp();
     foreach ($siteIds as $idsite) {
         // look for 'now' in the website's timezone
         $timezone = Site::getTimezoneFor($idsite);
         $date = Date::adjustForTimezone($now->getTimestamp(), $timezone);
         if ($date > $maxDate) {
             $maxDate = $date;
         }
         // look for the absolute minimum date
         $creationDate = Site::getCreationDateFor($idsite);
         $date = Date::adjustForTimezone(strtotime($creationDate), $timezone);
         if (is_null($minDate) || $date < $minDate) {
             $minDate = $date;
         }
     }
     return array(Date::factory($minDate), Date::factory($maxDate));
 }
Ejemplo n.º 28
0
 /**
  * Detects whether a site had visits since midnight in the websites timezone
  *
  * @param $idSite
  * @return bool
  */
 private function hadWebsiteTrafficSinceMidnightInTimezone($idSite)
 {
     $timezone = Site::getTimezoneFor($idSite);
     $nowInTimezone = Date::factory('now', $timezone);
     $midnightInTimezone = $nowInTimezone->setTime('00:00:00');
     $secondsSinceMidnight = $nowInTimezone->getTimestamp() - $midnightInTimezone->getTimestamp();
     $secondsSinceLastArchive = $this->getSecondsSinceLastArchive();
     if ($secondsSinceLastArchive < $secondsSinceMidnight) {
         $secondsBackToLookForVisits = $secondsSinceLastArchive;
         $sinceInfo = "(since the last successful archiving)";
     } else {
         $secondsBackToLookForVisits = $secondsSinceMidnight;
         $sinceInfo = "(since midnight)";
     }
     $from = Date::now()->subSeconds($secondsBackToLookForVisits)->getDatetime();
     $to = Date::now()->addHour(1)->getDatetime();
     $dao = new RawLogDao();
     $hasVisits = $dao->hasSiteVisitsBetweenTimeframe($from, $to, $idSite);
     if ($hasVisits) {
         $this->logger->info("- tracking data found for website id {$idSite} since {$from} UTC {$sinceInfo}");
     } else {
         $this->logger->info("- no new tracking data for website id {$idSite} since {$from} UTC {$sinceInfo}");
     }
     return $hasVisits;
 }
Ejemplo n.º 29
0
 /**
  * @group Plugins
  */
 public function test_UpdateSegment()
 {
     $name = 'name"';
     $definition = 'searches>1,visitIp!=127.0.0.1';
     $nameSegment1 = 'hello';
     $idSegment1 = API::getInstance()->add($nameSegment1, 'searches==0', $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1);
     $idSegment2 = API::getInstance()->add($name, $definition, $idSite = 1, $autoArchive = 1, $enabledAllUsers = 1);
     $updatedSegment = array('idsegment' => $idSegment2, 'name' => 'NEW name', 'definition' => 'searches==0', 'enable_only_idsite' => '0', 'enable_all_users' => '0', 'auto_archive' => '0', 'ts_last_edit' => Date::now()->getDatetime(), 'ts_created' => Date::now()->getDatetime(), 'login' => Piwik::getCurrentUserLogin(), 'deleted' => '0');
     API::getInstance()->update($idSegment2, $updatedSegment['name'], $updatedSegment['definition'], $updatedSegment['enable_only_idsite'], $updatedSegment['auto_archive'], $updatedSegment['enable_all_users']);
     $newSegment = API::getInstance()->get($idSegment2);
     // avoid test failures for when ts_created/ts_last_edit are different by between 1/2 secs
     $this->removeSecondsFromSegmentInfo($updatedSegment);
     $this->removeSecondsFromSegmentInfo($newSegment);
     $this->assertEquals($newSegment, $updatedSegment);
     // Check the other segmenet was not updated
     $newSegment = API::getInstance()->get($idSegment1);
     $this->assertEquals($newSegment['name'], $nameSegment1);
 }
Ejemplo n.º 30
0
 /**
  * Given a segment, will return a list of the most used values for this particular segment.
  * @param $segmentName
  * @param $idSite
  * @throws \Exception
  * @return array
  */
 public function getSuggestedValuesForSegment($segmentName, $idSite)
 {
     if (empty(Config::getInstance()->General['enable_segment_suggested_values'])) {
         return array();
     }
     Piwik::checkUserHasViewAccess($idSite);
     $maxSuggestionsToReturn = 30;
     $segmentsMetadata = $this->getSegmentsMetadata($idSite, $_hideImplementationData = false);
     $segmentFound = false;
     foreach ($segmentsMetadata as $segmentMetadata) {
         if ($segmentMetadata['segment'] == $segmentName) {
             $segmentFound = $segmentMetadata;
             break;
         }
     }
     if (empty($segmentFound)) {
         throw new \Exception("Requested segment not found.");
     }
     // if segment has suggested values callback then return result from it instead
     if (isset($segmentFound['suggestedValuesCallback'])) {
         return call_user_func($segmentFound['suggestedValuesCallback'], $idSite, $maxSuggestionsToReturn);
     }
     // if period=range is disabled, do not proceed
     if (!Period\Factory::isPeriodEnabledForAPI('range')) {
         return array();
     }
     $startDate = Date::now()->subDay(60)->toString();
     $requestLastVisits = "method=Live.getLastVisitsDetails\n        &idSite={$idSite}\n        &period=range\n        &date={$startDate},today\n        &format=original\n        &serialize=0\n        &flat=1";
     // Select non empty fields only
     // Note: this optimization has only a very minor impact
     $requestLastVisits .= "&segment={$segmentName}" . urlencode('!=');
     // By default Live fetches all actions for all visitors, but we'd rather do this only when required
     if ($this->doesSegmentNeedActionsData($segmentName)) {
         $requestLastVisits .= "&filter_limit=400";
     } else {
         $requestLastVisits .= "&doNotFetchActions=1";
         $requestLastVisits .= "&filter_limit=800";
     }
     $request = new Request($requestLastVisits);
     $table = $request->process();
     if (empty($table)) {
         throw new \Exception("There was no data to suggest for {$segmentName}");
     }
     // Cleanup data to return the top suggested (non empty) labels for this segment
     $values = $table->getColumn($segmentName);
     // Select also flattened keys (custom variables "page" scope, page URLs for one visit, page titles for one visit)
     $valuesBis = $table->getColumnsStartingWith($segmentName . ColumnDelete::APPEND_TO_COLUMN_NAME_TO_KEEP);
     $values = array_merge($values, $valuesBis);
     $values = $this->getMostFrequentValues($values);
     $values = array_slice($values, 0, $maxSuggestionsToReturn);
     $values = array_map(array('Piwik\\Common', 'unsanitizeInputValue'), $values);
     return $values;
 }