/** * returns singleton * * @return Piwik_FrontController */ public static function getInstance() { if (self::$instance == null) { self::$instance = new self(); } return self::$instance; }
function goalReport() { $idGoal = Piwik_Common::getRequestVar('idGoal', null, 'int'); if (!isset($this->goals[$idGoal])) { Piwik::redirectToModule('Goals', 'index', array('idGoal' => null)); } $goalDefinition = $this->goals[$idGoal]; $view = Piwik_View::factory('single_goal'); $view->currency = Piwik::getCurrency(); $goal = $this->getMetricsForGoal($idGoal); foreach ($goal as $name => $value) { $view->{$name} = $value; } $view->name = $goalDefinition['name']; $view->title = $goalDefinition['name'] . ' - Conversions'; $view->graphEvolution = $this->getEvolutionGraph(true, array(Piwik_Goals::getRecordName('nb_conversions', $idGoal)), $idGoal); $view->nameGraphEvolution = 'GoalsgetEvolutionGraph'; $view->topSegments = $this->getTopSegments($idGoal); // conversion rate for new and returning visitors $request = new Piwik_API_Request("method=Goals.getConversionRateReturningVisitors&format=original"); $view->conversion_rate_returning = round($request->process(), self::CONVERSION_RATE_PRECISION); $request = new Piwik_API_Request("method=Goals.getConversionRateNewVisitors&format=original"); $view->conversion_rate_new = round($request->process(), self::CONVERSION_RATE_PRECISION); $verticalSlider = array(); // string label // array parameters to ajax call on click (module, action) // specific order // (intermediate labels) // automatically load the first from the list, highlights it $view->tableByConversion = Piwik_FrontController::getInstance()->fetchDispatch('Referers', 'getKeywords', array(false, 'tableGoals')); echo $view->render(); }
/** * returns singleton * * @return Piwik_FrontController */ public static function getInstance() { if (self::$instance == null) { $c = __CLASS__; self::$instance = new $c(); } return self::$instance; }
public function showInContext() { $controllerName = Piwik_Common::getRequestVar('moduleToLoad'); $actionName = Piwik_Common::getRequestVar('actionToLoad', 'index'); $view = $this->getDefaultIndexView(); $view->content = Piwik_FrontController::getInstance()->fetchDispatch($controllerName, $actionName); echo $view->render(); }
function iframe() { $controllerName = Piwik_Common::getRequestVar('moduleToWidgetize'); $actionName = Piwik_Common::getRequestVar('actionToWidgetize'); $parameters = array($fetch = true); $outputDataTable = Piwik_FrontController::getInstance()->fetchDispatch($controllerName, $actionName, $parameters); $view = Piwik_View::factory('iframe'); $view->content = $outputDataTable; echo $view->render(); }
function iframe() { Piwik_API_Request::reloadAuthUsingTokenAuth(); $this->init(); $controllerName = Piwik_Common::getRequestVar('moduleToWidgetize'); $actionName = Piwik_Common::getRequestVar('actionToWidgetize'); $parameters = array ( $fetch = true ); $outputDataTable = Piwik_FrontController::getInstance()->fetchDispatch( $controllerName, $actionName, $parameters); $view = Piwik_View::factory('iframe'); $this->setGeneralVariablesView($view); $view->content = $outputDataTable; echo $view->render(); }
function toC_Piwik() { define('PIWIK_USER_PATH', DIR_FS_CATALOG . 'ext/piwik'); define('PIWIK_INCLUDE_PATH', DIR_FS_CATALOG . 'ext/piwik'); define('PIWIK_ENABLE_DISPATCH', false); define('PIWIK_ENABLE_ERROR_HANDLER', false); define('PIWIK_ENABLE_SESSION_START', 0); define('PIWIK_DISPLAY_ERRORS', 0); require_once PIWIK_INCLUDE_PATH . "/libs/PEAR.php"; require_once PIWIK_INCLUDE_PATH . "/index.php"; require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php"; Piwik_FrontController::getInstance()->init(); }
static function getWidgetsForFlexForm(&$PA, &$fobj) { $PA['items'] = array(); tx_piwikintegration_install::getInstaller()->getConfigObject()->initPiwikDatabase(); $controller = Piwik_FrontController::getInstance()->init(); $_GET['idSite'] = 1; $widgets = Piwik_GetWidgetsList(); foreach ($widgets as $pluginCat => $plugin) { foreach ($plugin as $widget) { $PA['items'][] = array($pluginCat . ' : ' . $widget['name'], base64_encode(json_encode($widget['parameters'])), 'i/catalog.gif'); } } }
function dispatch() { $module = Piwik_Common::getRequestVar('module', '', 'string'); $updater = new Piwik_Updater(); $updater->addComponentToCheck('core', Piwik_Version::VERSION); $updates = $updater->getComponentsWithNewVersion(); if (!empty($updates)) { Piwik::deleteAllCacheOnUpdate(); } if (self::getComponentUpdates($updater) !== null && $module != 'CoreUpdater' && $module != 'Proxy') { if (Piwik_FrontController::shouldRethrowException()) { throw new Exception("Piwik and/or some plugins have been upgraded to a new version. Please run the update process first. See documentation: http://piwik.org/docs/update/"); } else { Piwik::redirectToModule('CoreUpdater'); } } }
/** * Exception handler used to display nicely exceptions in Piwik * * @param Exception $exception */ function Piwik_ExceptionHandler(Exception $exception) { try { Zend_Registry::get('logger_exception')->logEvent($exception); } catch (Exception $e) { if (Piwik_FrontController::shouldRethrowException()) { throw $exception; } // case when the exception is raised before the logger being ready // we handle the exception a la mano, but using the Logger formatting properties $event = array(); $event['errno'] = $exception->getCode(); $event['message'] = $exception->getMessage(); $event['errfile'] = $exception->getFile(); $event['errline'] = $exception->getLine(); $event['backtrace'] = $exception->getTraceAsString(); $formatter = new Piwik_Log_Exception_Formatter_ScreenFormatter(); $message = $formatter->format($event); $message .= "<br /><br />And this exception raised another exception \"" . $e->getMessage() . "\""; Piwik::exitWithErrorMessage($message); } }
/** * Call PHP API * * @param $strParams API call params */ function callPHP($strParams) { if (PIWIK_INCLUDE_PATH === FALSE) { return serialize(array('result' => 'error', 'message' => __('Could not resolve', 'wp-piwik') . ' "' . htmlentities(self::$aryGlobalSettings['piwik_path']) . '": ' . __('realpath() returns false', 'wp-piwik') . '.')); } if (file_exists(PIWIK_INCLUDE_PATH . "/index.php")) { require_once PIWIK_INCLUDE_PATH . "/index.php"; } if (file_exists(PIWIK_INCLUDE_PATH . "/core/API/Request.php")) { require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php"; } if (class_exists('Piwik_FrontController')) { Piwik_FrontController::getInstance()->init(); } // Add Piwik URL to params $strParams .= '&piwikUrl=' . urlencode(self::$aryGlobalSettings['piwik_url']); // This inits the API Request with the specified parameters if (class_exists('Piwik_API_Request')) { $objRequest = new Piwik_API_Request($strParams); } else { return NULL; } // Calls the API and fetch XML data back return $objRequest->process(); }
protected function createAccessObject() { parent::createAccessObject(); Piwik::setUserIsSuperUser(true); }
protected function getGraphData() { $saveGet = $_GET; $params = array_merge($this->generateGraphDataParams, $this->parametersToModify); foreach ($params as $key => $val) { // We do not forward filter data to the graph controller. // This would cause the graph to have filter_limit=5 set by default, // which would break them (graphs need the full dataset to build the "Others" aggregate value) if (strpos($key, 'filter_') !== false) { continue; } if (is_array($val)) { $val = implode(',', $val); } $_GET[$key] = $val; } $content = Piwik_FrontController::getInstance()->fetchDispatch($this->currentControllerName, $this->currentControllerAction, array()); $_GET = $saveGet; return str_replace(array("\r", "\n"), '', $content); }
/** * Calls a set of controller actions & either checks the result against * expected output or just checks if errors occurred when called. * * The behavior of this function can be modified by setting * Test_Integration::$widgetTestingLevel (or $testingLevelOverride): * <ul> * <li>If set to <b>NO_WIDGET_TESTING</b> this function simply returns.<li> * <li>If set to <b>CHECK_WIDGET_ERRORS</b> controller actions are called & * this function will just check for errors.</li> * <li>If set to <b>COMPARE_WIDGET_OUTPUT</b> controller actions are * called & the output is checked against expected output.</li> * </ul> * * @param string $testName Unique name of this test group. Expected/processed * file names use this as a prefix. * @param array $actions Array of controller actions to call. Each element * must be in the following format: 'Controller.action' * @param array $requestParameters The request parameters to set. * @param array $userTypes The user types to test the controller with. Can contain * these values: 'anonymous', 'view', 'admin', 'superuser'. * Defaults to all four. * @param int $testingLevelOverride Overrides Test_Integration::$widgetTestingLevel. */ public function callWidgetsCompareOutput($testName, $actions, $requestParameters, $userTypes = false, $testingLevelOverride = false) { // deal with the testing level if (Test_Integration::$widgetTestingLevel == self::NO_WIDGET_TESTING) { return; } if ($testingLevelOverride === false) { $testingLevelOverride = self::$widgetTestingLevel; } // process $userTypes argument if (!$userTypes) { $userTypes = array('anonymous', 'view', 'admin', 'superuser'); } else { if (!is_array($userTypes)) { $userTypes = array($userTypes); } } $oldGet = $_GET; // get all testable controller actions if necessary $actionParams = array(); if ($actions == 'all') { // Goals.addWidgets requires idSite to be set $_GET['idSite'] = isset($requestParameters['idSite']) ? $requestParameters['idSite'] : '0'; list($actions, $actionParams) = $this->findAllWidgets(); $_GET = $oldGet; } else { if (!is_array($actions)) { $actions = array($actions); } } // run the tests foreach ($actions as $controllerAction) { $customParams = isset($actionParams[$controllerAction]) ? $actionParams[$controllerAction] : array(); list($controllerName, $actionName) = explode('.', $controllerAction); foreach ($userTypes as $userType) { $this->setUserType($userType); try { // set request parameters $_GET = array(); foreach ($customParams as $key => $value) { $_GET[$key] = $value; } foreach ($requestParameters as $key => $value) { $_GET[$key] = $value; } $_GET['module'] = $controllerName; $_GET['action'] = $actionName; if ($testingLevelOverride == self::CHECK_WIDGET_ERRORS) { $this->errorsOccurredInTest = array(); set_error_handler(array($this, "customErrorHandler")); } // call controller action $response = Piwik_FrontController::getInstance()->fetchDispatch(); list($processedFilePath, $expectedFilePath) = $this->getProcessedAndExpectedPaths($testName . '_' . $userType, $controllerAction, 'html'); if ($testingLevelOverride == self::CHECK_WIDGET_ERRORS) { restore_error_handler(); if (!empty($this->errorsOccurredInTest)) { // write processed (only if there are errors) file_put_contents($processedFilePath, $response); $this->fail("PHP Errors occurred in calling controller action '{$controllerAction}':"); foreach ($this->errorsOccurredInTest as $error) { echo " {$error}<br/>\n"; } } else { $this->pass(); } } else { // write raw processed response file_put_contents($processedFilePath, $response); // load expected $expected = $this->loadExpectedFile($expectedFilePath); if (!$expected) { continue; } // normalize eol delimeters $expected = str_replace("\r\n", "\n", $expected); $response = str_replace("\r\n", "\n", $response); // check against expected $passed = $this->assertEqual(trim($expected), trim($response), "<br/>\nDifferences with expected in: {$processedFilePath} %s "); if (!$passed) { var_dump('ERROR FOR ' . $controllerAction . ' -- FETCHED RESPONSE, then EXPECTED RESPONSE - '); echo "<br/>\n"; var_dump(htmlspecialchars($response)); echo "<br/>\n"; var_dump(htmlspecialchars($expected)); echo "<br/>\n"; } } } catch (Exception $e) { $this->fail("EXCEPTION THROWN IN {$controllerAction}: " . $e->getTraceAsString()); } } } // reset $_GET to old values $_GET = array(); foreach ($oldGet as $key => $value) { $_GET[$key] = $value; } // set user type $this->setUserType('superuser'); }
/** * Initialize Piwik Connector. * * require_once PIWIK_INCLUDE_PATH . "/index.php"; * require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php"; * Piwik_FrontController::getInstance()->init(); * * $con = new Knp\PiwikClient\Connection\PiwikConnection(); * * @param boolean $initFrontController will init Piwik instance if true */ public function __construct($initFrontController = false) { if ($initFrontController) { \Piwik_FrontController::getInstance()->init(); } }
public static function footerUserCountry($notification) { $out =& $notification->getNotificationObject(); $out = '</div> <div id="rightcolumn"> <h2>' . Piwik_Translate('Provider_WidgetProviders') . '</h2>'; $out .= Piwik_FrontController::getInstance()->fetchDispatch('Provider', 'getProvider'); $out .= '</div>'; }
error_reporting(E_ALL | E_NOTICE); @ini_set('display_errors', !defined('PIWIK_DISPLAY_ERRORS') || PIWIK_DISPLAY_ERRORS ? 1 : 0); @ini_set('xdebug.show_exception_trace', 0); @ini_set('magic_quotes_runtime', 0); define('PIWIK_DOCUMENT_ROOT', dirname(__FILE__) == '/' ? '' : dirname(__FILE__)); if (!defined('PIWIK_USER_PATH')) { define('PIWIK_USER_PATH', PIWIK_DOCUMENT_ROOT); } if (!defined('PIWIK_INCLUDE_PATH')) { define('PIWIK_INCLUDE_PATH', PIWIK_DOCUMENT_ROOT); } require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php'; require_once PIWIK_INCLUDE_PATH . '/core/testMinimumPhpVersion.php'; // NOTE: the code above this comment must be PHP4 compatible session_cache_limiter('nocache'); @date_default_timezone_set('UTC'); require_once PIWIK_INCLUDE_PATH . '/core/Loader.php'; if (!defined('PIWIK_ENABLE_SESSION_START') || PIWIK_ENABLE_SESSION_START) { Piwik_Session::start(); } if (!defined('PIWIK_ENABLE_ERROR_HANDLER') || PIWIK_ENABLE_ERROR_HANDLER) { require_once PIWIK_INCLUDE_PATH . '/core/ErrorHandler.php'; require_once PIWIK_INCLUDE_PATH . '/core/ExceptionHandler.php'; set_error_handler('Piwik_ErrorHandler'); set_exception_handler('Piwik_ExceptionHandler'); } if (!defined('PIWIK_ENABLE_DISPATCH') || PIWIK_ENABLE_DISPATCH) { $controller = Piwik_FrontController::getInstance(); $controller->init(); $controller->dispatch(); }
function redirectToIndex($moduleToRedirect, $actionToRedirect) { $sitesId = Piwik_SitesManager_API::getSitesIdWithAtLeastViewAccess(); if (!empty($sitesId)) { $firstSiteId = $sitesId[0]; $firstSite = new Piwik_Site($firstSiteId); if ($firstSite->getCreationDate()->isToday()) { $defaultDate = 'today'; } else { $defaultDate = Zend_Registry::get('config')->General->default_day; } $defaultPeriod = Zend_Registry::get('config')->General->default_period; header("Location:index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite={$firstSiteId}&period={$defaultPeriod}&date={$defaultDate}"); } else { if (Piwik::isUserIsSuperUser()) { Piwik_ExitWithMessage("Error: no website were found in this Piwik installation. \n\t\t\t\t<br>Check the table '" . Piwik::prefixTable('site') . "' that should contain your Piwik websites.", false, true); } $currentLogin = Piwik::getCurrentUserLogin(); if (!empty($currentLogin) && $currentLogin != 'anonymous') { $errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivileges'), $currentLogin); $errorMessage .= "<br /><br /> <b><a href='?module=" . Zend_Registry::get('auth')->getName() . "&action=logout'>› " . Piwik_Translate('General_Logout') . "</a></b><br />"; Piwik_ExitWithMessage($errorMessage, false, true); } else { Piwik_FrontController::dispatch('Login', false); } } exit; }
protected function getFlashData() { $saveGet = $_GET; foreach($this->parametersToModify as $key => $val) { if (is_array($val)) { $_GET[$key] = unserialize(serialize($val)); } else { $_GET[$key] = $val; } } $content = Piwik_FrontController::getInstance()->fetchDispatch( $this->currentControllerName, $this->currentControllerAction, array()); $_GET = $saveGet; return str_replace(array("\r", "\n", "'", '\"'), array('', '', "\\'", '\\\"'), $content); }
public static function footerMobileDevices($notification) { $out =& $notification->getNotificationObject(); $out = '</div> <div id="rightcolumn"> <h2>Mobile Devices</h2>'; $out .= Piwik_FrontController::getInstance()->fetchDispatch('MobileAnalytics', 'getDeviceName'); $out .= '</div>'; }
/** * Helper method used to redirect the current http request to another module/action * If specified, will also redirect to a given website, period and /or date * * @param string $moduleToRedirect Module, eg. "MultiSites" * @param string $actionToRedirect Action, eg. "index" * @param string $websiteId Website ID, eg. 1 * @param string $defaultPeriod Default period, eg. "day" * @param string $defaultDate Default date, eg. "today" * @param array $parameters Parameters to append to url */ function redirectToIndex($moduleToRedirect, $actionToRedirect, $websiteId = null, $defaultPeriod = null, $defaultDate = null, $parameters = array()) { if (is_null($websiteId)) { $websiteId = $this->getDefaultWebsiteId(); } if (is_null($defaultDate)) { $defaultDate = $this->getDefaultDate(); } if (is_null($defaultPeriod)) { $defaultPeriod = $this->getDefaultPeriod(); } $parametersString = ''; if (!empty($parameters)) { $parametersString = '&' . Piwik_Url::getQueryStringFromParameters($parameters); } if ($websiteId) { $url = "Location: index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite=" . $websiteId . "&period=" . $defaultPeriod . "&date=" . $defaultDate . $parametersString; header($url); exit; } if (Piwik::isUserIsSuperUser()) { Piwik_ExitWithMessage("Error: no website was found in this Piwik installation. \n\t\t\t<br />Check the table '" . Piwik_Common::prefixTable('site') . "' in your database, it should contain your Piwik websites.", false, true); } $currentLogin = Piwik::getCurrentUserLogin(); if (!empty($currentLogin) && $currentLogin != 'anonymous') { $errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivilegesAskPiwikAdmin'), $currentLogin, "<br/><a href='mailto:" . Piwik::getSuperUserEmail() . "?subject=Access to Piwik for user {$currentLogin}'>", "</a>"); $errorMessage .= "<br /><br /> <b><a href='index.php?module=" . Zend_Registry::get('auth')->getName() . "&action=logout'>› " . Piwik_Translate('General_Logout') . "</a></b><br />"; Piwik_ExitWithMessage($errorMessage, false, true); } Piwik_FrontController::getInstance()->dispatch(Piwik::getLoginPluginName(), false); exit; }
public function getEcommerceLog($fetch = false) { $saveGET = $_GET; $_GET['filterEcommerce'] = 1; $_GET['widget'] = 1; $_GET['segment'] = 'visitEcommerceStatus!=none'; $output = Piwik_FrontController::getInstance()->dispatch('Live', 'getVisitorLog', array($fetch)); $_GET = $saveGET; return $output; }
<?php // if you don't include 'index.php', you must also define PIWIK_DOCUMENT_ROOT // and include "libs/upgradephp/upgrade.php" and "core/Loader.php" define('PIWIK_INCLUDE_PATH', realpath('..')); define('PIWIK_USER_PATH', realpath('..')); define('PIWIK_ENABLE_DISPATCH', false); define('PIWIK_ENABLE_ERROR_HANDLER', false); define('PIWIK_ENABLE_SESSION_START', false); require_once PIWIK_INCLUDE_PATH . "/index.php"; require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php"; Piwik_FrontController::getInstance()->init(); // This inits the API Request with the specified parameters $request = new Piwik_API_Request(' method=UserSettings.getResolution &idSite=7 &date=yesterday &period=week &format=XML &filter_limit=3 &token_auth=anonymous '); // Calls the API and fetch XML data back $result = $request->process(); echo $result;
/** * Init Piwik, connect DB, create log & config objects, etc. */ private function initCore() { try { Piwik_FrontController::getInstance()->init(); } catch (Exception $e) { echo "ERROR: During Piwik init, Message: " . $e->getMessage(); exit; } }
public function footerVisitsFrequency($notification) { $out =& $notification->getNotificationObject(); $out = '</div> <div id="rightcolumn"> '; $out .= Piwik_FrontController::getInstance()->fetchDispatch('VisitorInterest', 'index'); $out .= '</div>'; }
function redirectToIndex($moduleToRedirect, $actionToRedirect) { $websiteId = $this->getDefaultWebsiteId(); $defaultDate = $this->getDefaultDate(); $defaultPeriod = $this->getDefaultPeriod(); if ($websiteId) { header("Location:index.php?module=" . $moduleToRedirect . "&action=" . $actionToRedirect . "&idSite=" . $websiteId . "&period=" . $defaultPeriod . "&date=" . $defaultDate); exit; } if (Piwik::isUserIsSuperUser()) { Piwik_ExitWithMessage("Error: no website were found in this Piwik installation. \n\t\t\t<br>Check the table '" . Piwik::prefixTable('site') . "' that should contain your Piwik websites.", false, true); } $currentLogin = Piwik::getCurrentUserLogin(); if (!empty($currentLogin) && $currentLogin != 'anonymous') { $errorMessage = sprintf(Piwik_Translate('CoreHome_NoPrivileges'), $currentLogin); $errorMessage .= "<br /><br /> <b><a href='index.php?module=" . Zend_Registry::get('auth')->getName() . "&action=logout'>› " . Piwik_Translate('General_Logout') . "</a></b><br />"; Piwik_ExitWithMessage($errorMessage, false, true); } Piwik_FrontController::dispatch('Login', false); exit; }