/** * Computes the output for the given data table * * @param Piwik_DataTable $table * @return string * @throws Exception */ protected function renderTable($table) { if (!$table instanceof Piwik_DataTable_Array || $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 = Piwik_Common::getRequestVar('idSite', 1, 'int'); $period = Piwik_Common::getRequestVar('period'); $piwikUrl = Piwik_Url::getCurrentUrlWithoutFileName() . "?module=CoreHome&action=index&idSite=" . $idSite . "&period=" . $period; $out = ""; $moreRecentFirst = array_reverse($table->getArray(), true); foreach ($moreRecentFirst as $date => $subtable) { $timestamp = $table->metadata[$date]['timestamp']; $site = $table->metadata[$date]['site']; $pudDate = date('r', $timestamp); $dateInSiteTimezone = Piwik_Date::factory($timestamp)->setTimezone($site->getTimezone())->toString('Y-m-d'); $thisPiwikUrl = Piwik_Common::sanitizeInputValue($piwikUrl . "&date={$dateInSiteTimezone}"); $siteName = $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 .= Piwik_Common::sanitizeInputValue($this->renderDataTable($subtable)); $out .= "</description>\n\t</item>\n"; } $header = $this->getRssHeader(); $footer = $this->getRssFooter(); return $header . $out . $footer; }
public function __construct() { parent::__construct(); $this->idSite = Piwik_Common::getRequestVar('idSite', null, 'int'); $this->goals = Piwik_Goals_API::getInstance()->getGoals($this->idSite); foreach ($this->goals as &$goal) { $goal['name'] = Piwik_Common::sanitizeInputValue($goal['name']); if (isset($goal['pattern'])) { $goal['pattern'] = Piwik_Common::sanitizeInputValue($goal['pattern']); } } }
/** * Renders the current view. * * @return string Generated template */ public function render() { try { $this->currentModule = Piwik::getModule(); $this->currentAction = Piwik::getAction(); $userLogin = Piwik::getCurrentUserLogin(); $this->userLogin = $userLogin; // workaround for #1331 $count = method_exists('Piwik', 'getWebsitesCountToDisplay') ? Piwik::getWebsitesCountToDisplay() : 1; $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess($count); usort($sites, create_function('$site1, $site2', 'return strcasecmp($site1["name"], $site2["name"]);')); $this->sites = $sites; $this->url = Piwik_Common::sanitizeInputValue(Piwik_Url::getCurrentUrl()); $this->token_auth = Piwik::getCurrentUserTokenAuth(); $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $this->userIsSuperUser = Piwik::isUserIsSuperUser(); $this->latest_version_available = Piwik_UpdateCheck::isNewestVersionAvailable(); $this->disableLink = Piwik_Common::getRequestVar('disableLink', 0, 'int'); $this->isWidget = Piwik_Common::getRequestVar('widget', 0, 'int'); if (Zend_Registry::get('config')->General->autocomplete_min_sites <= count($sites)) { $this->show_autocompleter = true; } else { $this->show_autocompleter = false; } // workaround for #1331 $this->loginModule = method_exists('Piwik', 'getLoginPluginName') ? Piwik::getLoginPluginName() : 'Login'; $user = Piwik_UsersManager_API::getInstance()->getUser($userLogin); $this->userAlias = $user['alias']; } catch (Exception $e) { // can fail, for example at installation (no plugin loaded yet) } $this->totalTimeGeneration = Zend_Registry::get('timer')->getTime(); try { $this->totalNumberOfQueries = Piwik::getQueryCount(); } catch (Exception $e) { $this->totalNumberOfQueries = 0; } // workaround for #1331 if (method_exists('Piwik', 'overrideCacheControlHeaders')) { Piwik::overrideCacheControlHeaders('no-store'); } @header('Content-Type: ' . $this->contentType); if ($this->xFrameOptions) { @header('X-Frame-Options: ' . $this->xFrameOptions); } return $this->smarty->fetch($this->template); }
/** * Rewrites the given URL so that it looks like a URL that can be loaded directly. * Useful for users who don't handle javascript / ajax, they can still use piwik with these rewritten URLs. * * @return string */ function smarty_modifier_urlRewriteBasicView($parameters) { // replace module=X by moduleToLoad=X // replace action=Y by actionToLoad=Y $parameters['moduleToLoad'] = $parameters['module']; unset($parameters['module']); if (isset($parameters['action'])) { $parameters['actionToLoad'] = $parameters['action']; unset($parameters['action']); } else { $parameters['actionToLoad'] = null; } $url = Piwik_Url::getCurrentQueryStringWithParametersModified($parameters); // add module=CoreHome&action=showInContext $url = $url . '&module=CoreHome&action=showInContext'; return Piwik_Common::sanitizeInputValue($url); }
protected function renderTable($table) { if(!($table instanceof Piwik_DataTable_Array) || $table->getKeyName() != 'date') { throw new Exception("RSS Feed only used on Piwik_DataTable_Array with keyName = 'date'"); } $idSite = Piwik_Common::getRequestVar('idSite', 1, 'int'); $period = Piwik_Common::getRequestVar('period'); $piwikUrl = Piwik_Url::getCurrentUrlWithoutFileName() . "?module=CoreHome&action=index&idSite=" . $idSite . "&period=" . $period; $out = ""; $moreRecentFirst = array_reverse($table->getArray(), true); foreach($moreRecentFirst as $date => $subtable ) { $timestamp = $table->metadata[$date]['timestamp']; $site = $table->metadata[$date]['site']; $pudDate = date('r', $timestamp); $dateInSiteTimezone = Piwik_Date::factory($timestamp)->setTimezone($site->getTimezone())->toString('Y-m-d'); $thisPiwikUrl = Piwik_Common::sanitizeInputValue($piwikUrl . "&date=$dateInSiteTimezone"); $siteName = $site->getName(); $title = $siteName . " on ". $date; $out .= "\t<item> <pubDate>$pudDate</pubDate> <guid>$thisPiwikUrl</guid> <link>$thisPiwikUrl</link> <title>$title</title> <author>http://piwik.org</author> <description>"; $out .= Piwik_Common::sanitizeInputValue( $this->renderDataTable($subtable) ); $out .= "</description>\n\t</item>\n"; } $header = $this->getRssHeader(); $footer = $this->getRssFooter(); return $header . $out . $footer; }
/** * Renders the current view. * * @return string Generated template */ public function render() { try { $this->currentModule = Piwik::getModule(); $this->currentAction = Piwik::getAction(); $userLogin = Piwik::getCurrentUserLogin(); $this->userLogin = $userLogin; $count = Piwik::getWebsitesCountToDisplay(); $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess($count); usort($sites, create_function('$site1, $site2', 'return strcasecmp($site1["name"], $site2["name"]);')); $this->sites = $sites; $this->url = Piwik_Common::sanitizeInputValue(Piwik_Url::getCurrentUrl()); $this->token_auth = Piwik::getCurrentUserTokenAuth(); $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $this->userIsSuperUser = Piwik::isUserIsSuperUser(); $this->latest_version_available = Piwik_UpdateCheck::isNewestVersionAvailable(); $this->disableLink = Piwik_Common::getRequestVar('disableLink', 0, 'int'); $this->isWidget = Piwik_Common::getRequestVar('widget', 0, 'int'); if (Piwik_Config::getInstance()->General['autocomplete_min_sites'] <= count($sites)) { $this->show_autocompleter = true; } else { $this->show_autocompleter = false; } $this->loginModule = Piwik::getLoginPluginName(); $user = Piwik_UsersManager_API::getInstance()->getUser($userLogin); $this->userAlias = $user['alias']; } catch (Exception $e) { // can fail, for example at installation (no plugin loaded yet) } $this->totalTimeGeneration = Zend_Registry::get('timer')->getTime(); try { $this->totalNumberOfQueries = Piwik::getQueryCount(); } catch (Exception $e) { $this->totalNumberOfQueries = 0; } Piwik::overrideCacheControlHeaders('no-store'); @header('Content-Type: ' . $this->contentType); // always sending this header, sometimes empty, to ensure that Dashboard embed loads (which could call this header() multiple times, the last one will prevail) @header('X-Frame-Options: ' . (string) $this->xFrameOptions); return $this->smarty->fetch($this->template); }
/** * Smarty {url} function plugin. * Generates a piwik URL with the specified parameters modified. * * Examples: * <pre> * {url module="API"} will rewrite the URL modifying the module GET parameter * {url module="API" method="getKeywords"} will rewrite the URL modifying the parameters module=API method=getKeywords * </pre> * * @see Piwik_Url::getCurrentQueryStringWithParametersModified() * * @param array $params $name=>$value pairs of the parameters to modify in the generated URL * @param Smarty &smarty Smarty object * @return string Something like index.php?module=X&action=Y */ function smarty_function_url($params, &$smarty) { return Piwik_Common::sanitizeInputValue('index.php' . Piwik_Url::getCurrentQueryStringWithParametersModified($params)); }
/** * If current URL is "http://example.org/dir1/dir2/index.php?param1=value1¶m2=value2" * will return "example.org" * * @param string $default Default value to return if host unknown * @return string */ public static function getCurrentHost($default = 'unknown') { $hostHeaders = @Piwik_Config::getInstance()->General['proxy_host_headers']; if (!is_array($hostHeaders)) { $hostHeaders = array(); } $host = self::getHost(); $default = Piwik_Common::sanitizeInputValue($host ? $host : $default); return Piwik_IP::getNonProxyIpFromHeader($default, $hostHeaders); }
/** * Returns an URL query string in an array format * * @param string $urlQuery * @return array array( param1=> value1, param2=>value2) */ public static function getArrayFromQueryString($urlQuery) { if (strlen($urlQuery) == 0) { return array(); } if ($urlQuery[0] == '?') { $urlQuery = substr($urlQuery, 1); } $separator = '&'; $urlQuery = $separator . $urlQuery; // $urlQuery = str_replace(array('%20'), ' ', $urlQuery); $refererQuery = trim($urlQuery); $values = explode($separator, $refererQuery); $nameToValue = array(); foreach ($values as $value) { $pos = strpos($value, '='); if ($pos !== false) { $name = substr($value, 0, $pos); $value = substr($value, $pos + 1); if ($value === false) { $value = ''; } } else { $name = $value; $value = false; } if (!empty($name)) { $name = Piwik_Common::sanitizeInputValue($name); } if (!empty($value)) { $value = Piwik_Common::sanitizeInputValue($value); } // if array without indexes $count = 0; $tmp = preg_replace('/(\\[|%5b)(]|%5d)$/i', '', $name, -1, $count); if (!empty($tmp) && $count) { $name = $tmp; if (isset($nameToValue[$name]) == false || is_array($nameToValue[$name]) == false) { $nameToValue[$name] = array(); } array_push($nameToValue[$name], $value); } else { if (!empty($name)) { $nameToValue[$name] = $value; } } } return $nameToValue; }
/** * Clean the parameter URLs: * - if the parameter is a string make it an array * - remove the trailing slashes if found * * @param string|array urls * @return array the array of cleaned URLs */ private function cleanParameterUrls($urls) { if (!is_array($urls)) { $urls = array($urls); } $urls = array_filter($urls); $urls = array_map('urldecode', $urls); foreach ($urls as &$url) { $url = $this->removeTrailingSlash($url); if (strpos($url, 'http') !== 0) { $url = 'http://' . $url; } $url = Piwik_Common::sanitizeInputValue($url); } $urls = array_unique($urls); return $urls; }
/** * The previous step is valid if it is either * - any step before (OK to go back) * - the current step (case when validating a form) * If step is invalid, then exit. * * @param string $currentStep Current step */ protected function checkPreviousStepIsValid( $currentStep ) { $error = false; if(empty($this->session->currentStepDone)) { $error = true; } else if($currentStep == 'finished' && $this->session->currentStepDone == 'finished') { // ok to refresh this page or use language selector } else { if(file_exists(Piwik_Config::getDefaultUserConfigPath())) { $error = true; } $steps = array_keys($this->steps); // the currentStep $currentStepId = array_search($currentStep, $steps); // the step before $previousStepId = array_search($this->session->currentStepDone, $steps); // not OK if currentStepId > previous+1 if( $currentStepId > $previousStepId + 1 ) { $error = true; } } if($error) { Piwik_Login_Controller::clearSession(); $message = Piwik_Translate('Installation_ErrorInvalidState', array( '<br /><b>', '</b>', '<a href=\''.Piwik_Common::sanitizeInputValue(Piwik_Url::getCurrentUrlWithoutFileName()).'\'>', '</a>') ); Piwik::exitWithErrorMessage( $message ); } }
/** * If current URL is "http://example.org/dir1/dir2/index.php?param1=value1¶m2=value2" * will return "example.org" * * @param string $default Default value to return if host unknown * @return string */ public static function getCurrentHost($default = 'unknown') { $hostHeaders = @Piwik_Config::getInstance()->General['proxy_host_headers']; if (!is_array($hostHeaders)) { $hostHeaders = array(); } $default = Piwik_Common::sanitizeInputValue($default); if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { $default = Piwik_Common::sanitizeInputValue($_SERVER['HTTP_HOST']); } return Piwik_IP::getNonProxyIpFromHeader($default, $hostHeaders); }
/** * Rewrites the given URL and modify the given parameters. * @see Piwik_Url::getCurrentQueryStringWithParametersModified() * * @param $parameters * @return string */ function smarty_modifier_urlRewriteWithParameters($parameters) { $parameters['updated'] = null; $url = Piwik_Url::getCurrentQueryStringWithParametersModified($parameters); return Piwik_Common::sanitizeInputValue($url); }
/** * Returns the last IP address in a comma separated list, subject to an optional exclusion list. * * @param string $csv Comma separated list of elements * @param array $excludedIps Optional list of excluded IP addresses (or IP address ranges) * @return string Last (non-excluded) IP address in the list */ static public function getLastIpFromList($csv, $excludedIps = null) { $p = strrpos($csv, ','); if($p !== false) { $elements = explode(',', $csv); for($i = count($elements); $i--; ) { $element = trim(Piwik_Common::sanitizeInputValue($elements[$i])); if(empty($excludedIps) || (!in_array($element, $excludedIps) && !self::isIpInRange(self::P2N(self::sanitizeIp($element)), $excludedIps))) { return $element; } } } return trim(Piwik_Common::sanitizeInputValue($csv)); }
protected function extractEvolutionReport($report) { $this->dataTable = $report['reportData']; $this->rowLabel = Piwik_Common::sanitizeInputValue($report['label']); $this->rowIcon = !empty($report['logo']) ? $report['logo'] : false; $this->availableMetrics = $report['metadata']['metrics']; $this->dimension = $report['metadata']['dimension']; }
/** * Checks if the current host is valid and sets variables on the given view, including: * * isValidHost - true if host is valid, false if otherwise * invalidHostMessage - message to display if host is invalid (only set if host is invalid) * invalidHost - the invalid hostname (only set if host is invalid) * mailLinkStart - the open tag of a link to email the super user of this problem (only set * if host is invalid) */ public static function setHostValidationVariablesView($view) { // check if host is valid $view->isValidHost = Piwik_Url::isValidHost(); if (!$view->isValidHost) { // invalid host, so display warning to user $validHost = Piwik_Config::getInstance()->General['trusted_hosts'][0]; $invalidHost = Piwik_Common::sanitizeInputValue($_SERVER['HTTP_HOST']); $emailSubject = rawurlencode(Piwik_Translate('CoreHome_InjectedHostEmailSubject', $invalidHost)); $emailBody = rawurlencode(Piwik_Translate('CoreHome_InjectedHostEmailBody')); $superUserEmail = Piwik::getSuperUserEmail(); $mailToUrl = "mailto:{$superUserEmail}?subject={$emailSubject}&body={$emailBody}"; $mailLinkStart = "<a href=\"{$mailToUrl}\">"; $invalidUrl = Piwik_Url::getCurrentUrlWithoutQueryString($checkIfTrusted = false); $validUrl = Piwik_Url::getCurrentScheme() . '://' . $validHost . Piwik_Url::getCurrentScriptName(); $validLink = "<a href=\"{$validUrl}\">{$validUrl}</a>"; $changeTrustedHostsUrl = "index.php" . Piwik_Url::getCurrentQueryStringWithParametersModified(array('module' => 'CoreAdminHome', 'action' => 'generalSettings')) . "#trustedHostsSection"; $warningStart = Piwik_Translate('CoreHome_InjectedHostWarningIntro', array('<strong>' . $invalidUrl . '</strong>', '<strong>' . $validUrl . '</strong>')) . ' <br/>'; if (Piwik::isUserIsSuperUser()) { $view->invalidHostMessage = $warningStart . ' ' . Piwik_Translate('CoreHome_InjectedHostSuperUserWarning', array("<a href=\"{$changeTrustedHostsUrl}\">", $invalidHost, '</a>', "<br/><a href=\"{$validUrl}\">", $validHost, '</a>')); } else { $view->invalidHostMessage = $warningStart . ' ' . Piwik_Translate('CoreHome_InjectedHostNonSuperUserWarning', array("<br/><a href=\"{$validUrl}\">", '</a>', $mailLinkStart, '</a>')); } $view->invalidHostMessageHowToFix = '<b>How do I fix this problem and how do I login again?</b><br/> The Piwik Super User can manually edit the file piwik/config/config.ini.php and add the following lines: <pre>[General]' . "\n" . 'trusted_hosts[] = "' . $validHost . '"</pre><br/>After making the change, you will be able to login again.<br/><br/> You may also <i>disable this security feature (not recommended)</i>. To do so edit config/config.ini.php and add: <pre>[General]' . "\n" . 'enable_trusted_host_check=0</pre>'; $view->invalidHost = $invalidHost; // for UserSettings warning $view->invalidHostMailLinkStart = $mailLinkStart; } }
/** * If current URL is "http://example.org/dir1/dir2/index.php?param1=value1¶m2=value2" * will return "example.org" * * @param string $default Default value to return if host unknown * @return string */ public static function getCurrentHost($default = 'unknown') { static $hostHeaders = null; if (is_null($hostHeaders)) { $config = Zend_Registry::get('config'); if ($config !== false && isset($config->General->proxy_host_headers)) { $hostHeaders = $config->General->proxy_host_headers->toArray(); } if (!is_array($hostHeaders)) { $hostHeaders = array(); } } $default = Piwik_Common::sanitizeInputValue($default); if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { $default = Piwik_Common::sanitizeInputValue($_SERVER['HTTP_HOST']); } // temporary workaround for #1331 if (!method_exists('Piwik_Common', 'getProxyFromHeader')) { return $default; } return Piwik_Common::getProxyFromHeader($default, $hostHeaders); }
/** * Returns the Javascript code to be inserted on every page to track * * @param int $idSite * @param string $piwikUrl http://path/to/piwik/directory/ * @return string */ public static function getJavascriptCode($idSite, $piwikUrl) { $jsCode = file_get_contents(PIWIK_INCLUDE_PATH . "/core/Tracker/javascriptCode.tpl"); $jsCode = nl2br(htmlentities($jsCode)); $piwikUrl = preg_match('~^(http|https)://(.*)$~D', $piwikUrl, $matches); $piwikUrl = @$matches[2]; $jsCode = str_replace('{$idSite}', $idSite, $jsCode); $jsCode = str_replace('{$piwikUrl}', Piwik_Common::sanitizeInputValue($piwikUrl), $jsCode); $jsCode = str_replace('{$hrefTitle}', Piwik::getRandomTitle(), $jsCode); return $jsCode; }
private function initPiwikHost() { // If archive.php run as a web cron, we use the current hostname if (!Piwik_Common::isPhpCliMode()) { // example.org/piwik/misc/cron/ $piwikUrl = Piwik_Common::sanitizeInputValue(Piwik_Url::getCurrentUrlWithoutFileName()); // example.org/piwik/ $piwikUrl = $piwikUrl . "../../"; } else { $piwikUrl = $this->isParameterSet("url", true); if (!$piwikUrl || !Piwik_Common::isLookLikeUrl($piwikUrl)) { $this->logFatalError("archive.php expects the argument --url to be set to your Piwik URL, for example: --url=http://example.org/piwik/ ", $backtrace = false); } // ensure there is a trailing slash if ($piwikUrl[strlen($piwikUrl) - 1] != '/') { $piwikUrl .= '/'; } } if (Piwik_Config::getInstance()->General['force_ssl'] == 1) { $piwikUrl = str_replace('http://', 'https://', $piwikUrl); } $this->piwikUrl = $piwikUrl . "index.php"; }
/** * Use variations of the label to make it easier to specify the desired label * * Note: The HTML Encoded version must be tried first, since in Piwik_API_ResponseBuilder the $label is unsanitized * via Piwik_Common::unsanitizeInputValue. * * @param string $label * @return array */ private function getLabelVariations($label) { $variations = array(); $label = trim($label); $sanitizedLabel = Piwik_Common::sanitizeInputValue($label); $variations[] = $sanitizedLabel; if ($this->apiModule == 'Actions' && $this->apiMethod == 'getPageTitles') { // special case: the Actions.getPageTitles report prefixes some labels with a blank. // the blank might be passed by the user but is removed in Piwik_API_Request::getRequestArrayFromString. $variations[] = ' ' . $sanitizedLabel; $variations[] = ' ' . $label; } $variations[] = $label; return $variations; }
/** * Returns, for a given parameter, the value of this parameter in the REQUEST array. * If not set, returns the default value for this parameter @see getDefault() * * @param string $nameVar * @return string|mixed Value of this parameter */ protected function getDefaultOrCurrent($nameVar) { if (isset($_GET[$nameVar])) { return Piwik_Common::sanitizeInputValue($_GET[$nameVar]); } $default = $this->getDefault($nameVar); return $default; }
function addWidgets() { $idSite = Piwik_Common::getRequestVar('idSite', null, 'int'); // Ecommerce widgets $site = new Piwik_Site($idSite); if ($site->isEcommerceEnabled()) { Piwik_AddWidget('Goals_Ecommerce', 'Goals_EcommerceOverview', 'Goals', 'widgetGoalReport', array('idGoal' => Piwik_Archive::LABEL_ECOMMERCE_ORDER)); Piwik_AddWidget('Goals_Ecommerce', 'Goals_EcommerceLog', 'Goals', 'getEcommerceLog'); foreach ($this->ecommerceReports as $widget) { Piwik_AddWidget('Goals_Ecommerce', $widget[0], $widget[1], $widget[2]); } } // Goals widgets Piwik_AddWidget('Goals_Goals', 'Goals_GoalsOverview', 'Goals', 'widgetGoalsOverview'); $goals = Piwik_Goals_API::getInstance()->getGoals($idSite); if (count($goals) > 0) { foreach ($goals as $goal) { Piwik_AddWidget('Goals_Goals', Piwik_Common::sanitizeInputValue($goal['name']), 'Goals', 'widgetGoalReport', array('idGoal' => $goal['idgoal'])); } } }
function addWidgets() { Piwik_AddWidget('Goals_Goals', 'Goals_GoalsOverview', 'Goals', 'widgetGoalsOverview'); $goals = Piwik_Tracker_GoalManager::getGoalDefinitions(Piwik_Common::getRequestVar('idSite', null, 'int')); if (count($goals) > 0) { foreach ($goals as $goal) { Piwik_AddWidget('Goals_Goals', Piwik_Common::sanitizeInputValue($goal['name']), 'Goals', 'widgetGoalReport', array('idGoal' => $goal['idgoal'])); } } }
/** * Dispatches the request to the right plugin and executes the requested action on the plugin controller. * * @throws Exception|Piwik_FrontController_PluginDeactivatedException in case the plugin doesn't exist, the action doesn't exist, there is not enough permission, etc. * * @param string $module * @param string $action * @param array $parameters * @return mixed The returned value of the calls, often nothing as the module print but don't return data * @see fetchDispatch() */ function dispatch($module = null, $action = null, $parameters = null) { if (self::$enableDispatch === false) { return; } if (is_null($module)) { $defaultModule = 'CoreHome'; $module = Piwik_Common::getRequestVar('module', $defaultModule, 'string'); } if (is_null($action)) { $action = Piwik_Common::getRequestVar('action', false); } if (!Piwik_Session::isFileBasedSessions() && ($module !== 'API' || $action && $action !== 'index')) { Piwik_Session::start(); } if (is_null($parameters)) { $parameters = array(); } if (!ctype_alnum($module)) { throw new Exception("Invalid module name '{$module}'"); } if (!Piwik_PluginsManager::getInstance()->isPluginActivated($module)) { throw new Piwik_FrontController_PluginDeactivatedException($module); } $controllerClassName = 'Piwik_' . $module . '_Controller'; // FrontController's autoloader if (!class_exists($controllerClassName, false)) { $moduleController = PIWIK_INCLUDE_PATH . '/plugins/' . $module . '/Controller.php'; if (!is_readable($moduleController)) { throw new Exception("Module controller {$moduleController} not found!"); } require_once $moduleController; // prefixed by PIWIK_INCLUDE_PATH } $controller = new $controllerClassName(); if ($action === false) { $action = $controller->getDefaultAction(); } // Piwik::log("Dispatching $module / $action, parameters: ".var_export($parameters, $return = true)); if (!is_callable(array($controller, $action))) { throw new Exception("Action {$action} not found in the controller {$controllerClassName}."); } // Generic hook that plugins can use to modify any input to the function, // or even change the plugin being called $params = array($controller, $action, $parameters); Piwik_PostEvent('FrontController.dispatch', $params); try { return call_user_func_array(array($params[0], $params[1]), $params[2]); } catch (Piwik_Access_NoAccessException $e) { Piwik_PostEvent('FrontController.NoAccessException', $e); } catch (Exception $e) { $debugTrace = $e->getTraceAsString(); $message = Piwik_Common::sanitizeInputValue($e->getMessage()); Piwik_ExitWithMessage($message, Piwik::shouldLoggerLog() ? $debugTrace : '', true); } }