protected function buildView() { // access control $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik_API_Request::reloadAuthUsingTokenAuth(); if (!Piwik::isUserHasViewAccess($idSite)) { throw new Exception(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idSite))); } // collect data $this->parametersToModify['action'] = $this->currentControllerAction; $this->parametersToModify = array_merge($this->variablesDefault, $this->parametersToModify); $this->graphData = $this->getGraphData(); // build view $view = new Piwik_View($this->dataTableTemplate); $view->width = $this->width; $view->height = $this->height; $view->chartDivId = $this->getUniqueIdViewDataTable() . "Chart"; $view->graphType = $this->graphType; $view->data = $this->graphData; $view->isDataAvailable = strpos($this->graphData, '"series":[]') === false; $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet(); $view->properties = $this->getViewProperties(); $view->reportDocumentation = $this->getReportDocumentation(); return $view; }
/** * send email to Piwik team and display nice thanks */ function sendFeedback() { $email = Piwik_Common::getRequestVar('email', '', 'string'); $body = Piwik_Common::getRequestVar('body', '', 'string'); $category = Piwik_Common::getRequestVar('category', '', 'string'); $nonce = Piwik_Common::getRequestVar('nonce', '', 'string'); $view = Piwik_View::factory('sent'); $view->feedbackEmailAddress = Zend_Registry::get('config')->General->feedback_email_address; try { $minimumBodyLength = 35; if (strlen($body) < $minimumBodyLength) { throw new Exception(Piwik_TranslateException('Feedback_ExceptionBodyLength', array($minimumBodyLength))); } if (!Piwik::isValidEmailString($email)) { throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidEmail')); } if (preg_match('/https?:/i', $body)) { throw new Exception(Piwik_TranslateException('Feedback_ExceptionNoUrls')); } if (!Piwik_Nonce::verifyNonce('Piwik_Feedback.sendFeedback', $nonce)) { throw new Exception(Piwik_TranslateException('General_ExceptionNonceMismatch')); } Piwik_Nonce::discardNonce('Piwik_Feedback.sendFeedback'); $mail = new Piwik_Mail(); $mail->setFrom(Piwik_Common::unsanitizeInputValue($email)); $mail->addTo($view->feedbackEmailAddress, 'Piwik Team'); $mail->setSubject('[ Feedback form - Piwik ] ' . $category); $mail->setBodyText(Piwik_Common::unsanitizeInputValue($body) . "\n" . 'Piwik ' . Piwik_Version::VERSION . "\n" . 'IP: ' . Piwik_Common::getIpString() . "\n" . 'URL: ' . Piwik_Url::getReferer() . "\n"); @$mail->send(); } catch (Exception $e) { $view->ErrorString = $e->getMessage(); $view->message = $body; } echo $view->render(); }
/** * Returns a Piwik_Date objects. * * @param string $strDate 'today' 'yesterday' or any YYYY-MM-DD or timestamp * @param string $timezone if specified, the dateString will be relative to this $timezone. * For example, today in UTC+12 will be a timestamp in the future for UTC. * This is different from using ->setTimezone() * @return Piwik_Date */ public static function factory($dateString, $timezone = null) { $invalidDateException = new Exception(Piwik_TranslateException('General_ExceptionInvalidDateFormat', array("YYYY-MM-DD, or 'today' or 'yesterday'", "strtotime", "http://php.net/strtotime"))); if ($dateString instanceof self) { $dateString = $dateString->toString(); } if ($dateString == 'now') { $date = self::now(); } elseif ($dateString == 'today') { $date = self::today(); } elseif ($dateString == 'yesterday') { $date = self::yesterday(); } elseif ($dateString == 'yesterdaySameTime') { $date = self::yesterdaySameTime(); } elseif (!is_int($dateString) && (strpos($dateString, ',') !== false || ($dateString = strtotime($dateString)) === false)) { throw $invalidDateException; } else { $date = new Piwik_Date($dateString); } $timestamp = $date->getTimestamp(); // can't be doing web analytics before the 1st website if ($timestamp < 681436800) { throw $invalidDateException; } if (empty($timezone)) { return $date; } $timestamp = self::adjustForTimezone($timestamp, $timezone); return Piwik_Date::factory($timestamp); }
protected function buildView() { $view = new Piwik_View($this->dataTableTemplate); $this->uniqueIdViewDataTable = $this->getUniqueIdViewDataTable(); $view->graphType = $this->graphType; $this->chartDivId = $this->uniqueIdViewDataTable . "Chart_swf"; $this->parametersToModify['action'] = $this->currentControllerAction; $this->parametersToModify = array_merge($this->variablesDefault, $this->parametersToModify); $url = Piwik_Url::getCurrentQueryStringWithParametersModified($this->parametersToModify); $this->includeData = !Zend_Registry::get('config')->Debug->disable_merged_requests; $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik_API_Request::reloadAuthUsingTokenAuth(); if (!Piwik::isUserHasViewAccess($idSite)) { throw new Exception(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idSite))); } if ($this->includeData) { $this->chartData = $this->getFlashData(); } else { $this->chartData = null; } $view->flashParameters = $this->getFlashParameters(); $view->urlGraphData = $url; $view->chartDivId = $this->chartDivId; $view->formEmbedId = "formEmbed" . $this->uniqueIdViewDataTable; $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet(); $view->properties = $this->getViewProperties(); return $view; }
/** * Check MySQL version */ public function checkServerVersion() { $databaseVersion = $this->getServerVersion(); $requiredVersion = Zend_Registry::get('config')->General->minimum_mysql_version; if (version_compare($databaseVersion, $requiredVersion) === -1) { throw new Exception(Piwik_TranslateException('Core_ExceptionDatabaseVersion', array('MySQL', $databaseVersion, $requiredVersion))); } }
/** * Check client version compatibility against database server */ public function checkClientVersion() { $serverVersion = $this->getServerVersion(); $clientVersion = $this->getClientVersion(); if (version_compare($serverVersion, '5') >= 0 && version_compare($clientVersion, '5') < 0) { throw new Exception(Piwik_TranslateException('General_ExceptionIncompatibleClientServerVersions', array('MySQL', $clientVersion, $serverVersion))); } }
/** * Check PostgreSQL version */ public function checkServerVersion() { $databaseVersion = $this->getServerVersion(); $requiredVersion = Piwik_Config::getInstance()->General['minimum_pgsql_version']; if (version_compare($databaseVersion, $requiredVersion) === -1) { throw new Exception(Piwik_TranslateException('General_ExceptionDatabaseVersion', array('PostgreSQL', $databaseVersion, $requiredVersion))); } }
/** * Load translations from file * * @param string $lang ISO 639-1 alpha-2 language code * @throws Exception * @return array $translations Array of translations ( key => translated string ) */ public static function loadTranslation($lang) { $path = self::getTranslationPath($lang); if (!is_readable($path)) { throw new Exception(Piwik_TranslateException('General_ExceptionLanguageFileNotFound', array($lang))); } require $path; return $translations; }
/** * Check client version compatibility against database server * * @throws Exception */ public function checkClientVersion() { $serverVersion = $this->getServerVersion(); $clientVersion = $this->getClientVersion(); // incompatible change to DECIMAL implementation in 5.0.3 if (version_compare($serverVersion, '5.0.3') >= 0 && version_compare($clientVersion, '5.0.3') < 0) { throw new Exception(Piwik_TranslateException('General_ExceptionIncompatibleClientServerVersions', array('MySQL', $clientVersion, $serverVersion))); } }
/** * Returns a Piwik_Date objects. * * @param string $strDate 'today' 'yesterday' or any YYYY-MM-DD or timestamp * @param string $timezone if specified, the dateString will be relative to this $timezone. * For example, today in UTC+12 will be a timestamp in the future for UTC. * This is different from using ->setTimezone() * @return Piwik_Date */ static public function factory($dateString, $timezone = null) { if($dateString instanceof self) { $dateString = $dateString->toString(); } if($dateString == 'now') { $date = self::now(); } elseif($dateString == 'today') { $date = self::today(); } elseif($dateString == 'yesterday') { $date = self::yesterday(); } elseif($dateString == 'yesterdaySameTime') { $date = self::yesterdaySameTime(); } elseif (!is_int($dateString) && ( // strtotime returns the timestamp for April 1st for a date like 2011-04-01,today // but we don't want this, as this is a date range and supposed to throw the exception strpos($dateString, ',') !== false || ($dateString = strtotime($dateString)) === false )) { throw new Exception(Piwik_TranslateException('General_ExceptionInvalidDateFormat', array("YYYY-MM-DD, or 'today' or 'yesterday'", "strtotime", "http://php.net/strtotime"))); } else { $date = new Piwik_Date($dateString); } if(empty($timezone)) { return $date; } // manually adjust for UTC timezones $utcOffset = self::extractUtcOffset($timezone); if($utcOffset !== false) { return $date->addHour($utcOffset); } date_default_timezone_set($timezone); $datetime = $date->getDatetime(); date_default_timezone_set('UTC'); $date = Piwik_Date::factory(strtotime($datetime)); return $date; }
static function update() { $obsoleteFile = PIWIK_DOCUMENT_ROOT . '/libs/open-flash-chart/php-ofc-library/ofc_upload_image.php'; if (file_exists($obsoleteFile)) { $rc = @unlink($obsoleteFile); if (!$rc) { throw new Exception(Piwik_TranslateException('General_ExceptionUndeletableFile', array($obsoleteFile))); } } }
/** * Return the StaticGraph according to the static graph type $graphType * * @throws exception If the static graph type is unknown * @param string $graphType * @return Piwik_ImageGraph_StaticGraph */ public static function factory($graphType) { if (isset(self::$availableStaticGraphTypes[$graphType])) { $className = self::$availableStaticGraphTypes[$graphType]; Piwik_Loader::loadClass($className); return new $className(); } else { throw new Exception(Piwik_TranslateException('General_ExceptionInvalidStaticGraphType', array($graphType, implode(', ', self::getAvailableStaticGraphTypes())))); } }
private function loadTranslation($language) { $path = PIWIK_INCLUDE_PATH . '/lang/' . $language . '.php'; if (!Piwik_Common::isValidFilename($language) || !is_readable($path)) { throw new Exception(Piwik_TranslateException('General_ExceptionLanguageFileNotFound', array($language))); } require $path; $this->mergeTranslationArray($translations); $this->setLocale(); $this->loadedLanguage = $language; }
/** * Return the SMSProvider associated to the provider name $providerName * * @throws exception If the provider is unknown * @param string $providerName * @return Piwik_MobileMessaging_SMSProvider */ public static function factory($providerName) { $name = ucfirst(strtolower($providerName)); $className = 'Piwik_MobileMessaging_SMSProvider_' . $name; try { Piwik_Loader::loadClass($className); return new $className(); } catch (Exception $e) { throw new Exception(Piwik_TranslateException('MobileMessaging_Exception_UnknownProvider', array($name, implode(', ', array_keys(self::$availableSMSProviders))))); } }
/** * Return the ReportRenderer associated to the renderer type $rendererType * * @throws exception If the renderer is unknown * @param string $rendererType * @return Piwik_ReportRenderer */ public static function factory($rendererType) { $name = ucfirst(strtolower($rendererType)); $className = 'Piwik_ReportRenderer_' . $name; try { Piwik_Loader::loadClass($className); return new $className(); } catch (Exception $e) { @header('Content-Type: text/html; charset=utf-8'); throw new Exception(Piwik_TranslateException('General_ExceptionInvalidReportRendererFormat', array($name, implode(', ', self::$availableReportRenderers)))); } }
/** * @see Piwik_ViewDataTable::main() */ public function main() { if ($this->mainAlreadyExecuted) { return; } $this->mainAlreadyExecuted = true; $this->loadDataTableFromAPI(); $this->isDataAvailable = $this->dataTable->getRowsCount() != 0; if (!$this->isDataAvailable) { throw new Exception(Piwik_TranslateException('General_NoDataForGraph')); } $values = $this->getValuesFromDataTable($this->dataTable); $graph = new Piwik_Visualization_Sparkline(); $graph->setValues($values); $graph->main(); $this->view = $graph; }
/** * @param string $strPeriod "day", "week", "month", "year" * @param Piwik_Date $date Piwik_Date object * @throws Exception * @return Piwik_Period */ public static function factory($strPeriod, Piwik_Date $date) { switch ($strPeriod) { case 'day': return new Piwik_Period_Day($date); break; case 'week': return new Piwik_Period_Week($date); break; case 'month': return new Piwik_Period_Month($date); break; case 'year': return new Piwik_Period_Year($date); break; default: throw new Exception(Piwik_TranslateException('General_ExceptionInvalidPeriod', array($strPeriod, self::$errorAvailablePeriods))); break; } }
/** * send email to Piwik team and display nice thanks */ function sendFeedback() { $body = Piwik_Common::getRequestVar('body', '', 'string'); $email = Piwik_Common::getRequestVar('email', '', 'string'); $view = Piwik_View::factory('sent'); try { $minimumBodyLength = 35; if(strlen($body) < $minimumBodyLength) { throw new Exception(sprintf("Message must be at least %s characters long.", $minimumBodyLength)); } if(!Piwik::isValidEmailString($email)) { throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidEmail')); } if(strpos($body, 'http://') !== false) { throw new Exception("The message cannot contain a URL, to avoid spams messages."); } $mail = new Piwik_Mail(); $mail->setFrom($email); $mail->addTo('*****@*****.**','Piwik Team'); $mail->setSubject('[ Feedback form - Piwik ]'); $mail->setBodyText($body); @$mail->send(); } catch(Exception $e) { $view->ErrorString = $e->getMessage(); $view->message = $body; } echo $view->render(); }
protected function buildView() { // access control $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); Piwik_API_Request::reloadAuthUsingTokenAuth(); if (!Piwik::isUserHasViewAccess($idSite)) { throw new Exception(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idSite))); } // collect data $this->parametersToModify['action'] = $this->currentControllerAction; $this->parametersToModify = array_merge($this->variablesDefault, $this->parametersToModify); $this->graphData = $this->getGraphData(); // build view $view = new Piwik_View($this->dataTableTemplate); $view->width = $this->width; $view->height = $this->height; $view->chartDivId = $this->getUniqueIdViewDataTable() . "Chart"; $view->graphType = $this->graphType; $view->data = $this->graphData; $view->isDataAvailable = strpos($this->graphData, '"series":[]') === false; $view->javascriptVariablesToSet = $this->getJavascriptVariablesToSet(); $view->properties = $this->getViewProperties(); $view->reportDocumentation = $this->getReportDocumentation(); // if it's likely that the report data for this data table has been purged, // set whether we should display a message to that effect. $view->showReportDataWasPurgedMessage = $this->hasReportBeenPurged(); $view->deleteReportsOlderThan = Piwik_GetOption('delete_reports_older_than'); return $view; }
private static function validateReportFormat($reportType, $reportFormat) { $reportFormats = array_keys(self::getReportFormats($reportType)); if (!in_array($reportFormat, $reportFormats)) { throw new Exception(Piwik_TranslateException('General_ExceptionInvalidReportRendererFormat', array($reportFormat, implode(', ', $reportFormats)))); } }
/** * Look at the URL or Page Title and sees if it matches any existing Goal definition * * @param int $idSite * @param Piwik_Tracker_Action $action * @throws Exception * @return int Number of goals matched */ function detectGoalsMatchingUrl($idSite, $action) { if (!Piwik_Common::isGoalPluginEnabled()) { return false; } $decodedActionUrl = $action->getActionUrl(); $actionType = $action->getActionType(); $goals = $this->getGoalDefinitions($idSite); foreach ($goals as $goal) { $attribute = $goal['match_attribute']; // if the attribute to match is not the type of the current action if ($actionType == Piwik_Tracker_Action::TYPE_ACTION_URL && $attribute != 'url' && $attribute != 'title' || $actionType == Piwik_Tracker_Action::TYPE_DOWNLOAD && $attribute != 'file' || $actionType == Piwik_Tracker_Action::TYPE_OUTLINK && $attribute != 'external_website' || $attribute == 'manually') { continue; } $url = $decodedActionUrl; // Matching on Page Title if ($attribute == 'title') { $url = $action->getActionName(); } $pattern_type = $goal['pattern_type']; switch ($pattern_type) { case 'regex': $pattern = $goal['pattern']; if (strpos($pattern, '/') !== false && strpos($pattern, '\\/') === false) { $pattern = str_replace('/', '\\/', $pattern); } $pattern = '/' . $pattern . '/'; if (!$goal['case_sensitive']) { $pattern .= 'i'; } $match = @preg_match($pattern, $url) == 1; break; case 'contains': if ($goal['case_sensitive']) { $matched = strpos($url, $goal['pattern']); } else { $matched = stripos($url, $goal['pattern']); } $match = $matched !== false; break; case 'exact': if ($goal['case_sensitive']) { $matched = strcmp($goal['pattern'], $url); } else { $matched = strcasecmp($goal['pattern'], $url); } $match = $matched == 0; break; default: throw new Exception(Piwik_TranslateException('General_ExceptionInvalidGoalPattern', array($pattern_type))); break; } if ($match) { $goal['url'] = $decodedActionUrl; $this->convertedGoals[] = $goal; } } // var_dump($this->convertedGoals);exit; return count($this->convertedGoals) > 0; }
/** * Generates a unique MD5 for the given login & password * * @param string $userLogin Login * @param string $md5Password MD5ied string of the password * @throws Exception * @return string */ public function getTokenAuth($userLogin, $md5Password) { if (strlen($md5Password) != 32) { throw new Exception(Piwik_TranslateException('UsersManager_ExceptionPasswordMD5HashExpected')); } return md5($userLogin . $md5Password); }
/** * Checks that the specified token matches the current logged in user token. * Note: this protection against CSRF should be limited to controller * actions that are either invoked via AJAX or redirect to a page * within the site. The token should never appear in the browser's * address bar. * * @throws Piwik_Access_NoAccessException if token doesn't match * @return void */ protected function checkTokenInUrl() { if (Piwik_Common::getRequestVar('token_auth', false) != Piwik::getCurrentUserTokenAuth()) { throw new Piwik_Access_NoAccessException(Piwik_TranslateException('General_ExceptionInvalidToken')); } }
private function checkAggregateReportsFormat($format) { $availableAggregateReportsFormats = array_keys(Piwik_PDFReports_API::getAggregateReportsFormats()); if (!in_array($format, $availableAggregateReportsFormats)) { throw new Exception(Piwik_TranslateException('General_ExceptionInvalidAggregateReportsFormat', array($format, implode(', ', $availableAggregateReportsFormats)))); } }
private function oneClick_Verify() { $someExpectedFiles = array('/config/global.ini.php', '/index.php', '/core/Piwik.php', '/piwik.php', '/plugins/API/API.php'); foreach ($someExpectedFiles as $file) { if (!is_file($this->pathRootExtractedPiwik . $file)) { throw new Exception(Piwik_TranslateException('CoreUpdater_ExceptionArchiveIncomplete', $file)); } } }
/** * This method checks that the user has VIEW or ADMIN access for the given list of websites. * If the user doesn't have VIEW or ADMIN access for at least one website of the list, we throw an exception. * * @param int|array|string $idSites List of ID sites to check (integer, array of integers, string comma separated list of integers) * @throws Piwik_Access_NoAccessException If for any of the websites the user doesn't have an VIEW or ADMIN access */ public function checkUserHasViewAccess($idSites) { if ($this->isSuperUser()) { return; } $idSites = $this->getIdSites($idSites); $idSitesAccessible = $this->getSitesIdWithAtLeastViewAccess(); foreach ($idSites as $idsite) { if (!in_array($idsite, $idSitesAccessible)) { throw new Piwik_Access_NoAccessException(Piwik_TranslateException('General_ExceptionPrivilegeAccessWebsite', array("'view'", $idsite))); } } }
/** * Returns true if the login is valid. * Warning: does not check if the login already exists! You must use UsersManager_API->userExists as well. * * @param string $login * @return bool or throws exception */ public static function checkValidLoginString($userLogin) { if (!self::isChecksEnabled() && !empty($userLogin)) { return; } $loginMinimumLength = 3; $loginMaximumLength = 100; $l = strlen($userLogin); if (!($l >= $loginMinimumLength && $l <= $loginMaximumLength && preg_match('/^[A-Za-z0-9_.@+-]*$/D', $userLogin) > 0)) { throw new Exception(Piwik_TranslateException('UsersManager_ExceptionInvalidLoginFormat', array($loginMinimumLength, $loginMaximumLength))); } }
/** * Read configuration from files into memory * * @throws Exception if local config file is not readable; exits for other errors */ public function init() { $this->initialized = true; // read defaults from global.ini.php if (!is_readable($this->pathGlobal)) { Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionConfigurationFileNotFound', array($this->pathGlobal))); } $this->configGlobal = _parse_ini_file($this->pathGlobal, true); if (empty($this->configGlobal)) { Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionUnreadableFileDisabledMethod', array($this->pathGlobal, "parse_ini_file()"))); } // read the local settings from config.ini.php if (!is_readable($this->pathLocal)) { throw new Exception(Piwik_TranslateException('General_ExceptionConfigurationFileNotFound', array($this->pathLocal))); } $this->configLocal = _parse_ini_file($this->pathLocal, true); if (empty($this->configLocal)) { Piwik_ExitWithMessage(Piwik_TranslateException('General_ExceptionUnreadableFileDisabledMethod', array($this->pathLocal, "parse_ini_file()"))); } }
private function checkPatternIsValid($patternType, $pattern) { if ($patternType == 'exact' && substr($pattern, 0, 4) != 'http') { throw new Exception(Piwik_TranslateException('Goals_ExceptionInvalidMatchingString', array("http:// or https://", "http://www.yourwebsite.com/newsletter/subscribed.html"))); } }
/** * Check that the array of URLs are valid URLs * * @exception if any of the urls is not valid * @param array */ private static function checkUrls($urls) { foreach ($urls as $url) { if (!self::isValidUrl($url)) { throw new Exception(sprintf(Piwik_TranslateException("SitesManager_ExceptionInvalidUrl"), $url)); } } }