Use this function to get request parameter values. **_NEVER use $_GET and $_POST directly._**
If the variable cannot be found, and a default value was not provided, an exception is raised.
_See {@link sanitizeInputValues()} to learn more about sanitization._
public static getRequestVar ( string $varName, string | null $varDefault = null, string | null $varType = null, array | null $requestArrayToUse = null ) : mixed | ||
$varName | string | Name of the request parameter to get. By default, we look in `$_GET[$varName]` and `$_POST[$varName]` for the value. |
$varDefault | string | null | The value to return if the request parameter cannot be found or has an empty value. |
$varType | string | null | Expected type of the request variable. This parameters value must be one of the following: `'array'`, `'int'`, `'integer'`, `'string'`, `'json'`. If `'json'`, the string value will be `json_decode`-d and then sanitized. |
$requestArrayToUse | array | null | The array to use instead of `$_GET` and `$_POST`. |
Résultat | mixed | The sanitized request parameter. |
protected function configureSegments() { $idSite = Common::getRequestVar('idSite', 0, 'int'); if (empty($idSite)) { return array(); } $configuration = StaticContainer::get('Piwik\\Plugins\\CustomDimensions\\Dao\\Configuration'); $dimensions = $configuration->getCustomDimensionsForSite($idSite); foreach ($dimensions as $dimension) { if (!$dimension['active']) { continue; } $segment = new Segment(); $segment->setSegment(CustomDimensionsRequestProcessor::buildCustomDimensionTrackingApiName($dimension)); $segment->setType(Segment::TYPE_DIMENSION); $segment->setName($dimension['name']); $columnName = LogTable::buildCustomDimensionColumnName($dimension); if ($dimension['scope'] === CustomDimensions::SCOPE_ACTION) { $segment->setSqlSegment('log_link_visit_action. ' . $columnName); $segment->setCategory('General_Actions'); $segment->setSuggestedValuesCallback(function ($idSite, $maxValuesToReturn) use($dimension) { $autoSuggest = new AutoSuggest(); return $autoSuggest->getMostUsedActionDimensionValues($dimension, $idSite, $maxValuesToReturn); }); } elseif ($dimension['scope'] === CustomDimensions::SCOPE_VISIT) { $segment->setSqlSegment('log_visit. ' . $columnName); $segment->setCategory('General_Visit'); } else { continue; } $this->addSegment($segment); } }
/** * @see ViewDataTable::main() * @return mixed */ public function render() { // If period=range, we force the sparkline to draw daily data points $period = Common::getRequestVar('period'); if ($period == 'range') { $_GET['period'] = 'day'; } $this->loadDataTableFromAPI(); // then revert the hack for potentially subsequent getRequestVar $_GET['period'] = $period; $values = $this->getValuesFromDataTable($this->dataTable); if (empty($values)) { $values = array_fill(0, 30, 0); } $graph = new \Piwik\Visualization\Sparkline(); $graph->setValues($values); $height = Common::getRequestVar('height', 0, 'int'); if (!empty($height)) { $graph->setHeight($height); } $width = Common::getRequestVar('width', 0, 'int'); if (!empty($width)) { $graph->setWidth($width); } $graph->main(); return $graph->render(); }
/** * Returns true if it is likely that the data for this report has been purged and if the * user should be told about that. * * In order for this function to return true, the following must also be true: * - The data table for this report must either be empty or not have been fetched. * - The period of this report is not a multiple period. * - The date of this report must be older than the delete_reports_older_than config option. * @param DataTableInterface $dataTable * @return bool */ public static function hasReportBeenPurged($dataTable) { $strPeriod = Common::getRequestVar('period', false); $strDate = Common::getRequestVar('date', false); if (false !== $strPeriod && false !== $strDate && (is_null($dataTable) || !empty($dataTable) && $dataTable->getRowsCount() == 0)) { // if range, only look at the first date if ($strPeriod == 'range') { $idSite = Common::getRequestVar('idSite', ''); if (intval($idSite) != 0) { $site = new Site($idSite); $timezone = $site->getTimezone(); } else { $timezone = 'UTC'; } $period = new Range('range', $strDate, $timezone); $reportDate = $period->getDateStart(); } elseif (Period::isMultiplePeriod($strDate, $strPeriod)) { // if a multiple period, this function is irrelevant return false; } else { // otherwise, use the date as given $reportDate = Date::factory($strDate); } $reportYear = $reportDate->toString('Y'); $reportMonth = $reportDate->toString('m'); if (static::shouldReportBePurged($reportYear, $reportMonth)) { return true; } } return false; }
/** * @throws \Exception */ public function addOptOutStyles() { /** @var \Piwik\Plugins\CoreAdminHome\OptOutManager $manager */ $manager = StaticContainer::get('Piwik\\Plugins\\CoreAdminHome\\OptOutManager'); // See Issue #33 $siteId = Common::getRequestVar('idsite', 0, 'integer'); // Is still available for BC if (!$siteId) { $siteId = Common::getRequestVar('idSite', 0, 'integer'); } // Try to find siteId in Session if (!$siteId) { return; } $site = API::getInstance()->getSiteDataId($siteId); if (!$site) { return; } $manager->addQueryParameter('idsite', $siteId); // Add CSS file if set if (!empty($site['custom_css_file'])) { $manager->addStylesheet($site['custom_css_file'], false); } // Add CSS Inline Styles if set if (!empty($site['custom_css'])) { $manager->addStylesheet($site['custom_css'], true); } }
public function index() { Piwik::checkUserHasSuperUserAccess(); $limit = Common::getRequestVar('limit', 100, 'int'); // Render the Twig template templates/index.twig and assign the view variable answerToLife to the view. return $this->renderTemplate('index', array('limit' => $limit)); }
/** * Configure visualization. */ public function beforeRender() { $this->config->datatable_js_type = 'VisitorLog'; $this->config->enable_sort = false; $this->config->show_search = false; $this->config->show_exclude_low_population = false; $this->config->show_offset_information = false; $this->config->show_all_views_icons = false; $this->config->show_table_all_columns = false; $this->config->show_export_as_rss_feed = false; $this->config->documentation = Piwik::translate('Live_VisitorLogDocumentation', array('<br />', '<br />')); $filterEcommerce = Common::getRequestVar('filterEcommerce', 0, 'int'); $this->config->custom_parameters = array('totalRows' => 10000000, 'filterEcommerce' => $filterEcommerce, 'pageUrlNotDefined' => Piwik::translate('General_NotDefined', Piwik::translate('Actions_ColumnPageURL')), 'smallWidth' => 1 == Common::getRequestVar('small', 0, 'int')); $this->config->footer_icons = array(array('class' => 'tableAllColumnsSwitch', 'buttons' => array(array('id' => static::ID, 'title' => Piwik::translate('Live_LinkVisitorLog'), 'icon' => 'plugins/Zeitgeist/images/table.png')))); // determine if each row has ecommerce activity or not if ($filterEcommerce) { $this->dataTable->filter('ColumnCallbackAddMetadata', array('actionDetails', 'hasEcommerce', function ($actionDetails) use($filterEcommerce) { foreach ($actionDetails as $action) { $isEcommerceOrder = $action['type'] == 'ecommerceOrder' && $filterEcommerce == \Piwik\Plugins\Goals\Controller::ECOMMERCE_LOG_SHOW_ORDERS; $isAbandonedCart = $action['type'] == 'ecommerceAbandonedCart' && $filterEcommerce == \Piwik\Plugins\Goals\Controller::ECOMMERCE_LOG_SHOW_ABANDONED_CARTS; if ($isAbandonedCart || $isEcommerceOrder) { return true; } } return false; })); } }
public function dispatch() { $module = Common::getRequestVar('module', '', 'string'); $action = Common::getRequestVar('action', '', 'string'); if ($module == 'CoreUpdater' || $module == 'Proxy' || $module == 'Installation' || $module == 'LanguagesManager' && $action == 'saveLanguage') { return; } $updater = new PiwikCoreUpdater(); $updates = $updater->getComponentsWithNewVersion(array('core' => Version::VERSION)); if (!empty($updates)) { Filesystem::deleteAllCacheOnUpdate(); } if ($updater->getComponentUpdates() !== null) { if (FrontController::shouldRethrowException()) { throw new Exception("Piwik and/or some plugins have been upgraded to a new version. \n" . "--> Please run the update process first. See documentation: http://piwik.org/docs/update/ \n"); } elseif ($module === 'API') { $outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $_GET + $_POST)); $response = new ResponseBuilder($outputFormat); $e = new Exception('Database Upgrade Required. Your Piwik database is out-of-date, and must be upgraded before you can continue.'); echo $response->getResponseException($e); Common::sendResponseCode(503); exit; } else { Piwik::redirectToModule('CoreUpdater'); } } }
/** * Computes the output for the given data table * * @param DataTable $table * @return string * @throws Exception */ protected function renderTable($table) { if (!$table instanceof DataTable\Map || $table->getKeyName() != 'date') { throw new Exception("RSS feeds can be generated for one specific website &idSite=X." . "\nPlease specify only one idSite or consider using &format=XML instead."); } $idSite = Common::getRequestVar('idSite', 1, 'int'); $period = Common::getRequestVar('period'); $piwikUrl = SettingsPiwik::getPiwikUrl() . "?module=CoreHome&action=index&idSite=" . $idSite . "&period=" . $period; $out = ""; $moreRecentFirst = array_reverse($table->getDataTables(), true); foreach ($moreRecentFirst as $date => $subtable) { /** @var DataTable $subtable */ $timestamp = $subtable->getMetadata(Archive\DataTableFactory::TABLE_METADATA_PERIOD_INDEX)->getDateStart()->getTimestamp(); $site = $subtable->getMetadata(Archive\DataTableFactory::TABLE_METADATA_SITE_INDEX); $pudDate = date('r', $timestamp); $dateInSiteTimezone = Date::factory($timestamp); if ($site) { $dateInSiteTimezone = $dateInSiteTimezone->setTimezone($site->getTimezone()); } $dateInSiteTimezone = $dateInSiteTimezone->toString('Y-m-d'); $thisPiwikUrl = Common::sanitizeInputValue($piwikUrl . "&date={$dateInSiteTimezone}"); $siteName = $site ? $site->getName() : ''; $title = $siteName . " on " . $date; $out .= "\t<item>\n\t\t<pubDate>{$pudDate}</pubDate>\n\t\t<guid>{$thisPiwikUrl}</guid>\n\t\t<link>{$thisPiwikUrl}</link>\n\t\t<title>{$title}</title>\n\t\t<author>http://piwik.org</author>\n\t\t<description>"; $out .= Common::sanitizeInputValue($this->renderDataTable($subtable)); $out .= "</description>\n\t</item>\n"; } $header = $this->getRssHeader(); $footer = $this->getRssFooter(); return $header . $out . $footer; }
/** * Generates a graphic report based on the given parameters * @param string $type * @param string $apiMethod * @param string $controllerMethod * @param array $selectable * @param array $to_display * @return View */ private function getReportGraph($type, $apiMethod, $controllerMethod, $selectable = array(), $to_display = array()) { $view = ViewDataTableFactory::build($type, $apiMethod, $controllerMethod, $forceDefault = true); $view->config->show_goals = false; if (empty($selectable)) { if (Common::getRequestVar('period', false) == 'day') { $selectable = array('nb_visits', 'nb_uniq_visitors', 'nb_actions'); } else { $selectable = array('nb_visits', 'nb_actions'); } } if (empty($to_display)) { $to_display = Common::getRequestVar('columns', false); if (false !== $to_display) { $to_display = Piwik::getArrayFromApiParameter($columns); } } if (false !== $to_display) { $to_display = !is_array($to_display) ? array($to_display) : $to_display; } else { $to_display = $selectable; } $view->config->selectable_columns = $selectable; $view->config->columns_to_display = $to_display; $view->config->show_footer_icons = false; return $this->renderView($view); }
private function getCustomDimensionsInScope($scope, Request $request) { $dimensions = self::getCachedCustomDimensions($request); $params = $request->getParams(); $values = array(); foreach ($dimensions as $dimension) { if ($dimension['scope'] !== $scope) { continue; } $field = self::buildCustomDimensionTrackingApiName($dimension); $dbField = Dao\LogTable::buildCustomDimensionColumnName($dimension); $value = Common::getRequestVar($field, '', 'string', $params); if ($value !== '') { $values[$dbField] = $value; continue; } $extractions = $dimension['extractions']; if (is_array($extractions)) { foreach ($extractions as $extraction) { if (!array_key_exists('dimension', $extraction) || !array_key_exists('pattern', $extraction) || empty($extraction['pattern'])) { continue; } $extraction = new Extraction($extraction['dimension'], $extraction['pattern']); $extraction->setCaseSensitive($dimension['case_sensitive']); $value = $extraction->extract($request); if (!isset($value) || '' === $value) { continue; } $values[$dbField] = $value; break; } } } return $values; }
private function setShowGoalsColumnsProperties() { // set view properties based on goal requested $idSite = Common::getRequestVar('idSite', null, 'int'); $idGoal = Common::getRequestVar('idGoal', AddColumnsProcessedMetricsGoal::GOALS_OVERVIEW, 'string'); $goalsToProcess = null; if (Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER == $idGoal) { $this->setPropertiesForEcommerceView(); $goalsToProcess = array($idGoal); } else { if (AddColumnsProcessedMetricsGoal::GOALS_FULL_TABLE == $idGoal) { $this->setPropertiesForGoals($idSite, 'all'); $goalsToProcess = $this->getAllGoalIds($idSite); } else { if (AddColumnsProcessedMetricsGoal::GOALS_OVERVIEW == $idGoal) { $this->setPropertiesForGoalsOverview($idSite); $goalsToProcess = $this->getAllGoalIds($idSite); } else { $this->setPropertiesForGoals($idSite, array($idGoal)); $goalsToProcess = array($idGoal); } } } // add goals columns $this->config->filters[] = array('AddColumnsProcessedMetricsGoal', array($enable = true, $idGoal, $goalsToProcess), $priority = true); }
/** * @see ViewDataTable::main() * @return mixed */ public function render() { $view = new View('@CoreVisualizations/_dataTableViz_sparklines.twig'); $columnsList = array(); if ($this->config->hasSparklineMetrics()) { foreach ($this->config->getSparklineMetrics() as $cols) { $columns = $cols['columns']; if (!is_array($columns)) { $columns = array($columns); } $columnsList = array_merge($columns, $columnsList); } } $view->allMetricsDocumentation = Metrics::getDefaultMetricsDocumentation(); $this->requestConfig->request_parameters_to_modify['columns'] = $columnsList; $this->requestConfig->request_parameters_to_modify['format_metrics'] = '1'; if (!empty($this->requestConfig->apiMethodToRequestDataTable)) { $this->fetchConfiguredSparklines(); } $view->sparklines = $this->config->getSortedSparklines(); $view->isWidget = Common::getRequestVar('widget', 0, 'int'); $view->titleAttributes = $this->config->title_attributes; $view->footerMessage = $this->config->show_footer_message; $view->areSparklinesLinkable = $this->config->areSparklinesLinkable(); $view->title = ''; if ($this->config->show_title) { $view->title = $this->config->title; } return $view->render(); }
public function configureView(ViewDataTable $view) { $idSubtable = Common::getRequestVar('idSubtable', false); $labelColumnTitle = $this->name; switch ($idSubtable) { case Common::REFERRER_TYPE_SEARCH_ENGINE: $labelColumnTitle = Piwik::translate('Referrers_ColumnSearchEngine'); break; case Common::REFERRER_TYPE_WEBSITE: $labelColumnTitle = Piwik::translate('Referrers_ColumnWebsite'); break; case Common::REFERRER_TYPE_CAMPAIGN: $labelColumnTitle = Piwik::translate('Referrers_ColumnCampaign'); break; default: break; } $view->config->show_search = false; $view->config->show_offset_information = false; $view->config->show_pagination_control = false; $view->config->show_limit_control = false; $view->config->show_exclude_low_population = false; $view->config->addTranslation('label', $labelColumnTitle); $view->requestConfig->filter_limit = 10; if ($view->isViewDataTableId(HtmlTable::ID)) { $view->config->disable_subtable_when_show_goals = true; } }
/** * Constructor. */ public function __construct($idSite = false) { parent::__construct(); $this->jsClass = "SegmentSelectorControl"; $this->cssIdentifier = "segmentEditorPanel"; $this->cssClass = "piwikTopControl"; $this->idSite = $idSite ?: Common::getRequestVar('idSite', false, 'int'); $this->selectedSegment = Common::getRequestVar('segment', false, 'string'); $segments = APIMetadata::getInstance()->getSegmentsMetadata($this->idSite); $segmentsByCategory = $customVariablesSegments = array(); foreach ($segments as $segment) { if ($segment['category'] == Piwik::translate('General_Visit') && ($segment['type'] == 'metric' && $segment['segment'] != 'visitIp')) { $metricsLabel = Piwik::translate('General_Metrics'); $metricsLabel[0] = strtolower($metricsLabel[0]); $segment['category'] .= ' (' . $metricsLabel . ')'; } $segmentsByCategory[$segment['category']][] = $segment; } uksort($segmentsByCategory, array($this, 'sortSegmentCategories')); $this->createRealTimeSegmentsIsEnabled = Config::getInstance()->General['enable_create_realtime_segments']; $this->segmentsByCategory = $segmentsByCategory; $this->nameOfCurrentSegment = ''; $this->isSegmentNotAppliedBecauseBrowserArchivingIsDisabled = 0; $this->availableSegments = API::getInstance()->getAll($this->idSite); foreach ($this->availableSegments as &$savedSegment) { $savedSegment['name'] = Common::sanitizeInputValue($savedSegment['name']); if (!empty($this->selectedSegment) && $this->selectedSegment == $savedSegment['definition']) { $this->nameOfCurrentSegment = $savedSegment['name']; $this->isSegmentNotAppliedBecauseBrowserArchivingIsDisabled = $this->wouldApplySegment($savedSegment) ? 0 : 1; } } $this->authorizedToCreateSegments = SegmentEditorAPI::getInstance()->isUserCanAddNewSegment($this->idSite); $this->isUserAnonymous = Piwik::isUserIsAnonymous(); $this->segmentTranslations = $this->getTranslations(); }
/** * The constructor * Initialize some local variables from the request * @param int $idSite * @param Date $date ($this->date from controller) * @param null|string $graphType * @throws Exception */ public function __construct($idSite, $date, $graphType = 'graphEvolution') { $this->apiMethod = Common::getRequestVar('apiMethod', '', 'string'); if (empty($this->apiMethod)) { throw new Exception("Parameter apiMethod not set."); } $this->label = DataTablePostProcessor::getLabelFromRequest($_GET); if (!is_array($this->label)) { throw new Exception("Expected label to be an array, got instead: " . $this->label); } $this->label = $this->label[0]; if ($this->label === '') { throw new Exception("Parameter label not set."); } $this->period = Common::getRequestVar('period', '', 'string'); PeriodFactory::checkPeriodIsEnabled($this->period); $this->idSite = $idSite; $this->graphType = $graphType; if ($this->period != 'range') { // handle day, week, month and year: display last X periods $end = $date->toString(); list($this->date, $lastN) = EvolutionViz::getDateRangeAndLastN($this->period, $end); } $this->segment = \Piwik\API\Request::getRawSegmentFromRequest(); $this->loadEvolutionReport(); }
/** * Checks if the provided CURRENT password is correct and calls the parent * class function if so. Otherwise provides error message. * * @see the parent class function for parameters and return value */ public function recordUserSettings() { try { $passwordCurrent = Common::getRequestvar('passwordCurrent', false); $passwordCurrent = Crypto::decrypt($passwordCurrent); // Note: Compare loosely, so both, "" (password input empty; forms send strings) // and "password input not sent" are covered - see // https://secure.php.net/manual/en/types.comparisons.php if ($passwordCurrent != "") { $userName = Piwik::getCurrentUserLogin(); // gets username as string or "anonymous" // see Piwik\Plugins\Login\Auth for used password hash function // (in setPassword()) and access to hashed password (in getTokenAuthSecret()) if ($userName != 'anonymous') { $model = new Model(); $user = $model->getUser($userName); if (UsersManagerEncrypted::getPasswordHash($passwordCurrent) === $user['password']) { $toReturn = parent::recordUserSettings(); } else { throw new Exception(Piwik::translate('UsersManagerEncrypted_CurrentPasswordIncorrect')); } } else { throw new Exception(Piwik::translate('UsersManagerEncrypted_UserNotAuthenticated')); } } else { throw new Exception(Piwik::translate('UsersManagerEncrypted_CurrentPasswordNotProvided')); } } catch (Exception $e) { $response = new ResponseBuilder(Common::getRequestVar('format')); $toReturn = $response->getResponseException($e); } return $toReturn; }
public function getSelector() { $view = new View('@SegmentEditor/getSelector'); $idSite = Common::getRequestVar('idSite'); $this->setGeneralVariablesView($view); $segments = APIMetadata::getInstance()->getSegmentsMetadata($idSite); $segmentsByCategory = $customVariablesSegments = array(); foreach ($segments as $segment) { if ($segment['category'] == Piwik::translate('General_Visit') && ($segment['type'] == 'metric' && $segment['segment'] != 'visitIp')) { $metricsLabel = Piwik::translate('General_Metrics'); $metricsLabel[0] = strtolower($metricsLabel[0]); $segment['category'] .= ' (' . $metricsLabel . ')'; } $segmentsByCategory[$segment['category']][] = $segment; } uksort($segmentsByCategory, array($this, 'sortSegmentCategories')); $view->segmentsByCategory = $segmentsByCategory; $savedSegments = API::getInstance()->getAll($idSite); foreach ($savedSegments as &$savedSegment) { $savedSegment['name'] = Common::sanitizeInputValue($savedSegment['name']); } $view->savedSegmentsJson = Common::json_encode($savedSegments); $view->authorizedToCreateSegments = !Piwik::isUserIsAnonymous(); $view->segmentTranslations = Common::json_encode($this->getTranslations()); $out = $view->render(); return $out; }
public function addSubcategories(&$subcategories) { $idSite = Common::getRequestVar('idSite', 0, 'int'); if (!$idSite) { // fallback for eg API.getReportMetadata which uses idSites $idSite = Common::getRequestVar('idSites', 0, 'int'); if (!$idSite) { return; } } $dimensions = $this->configuration->getCustomDimensionsForSite($idSite); $order = 70; foreach ($dimensions as $dimension) { if (!$dimension['active']) { continue; } $category = new Subcategory(); $category->setName($dimension['name']); if ($dimension['scope'] === CustomDimensions::SCOPE_ACTION) { $category->setCategoryId('General_Actions'); } elseif ($dimension['scope'] === CustomDimensions::SCOPE_VISIT) { $category->setCategoryId('General_Visitors'); } $category->setId('customdimension' . $dimension['idcustomdimension']); $category->setOrder($order++); $subcategories[] = $category; } }
/** * Here you can configure how your report should be displayed. For instance whether your report supports a search * etc. You can also change the default request config. For instance change how many rows are displayed by default. * * @param ViewDataTable $view */ public function configureView(ViewDataTable $view) { if ($view->isViewDataTableId(Sparklines::ID)) { /** @var Sparklines $view */ $view->config->addSparklineMetric(array('server1')); $view->config->addSparklineMetric(array('server2')); $view->config->addTranslations(array('server1' => 'Evolution of temperature for server piwik.org')); $view->config->addTranslations(array('server2' => 'Evolution of temperature for server dev.piwik.org')); } elseif ($view->isViewDataTableId(Evolution::ID)) { /** @var Evolution $view */ $selectableColumns = array('server1', 'server2'); $columns = Common::getRequestVar('columns', false); if (!empty($columns)) { $columns = Piwik::getArrayFromApiParameter($columns); } $columns = array_merge($columns ? $columns : array(), $selectableColumns); $view->config->columns_to_display = $columns; $view->config->addTranslations(array_combine($columns, $columns)); $view->config->selectable_columns = $selectableColumns; $view->requestConfig->filter_sort_column = 'label'; $view->requestConfig->filter_sort_order = 'asc'; $view->config->documentation = 'My documentation'; $view->config->show_goals = false; } }
public function configureReportingMenu(MenuReporting $menu) { $idSite = Common::getRequestVar('idSite', null, 'int'); $goals = API::getInstance()->getGoals($idSite); $mainGoalMenu = $this->getGoalCategoryName($idSite); $site = new Site($idSite); if (count($goals) == 0) { $menu->add($mainGoalMenu, '', array('module' => 'Goals', 'action' => $site->isEcommerceEnabled() ? 'ecommerceReport' : 'addNewGoal', 'idGoal' => $site->isEcommerceEnabled() ? Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER : null), true, 25); if ($site->isEcommerceEnabled()) { $menu->add($mainGoalMenu, 'Goals_Ecommerce', array('module' => 'Goals', 'action' => 'ecommerceReport', 'idGoal' => Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER), true, 1); } $menu->add($mainGoalMenu, 'Goals_AddNewGoal', array('module' => 'Goals', 'action' => 'addNewGoal')); } else { $menu->add($mainGoalMenu, '', array('module' => 'Goals', 'action' => $site->isEcommerceEnabled() ? 'ecommerceReport' : 'index', 'idGoal' => $site->isEcommerceEnabled() ? Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER : null), true, 25); if ($site->isEcommerceEnabled()) { $menu->add($mainGoalMenu, 'Goals_Ecommerce', array('module' => 'Goals', 'action' => 'ecommerceReport', 'idGoal' => Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER), true, 1); } $menu->add($mainGoalMenu, 'Goals_GoalsOverview', array('module' => 'Goals', 'action' => 'index'), true, 2); $group = new Group(); foreach ($goals as $goal) { $subMenuName = str_replace('%', '%%', Translate::clean($goal['name'])); $params = array('module' => 'Goals', 'action' => 'goalReport', 'idGoal' => $goal['idgoal']); $tooltip = sprintf('%s (id = %d)', $subMenuName, $goal['idgoal']); if (count($goals) <= 3) { $menu->add($mainGoalMenu, $subMenuName, $params, true, 50, $tooltip); } else { $group->add($subMenuName, $params, $tooltip); } } if (count($goals) > 3) { $menu->addGroup($mainGoalMenu, 'Goals_ChooseGoal', $group, $orderId = 50, $tooltip = false); } } }
/** * Check for a newer version * * @param bool $force Force check * @param int $interval Interval used for update checks */ public static function check($force = false, $interval = null) { if (!self::isAutoUpdateEnabled()) { return; } if ($interval === null) { $interval = self::CHECK_INTERVAL; } $lastTimeChecked = Option::get(self::LAST_TIME_CHECKED); if ($force || $lastTimeChecked === false || time() - $interval > $lastTimeChecked) { // set the time checked first, so that parallel Piwik requests don't all trigger the http requests Option::set(self::LAST_TIME_CHECKED, time(), $autoLoad = 1); $parameters = array('piwik_version' => Version::VERSION, 'php_version' => PHP_VERSION, 'url' => Url::getCurrentUrlWithoutQueryString(), 'trigger' => Common::getRequestVar('module', '', 'string'), 'timezone' => API::getInstance()->getDefaultTimezone()); $url = Config::getInstance()->General['api_service_url'] . '/1.0/getLatestVersion/' . '?' . http_build_query($parameters, '', '&'); $timeout = self::SOCKET_TIMEOUT; if (@Config::getInstance()->Debug['allow_upgrades_to_beta']) { $url = 'http://builds.piwik.org/LATEST_BETA'; } try { $latestVersion = Http::sendHttpRequest($url, $timeout); if (!preg_match('~^[0-9][0-9a-zA-Z_.-]*$~D', $latestVersion)) { $latestVersion = ''; } } catch (Exception $e) { // e.g., disable_functions = fsockopen; allow_url_open = Off $latestVersion = ''; } Option::set(self::LATEST_VERSION, $latestVersion); } }
/** * The constructor * Initialize some local variables from the request * @param int $idSite * @param Date $date ($this->date from controller) * @param null|string $graphType * @throws Exception */ public function __construct($idSite, $date, $graphType = null) { $this->apiMethod = Common::getRequestVar('apiMethod', '', 'string'); if (empty($this->apiMethod)) { throw new Exception("Parameter apiMethod not set."); } $this->label = ResponseBuilder::getLabelFromRequest($_GET); $this->label = $this->label[0]; if ($this->label === '') { throw new Exception("Parameter label not set."); } $this->period = Common::getRequestVar('period', '', 'string'); if (empty($this->period)) { throw new Exception("Parameter period not set."); } $this->idSite = $idSite; $this->graphType = $graphType; if ($this->period != 'range') { // handle day, week, month and year: display last X periods $end = $date->toString(); list($this->date, $lastN) = EvolutionViz::getDateRangeAndLastN($this->period, $end); } $this->segment = \Piwik\API\Request::getRawSegmentFromRequest(); $this->loadEvolutionReport(); }
/** * Set login name and authentication token for API request. * Listens to API.Request.authenticate hook. */ public function ApiRequestAuthenticate($tokenAuth) { /** @var \Piwik\Auth $auth */ $auth = StaticContainer::get('Piwik\\Auth'); $auth->setLogin($login = null); $auth->setTokenAuth($tokenAuth); $auth->setAuthCode(Common::getRequestVar('auth_code', '', 'string')); }
public function isEnabled() { $idSite = Common::getRequestVar('idSite', false, 'int'); if (empty($idSite)) { return false; } return $this->isEcommerceEnabled($idSite); }
/** * Renders and echo's the in-app donate form w/ slider. */ public function getDonateForm() { $view = new View('@CoreHome/getDonateForm'); if (Common::getRequestVar('widget', false) && Piwik::hasUserSuperUserAccess()) { $view->footerMessage = $this->translator->translate('CoreHome_OnlyForSuperUserAccess'); } return $view->render(); }
/** * Displays the admin UI page showing all tracking tags * @return string */ function displayJavascriptCode() { $idSite = Common::getRequestVar('idSite'); Piwik::checkUserHasViewAccess($idSite); $jsTag = Piwik::getJavascriptCode($idSite, SettingsPiwik::getPiwikUrl()); $site = new Site($idSite); return $this->renderTemplate('displayJavascriptCode', array('idSite' => $idSite, 'displaySiteName' => $site->getName(), 'jsTag' => $jsTag)); }
private function getJsonpCallback() { $jsonCallback = Common::getRequestVar('callback', false, null, $this->request); if ($jsonCallback === false) { $jsonCallback = Common::getRequestVar('jsoncallback', false, null, $this->request); } return $jsonCallback; }
public function getSort() { $sort = Common::getRequestVar('sort', self::DEFAULT_SORT, 'string'); if (!$this->isValidSortMethod($sort)) { $sort = self::DEFAULT_SORT; } return $sort; }
public function render() { $footerMessage = null; if (Common::getRequestVar('widget', false) && Piwik::hasUserSuperUserAccess()) { $footerMessage = $this->translator->translate('CoreHome_OnlyForSuperUserAccess'); } return $this->renderTemplate('getDonateForm', array('footerMessage' => $footerMessage)); }
/** * send email to Piwik team and display nice thanks * @throws Exception */ function sendFeedback() { $email = Common::getRequestVar('email', '', 'string'); $body = Common::getRequestVar('body', '', 'string'); $category = Common::getRequestVar('category', '', 'string'); $nonce = Common::getRequestVar('nonce', '', 'string'); $view = new View('@Feedback/sendFeedback'); $view->feedbackEmailAddress = Config::getInstance()->General['feedback_email_address']; try { $minimumBodyLength = 40; if (strlen($body) < $minimumBodyLength || strpos($email, 'probe@') !== false || strpos($body, '<probe') !== false) { throw new Exception(Piwik::translate('Feedback_ExceptionBodyLength', array($minimumBodyLength))); } if (!Piwik::isValidEmailString($email)) { throw new Exception(Piwik::translate('UsersManager_ExceptionInvalidEmail')); } if (preg_match('/https?:/i', $body)) { throw new Exception(Piwik::translate('Feedback_ExceptionNoUrls')); } if (!Nonce::verifyNonce('Feedback.sendFeedback', $nonce)) { throw new Exception(Piwik::translate('General_ExceptionNonceMismatch')); } Nonce::discardNonce('Feedback.sendFeedback'); $mail = new Mail(); $mail->setFrom(Common::unsanitizeInputValue($email)); $mail->addTo($view->feedbackEmailAddress, 'Piwik Team'); $mail->setSubject('[ Feedback form - Piwik ] ' . $category); $mail->setBodyText(Common::unsanitizeInputValue($body) . "\n" . 'Piwik ' . Version::VERSION . "\n" . 'IP: ' . IP::getIpFromHeader() . "\n" . 'URL: ' . Url::getReferrer() . "\n"); @$mail->send(); } catch (Exception $e) { $view->errorString = $e->getMessage(); $view->message = $body; } return $view->render(); }