function addMenu() { Piwik_AddAdminMenu('CorePluginsAdmin_MenuPlugins', array('module' => 'CorePluginsAdmin', 'action' => 'index'), Piwik::isUserIsSuperUser(), $order = 7); }
public function generalSettings() { Piwik::checkUserHasSomeAdminAccess(); $view = Piwik_View::factory('generalSettings'); if (Piwik::isUserIsSuperUser()) { $enableBrowserTriggerArchiving = Piwik_ArchiveProcessing::isBrowserTriggerArchivingEnabled(); $todayArchiveTimeToLive = Piwik_ArchiveProcessing::getTodayArchiveTimeToLive(); $showWarningCron = false; if (!$enableBrowserTriggerArchiving && $todayArchiveTimeToLive < 3600) { $showWarningCron = true; } $view->showWarningCron = $showWarningCron; $view->todayArchiveTimeToLive = $todayArchiveTimeToLive; $view->enableBrowserTriggerArchiving = $enableBrowserTriggerArchiving; $view->language = Piwik_LanguagesManager::getLanguageCodeForCurrentUser(); if (!Zend_Registry::get('config')->isFileWritable()) { $view->configFileNotWritable = true; } $view->mail = Zend_Registry::get('config')->mail->toArray(); } $this->setBasicVariablesView($view); $view->topMenu = Piwik_GetTopMenu(); $view->menu = Piwik_GetAdminMenu(); echo $view->render(); }
function index() { Piwik::checkUserIsNotAnonymous(); $view = Piwik_View::factory('Settings'); $view->isSuperUser = Piwik::isUserIsSuperUser(); $mobileMessagingAPI = Piwik_MobileMessaging_API::getInstance(); $view->delegatedManagement = $mobileMessagingAPI->getDelegatedManagement(); $view->credentialSupplied = $mobileMessagingAPI->areSMSAPICredentialProvided(); $view->accountManagedByCurrentUser = $view->isSuperUser || $view->delegatedManagement; $view->strHelpAddPhone = Piwik_Translate('MobileMessaging_Settings_PhoneNumbers_HelpAdd', array(Piwik_Translate('UserSettings_SubmenuSettings'), Piwik_Translate('MobileMessaging_SettingsMenu'))); if ($view->credentialSupplied && $view->accountManagedByCurrentUser) { $view->provider = $mobileMessagingAPI->getSMSProvider(); $view->creditLeft = $mobileMessagingAPI->getCreditLeft(); } $view->smsProviders = Piwik_MobileMessaging_SMSProvider::$availableSMSProviders; // construct the list of countries from the lang files $countries = array(); foreach (Piwik_Common::getCountriesList() as $countryCode => $continentCode) { if (isset(Piwik_MobileMessaging_CountryCallingCodes::$countryCallingCodes[$countryCode])) { $countries[$countryCode] = array('countryName' => Piwik_CountryTranslate($countryCode), 'countryCallingCode' => Piwik_MobileMessaging_CountryCallingCodes::$countryCallingCodes[$countryCode]); } } $view->countries = $countries; $view->defaultCountry = Piwik_Common::getCountry(Piwik_LanguagesManager::getLanguageCodeForCurrentUser(), true, Piwik_IP::getIpFromHeader()); $view->phoneNumbers = $mobileMessagingAPI->getPhoneNumbers(); $this->setBasicVariablesView($view); $view->menu = Piwik_GetAdminMenu(); echo $view->render(); }
public function generalSettings() { Piwik::checkUserHasSomeAdminAccess(); $view = Piwik_View::factory('generalSettings'); if (Piwik::isUserIsSuperUser()) { $enableBrowserTriggerArchiving = Piwik_ArchiveProcessing::isBrowserTriggerArchivingEnabled(); $todayArchiveTimeToLive = Piwik_ArchiveProcessing::getTodayArchiveTimeToLive(); $showWarningCron = false; if (!$enableBrowserTriggerArchiving && $todayArchiveTimeToLive < 3600) { $showWarningCron = true; } $view->showWarningCron = $showWarningCron; $view->todayArchiveTimeToLive = $todayArchiveTimeToLive; $view->enableBrowserTriggerArchiving = $enableBrowserTriggerArchiving; if (!Piwik_Config::getInstance()->isFileWritable()) { $view->configFileNotWritable = true; } $view->mail = Piwik_Config::getInstance()->mail; $view->branding = Piwik_Config::getInstance()->branding; $directoryWritable = is_writable(PIWIK_DOCUMENT_ROOT . '/themes/'); $logoFilesWriteable = is_writeable(PIWIK_DOCUMENT_ROOT . '/themes/logo.png') && is_writeable(PIWIK_DOCUMENT_ROOT . '/themes/logo-header.png'); $view->logosWriteable = ($logoFilesWriteable || $directoryWritable) && ini_get('file_uploads') == 1; } $view->language = Piwik_LanguagesManager::getLanguageCodeForCurrentUser(); $this->setBasicVariablesView($view); $view->topMenu = Piwik_GetTopMenu(); $view->menu = Piwik_GetAdminMenu(); echo $view->render(); }
function addMenu() { Piwik_AddAdminMenu('DBStats_DatabaseUsage', array('module' => 'DBStats', 'action' => 'index'), Piwik::isUserIsSuperUser(), $order = 9); }
public function render() { try { $this->currentModule = Piwik::getModule(); $this->currentPluginName = Piwik::getCurrentPlugin()->getName(); $this->userLogin = Piwik::getCurrentUserLogin(); $showWebsiteSelectorInUserInterface = Zend_Registry::get('config')->General->show_website_selector_in_user_interface; if ($showWebsiteSelectorInUserInterface) { $sites = Piwik_SitesManager_API::getSitesWithAtLeastViewAccess(); usort($sites, create_function('$site1, $site2', 'return strcasecmp($site1["name"], $site2["name"]);')); $this->sites = $sites; } $this->showWebsiteSelectorInUserInterface = $showWebsiteSelectorInUserInterface; $this->url = Piwik_Url::getCurrentUrl(); $this->token_auth = Piwik::getCurrentUserTokenAuth(); $this->userHasSomeAdminAccess = Piwik::isUserHasSomeAdminAccess(); $this->userIsSuperUser = Piwik::isUserIsSuperUser(); $this->piwik_version = Piwik_Version::VERSION; $this->latest_version_available = Piwik_UpdateCheck::isNewestVersionAvailable(); $this->loginModule = Zend_Registry::get('auth')->getName(); } 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; } header('Content-Type: text/html; charset=utf-8'); header("Pragma: "); header("Cache-Control: no-store, must-revalidate"); return $this->smarty->fetch($this->template); }
function index() { $view = Piwik_View::factory('SitesManager'); if (Piwik::isUserIsSuperUser()) { $sites = Piwik_SitesManager_API::getInstance()->getAllSites(); Piwik_Site::setSites($sites); $sites = array_values($sites); } else { $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess(); Piwik_Site::setSitesFromArray($sites); } foreach ($sites as &$site) { $site['alias_urls'] = Piwik_SitesManager_API::getInstance()->getSiteUrlsFromId($site['idsite']); $site['excluded_ips'] = str_replace(',', '<br/>', $site['excluded_ips']); $site['excluded_parameters'] = str_replace(',', '<br/>', $site['excluded_parameters']); } $view->adminSites = $sites; $view->adminSitesCount = count($sites); $timezones = Piwik_SitesManager_API::getInstance()->getTimezonesList(); $view->timezoneSupported = Piwik::isTimezoneSupportEnabled(); $view->timezones = Piwik_Common::json_encode($timezones); $view->defaultTimezone = Piwik_SitesManager_API::getInstance()->getDefaultTimezone(); $view->currencies = Piwik_Common::json_encode(Piwik_SitesManager_API::getInstance()->getCurrencyList()); $view->defaultCurrency = Piwik_SitesManager_API::getInstance()->getDefaultCurrency(); $view->utcTime = Piwik_Date::now()->getDatetime(); $excludedIpsGlobal = Piwik_SitesManager_API::getInstance()->getExcludedIpsGlobal(); $view->globalExcludedIps = str_replace(',', "\n", $excludedIpsGlobal); $excludedQueryParametersGlobal = Piwik_SitesManager_API::getInstance()->getExcludedQueryParametersGlobal(); $view->globalExcludedQueryParameters = str_replace(',', "\n", $excludedQueryParametersGlobal); $view->currentIpAddress = Piwik_IP::getIpFromHeader(); $view->showAddSite = (bool) Piwik_Common::getRequestVar('showaddsite', false); $this->setBasicVariablesView($view); $view->menu = Piwik_GetAdminMenu(); echo $view->render(); }
function addMenu() { Piwik_AddAdminMenu('SecurityInfo_Security', array('module' => 'SecurityInfo', 'action' => 'index'), Piwik::isUserIsSuperUser(), $order = 10); }
public function addMenu() { Piwik_AddAdminMenu( 'VisitorGenerator_VisitorGenerator', array('module' => 'VisitorGenerator', 'action' => 'index'), Piwik::isUserIsSuperUser(), $order = 10 ); }
/** * This method displays a text containing an help about "How to build plugins for Piwik". * This help is then used on http://piwik.org/docs/plugins/functions * */ function index() { $out = ''; $out .= '<i>This page aims to list the different functions you can use when programming plugins for Piwik.</i><br />'; $out .= '<b>Be careful, the following APIs may change in the near future as Piwik is still in development.</b><br />'; $out .= '<h2>General</h2>'; $out .= '<h3>Accessible from your plugin controller</h3>'; $out .= '<code>$this->date</code> = current selected <b>Piwik_Date</b> object (<a href="http://dev.piwik.org/trac/browser/trunk/core/Date.php">class</a>)<br />'; $out .= '<code>$period = Piwik_Common::getRequestVar("period");</code> - Get the current selected period<br />'; $out .= '<code>$idSite = Piwik_Common::getRequestVar("idSite");</code> - Get the selected idSite<br />'; $out .= '<code>$site = new Piwik_Site($idSite);</code> - Build the Piwik_Site object (<a href="http://dev.piwik.org/trac/browser/trunk/core/Site.php">class</a>)<br />'; $out .= '<code>$this->str_date</code> = current selected date in YYYY-MM-DD format<br />'; $out .= '<h3>Misc</h3>'; $out .= '<code>Piwik_AddMenu( $mainMenuName, $subMenuName, $url );</code> - Adds an entry to the menu in the Piwik interface (See the example in the <a href="http://dev.piwik.org/trac/browser/tags/1.0/plugins/UserCountry/UserCountry.php#L76">UserCountry Plugin file</a>)<br />'; $out .= '<code>Piwik_AddWidget( $widgetCategory, $widgetName, $controllerName, $controllerAction, $customParameters = array());</code> - Adds a widget that users can add in the dashboard, or export using the Widgets link at the top of the screen. See the example in the <a href="http://dev.piwik.org/trac/browser/tags/1.0/plugins/UserCountry/UserCountry.php#L70">UserCountry Plugin file</a> or any other plugin)<br />'; $out .= '<code>Piwik_Common::prefixTable("site")</code> = <b>' . Piwik_Common::prefixTable("site") . '</b><br />'; $out .= '<h2>User access</h2>'; $out .= '<code>Piwik::getCurrentUserLogin()</code> = <b>' . Piwik::getCurrentUserLogin() . '</b><br />'; $out .= '<code>Piwik::isUserHasSomeAdminAccess()</code> = <b>' . self::boolToString(Piwik::isUserHasSomeAdminAccess()) . '</b><br />'; $out .= '<code>Piwik::isUserHasAdminAccess( array $idSites = array(1,2) )</code> = <b>' . self::boolToString(Piwik::isUserHasAdminAccess(array(1, 2))) . '</b><br />'; $out .= '<code>Piwik::isUserHasViewAccess( array $idSites = array(1) ) </code> = <b>' . self::boolToString(Piwik::isUserHasViewAccess(array(1))) . '</b><br />'; $out .= '<code>Piwik::isUserIsSuperUser()</code> = <b>' . self::boolToString(Piwik::isUserIsSuperUser()) . '</b><br />'; $out .= '<h2>Execute SQL queries</h2>'; $txtQuery = "SELECT token_auth FROM " . Piwik_Common::prefixTable('user') . " WHERE login = ?"; $result = Piwik_FetchOne($txtQuery, array('anonymous')); $out .= '<code>Piwik_FetchOne("' . $txtQuery . '", array("anonymous"))</code> = <b>' . var_export($result, true) . '</b><br />'; $out .= '<br />'; $query = Piwik_Query($txtQuery, array('anonymous')); $fetched = $query->fetch(); $token_auth = $fetched['token_auth']; $out .= '<code>$query = Piwik_Query("' . $txtQuery . '", array("anonymous"))</code><br />'; $out .= '<code>$fetched = $query->fetch();</code><br />'; $out .= 'At this point, we have: <code>$fetched[\'token_auth\'] == <b>' . var_export($token_auth, true) . '</b></code><br />'; $out .= '<h2>Example Sites information API</h2>'; $out .= '<code>Piwik_SitesManager_API::getInstance()->getSitesWithViewAccess()</code> = <b><pre>' . var_export(Piwik_SitesManager_API::getInstance()->getSitesWithViewAccess(), true) . '</pre></b><br />'; $out .= '<code>Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess()</code> = <b><pre>' . var_export(Piwik_SitesManager_API::getInstance()->getSitesWithAdminAccess(), true) . '</pre></b><br />'; $out .= '<h2>Example API Users information</h2>'; $out .= 'View the list of API methods you can call on <a href="http://piwik.org/docs/analytics-api/reference">API reference</a><br />'; $out .= 'For example you can try <code>Piwik_UsersManager_API::getInstance()->getUsersSitesFromAccess("view");</code> or <code>Piwik_UsersManager_API::getInstance()->deleteUser("userToDelete");</code><br />'; $out .= '<h2>Javascript in Piwik</h2>'; $out .= '<h3>i18n internationalization</h3>'; $out .= 'In order to translate strings within Javascript code, you can use the javascript function _pk_translate( token );. <ul><li>The "token" parameter is the string unique key found in the translation file. For this token string to be available in Javascript, you must suffix your token by "_js" in the language file. For example, you can add <code>\'Goals_AddGoal_js\' => \'Add Goal\',</code> in the lang/en.php file</li> <li>You then need to instruct Piwik to load your Javascript translations for your plugin; by default, all translation strings are not loaded in Javascript for performance reasons. This can be done by calling a custom-made Smarty modifier before the Javascript code requiring translations, eg. <code>{loadJavascriptTranslations plugins=\'$YOUR_PLUGIN_NAME\'}</code>. In our previous example, the $YOUR_PLUGIN_NAME being Goals, we would write <code>{loadJavascriptTranslations plugins=\'Goals\'}</code> </li><li>You can then print this string from your JS code by doing <code>_pk_translate(\'Goals_AddGoal_js\');</code>. </li></ul>'; $out .= '<h3>Reload a widget in the dashboard</h3>'; $out .= 'It is sometimes useful to reload one widget in the dashboard (for example, every 20 seconds for a real time widget, or after a setting change). You can easily force your widget to reload in the dashboard by calling the helper function <code>piwik.dashboardObject.reloadEnclosingWidget($(this));</code>.'; $out .= '<h2>Smarty plugins</h2>'; $out .= 'There are some builtin plugins for Smarty especially developped for Piwik. <br /> You can find them on the <a href="http://dev.piwik.org/trac/browser/trunk/core/SmartyPlugins">SVN at /trunk/core/SmartyPlugins</a>. <br /> More documentation to come about smarty plugins.<br />'; echo $out; }
function redirectToIndex() { if (Piwik::isUserIsSuperUser()) { $module = 'CorePluginsAdmin'; } else { $module = 'SitesManager'; } header("Location:index.php?module=" . $module); }
/** * Returns a report displaying the total visits, actions and revenue, as * well as the evolution of these values, of all existing sites over a * specified period of time. * * If the specified period is not a 'range', this function will calculcate * evolution metrics. Evolution metrics are metrics that display the * percent increase/decrease of another metric since the last period. * * This function will merge the result of the archive query so each * row in the result DataTable will correspond to the metrics of a single * site. If a date range is specified, the result will be a * DataTable_Array, but it will still be merged. * * @param string $period The period type to get data for. * @param string $date The date(s) to get data for. * @param string $segment The segments to get data for. */ public function getAll($period, $date, $segment = false) { Piwik::checkUserHasSomeViewAccess(); $isGoalPluginEnabled = Piwik_Common::isGoalPluginEnabled(); // get site data for every viewable site and cache them if (Piwik::isUserIsSuperUser()) { $sites = Piwik_SitesManager_API::getInstance()->getAllSites(); Piwik_Site::setSites($sites); } else { $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess(); Piwik_Site::setSitesFromArray($sites); } // build the archive type used to query archive data $archive = Piwik_Archive::build('all', $period, $date, $segment); // determine what data will be displayed $fieldsToGet = array('nb_visits', 'nb_actions'); if ($isGoalPluginEnabled) { $revenueMetric = Piwik_Goals::getRecordName('revenue'); $fieldsToGet[] = $revenueMetric; } // get the data $dataTable = $archive->getDataTableFromNumeric($fieldsToGet); // get rid of the DataTable_Array that is created by the IndexedBySite archive type $dataTable = $dataTable->mergeChildren(); // if the period isn't a range & a lastN/previousN date isn't used, we get the same // data for the last period to show the evolution of visits/actions/revenue if ($period != 'range' && !preg_match('/(last|previous)([0-9]*)/', $date, $regs)) { if (strpos($date, ',')) { $rangePeriod = new Piwik_Period_Range($period, $date); $lastStartDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateStart(), $n = 1); $lastEndDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateEnd(), $n = 1); $strLastDate = "{$lastStartDate},{$lastEndDate}"; } else { $strLastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1)->toString(); } $pastArchive = Piwik_Archive::build('all', $period, $strLastDate, $segment); $pastData = $pastArchive->getDataTableFromNumeric($fieldsToGet); $pastData = $pastData->mergeChildren(); // use past data to calculate evolution percentages $this->calculateEvolutionPercentages($dataTable, $pastData, $fieldsToGet); } // move the site id to a metadata column $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'idsite')); // set the label of each row to the site name $getNameFor = array('Piwik_Site', 'getNameFor'); $dataTable->filter('ColumnCallbackReplace', array('label', $getNameFor)); // rename the revenue column from the metric name to 'revenue' if ($isGoalPluginEnabled) { $mapping = array($revenueMetric => 'revenue'); $dataTable->filter('ReplaceColumnNames', array($mapping)); } // Ensures data set sorted, for Metadata output $dataTable->filter('Sort', array('nb_visits', 'desc', $naturalSort = false)); return $dataTable; }
public function privacySettings() { Piwik::checkUserHasSomeAdminAccess(); $view = Piwik_View::factory('privacySettings'); if (Piwik::isUserIsSuperUser()) { $deleteLogs = array(); $view->deleteLogs = $this->getDeleteLogsInfo(); $view->anonymizeIP = $this->getAnonymizeIPInfo(); } $view->language = Piwik_LanguagesManager::getLanguageCodeForCurrentUser(); if (!Zend_Registry::get('config')->isFileWritable()) { $view->configFileNotWritable = true; } $this->setBasicVariablesView($view); $view->menu = Piwik_GetAdminMenu(); echo $view->render(); }
public static function setBasicVariablesAdminView($view) { $view->currentAdminMenuName = Piwik_GetCurrentAdminMenuName(); $view->enableFrames = Piwik_Config::getInstance()->General['enable_framed_settings']; if (!$view->enableFrames) { $view->setXFrameOptions('sameorigin'); } $view->isSuperUser = Piwik::isUserIsSuperUser(); // for old geoip plugin warning $view->usingOldGeoIPPlugin = Piwik_PluginsManager::getInstance()->isPluginActivated('GeoIP'); // for cannot find installed plugin warning $missingPlugins = Piwik_PluginsManager::getInstance()->getMissingPlugins(); if (!empty($missingPlugins)) { $pluginsLink = Piwik_Url::getCurrentQueryStringWithParametersModified(array('module' => 'CorePluginsAdmin', 'action' => 'index')); $view->missingPluginsWarning = Piwik_Translate('CoreAdminHome_MissingPluginsWarning', array('<strong>' . implode('</strong>, <strong>', $missingPlugins) . '</strong>', '<a href="' . $pluginsLink . '"/>', '</a>')); } }
/** Admin menu hook */ public function addAdminMenu() { Piwik_AddAdminMenu('SiteSearch_SiteSearch', array('module' => 'SiteSearch', 'action' => 'admin'), Piwik::isUserIsSuperUser(), 8); }
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; }
/** * 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); }
/** * 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); }
/** * Get current user email address * * @return string */ public static function getCurrentUserEmail() { if (!Piwik::isUserIsSuperUser()) { $user = Piwik_UsersManager_API::getInstance()->getUser(Piwik::getCurrentUserLogin()); return $user['email']; } return self::getSuperUserEmail(); }
/** * This method displays a text containing an help about "How to build plugins for Piwik". * This help is then used on http://dev.piwik.org/trac/wiki/Plugins/GlobalFunctions * */ function index() { $out = ''; $out .= '<i>This page aims to list the different functions you can use when programming plugins for Piwik.</i><br>'; $out .= '<b>Be careful, the following APIs may change in the near future as Piwik is still in development.</b><br>'; $out .= '<h2>General</h2>'; $out .= '<h3>Accessible from your plugin controller</h3>'; $out .= '<code>$this->date</code> = current selected <b>Piwik_Date</b> object (<a href="http://dev.piwik.org/trac/browser/trunk/core/Date.php">class</a>)<br/>'; $out .= '<code>$period = Piwik_Common::getRequestVar("period");</code> - Get the current selected period<br/>'; $out .= '<code>$idSite = Piwik_Common::getRequestVar("idSite");</code> - Get the selected idSite<br/>'; $out .= '<code>$site = new Piwik_Site($idSite);</code> - Build the Piwik_Site object (<a href="http://dev.piwik.org/trac/browser/trunk/core/Site.php">class</a>)<br/>'; $out .= '<code>$this->str_date</code> = current selected date in YYYY-MM-DD format<br/>'; $out .= '<h3>Misc</h3>'; $out .= '<code>Piwik_AddMenu( $mainMenuName, $subMenuName, $url );</code> - Adds an entry to the menu in the Piwik interface (See the example in the <a href="http://dev.piwik.org/trac/browser/trunk/plugins/UserCountry/UserCountry.php#L146">UserCountry Plugin file</a>)<br/>'; $out .= '<code>Piwik_AddWidget( $widgetCategory, $widgetName, $controllerName, $controllerAction, $customParameters = array());</code> - Adds a widget that users can add in the dashboard, or export using the Widgets link at the top of the screen. See the example in the <a href="http://dev.piwik.org/trac/browser/trunk/plugins/UserCountry/UserCountry.php#L143">UserCountry Plugin file</a> or any other plugin)<br/>'; $out .= '<code>Piwik::prefixTable("site")</code> = <b>' . Piwik::prefixTable("site") . '</b><br/>'; $out .= '<h2>User access</h2>'; $out .= '<code>Piwik::getCurrentUserLogin()</code> = <b>' . Piwik::getCurrentUserLogin() . '</b><br/>'; $out .= '<code>Piwik::isUserHasSomeAdminAccess()</code> = <b>' . self::boolToString(Piwik::isUserHasSomeAdminAccess()) . '</b><br/>'; $out .= '<code>Piwik::isUserHasAdminAccess( array $idSites = array(1,2) )</code> = <b>' . self::boolToString(Piwik::isUserHasAdminAccess(array(1,2) )) . '</b><br/>'; $out .= '<code>Piwik::isUserHasViewAccess( array $idSites = array(1) ) </code> = <b>' . self::boolToString(Piwik::isUserHasViewAccess(array(1))) . '</b><br/>'; $out .= '<code>Piwik::isUserIsSuperUser()</code> = <b>' . self::boolToString(Piwik::isUserIsSuperUser()) . '</b><br/>'; $out .= '<h2>Execute SQL queries</h2>'; $txtQuery = "SELECT token_auth FROM ".Piwik::prefixTable('user')." WHERE login = ?"; $result = Piwik_FetchOne($txtQuery, array('anonymous')); $out .= '<code>Piwik_FetchOne("'.$txtQuery.'", array("anonymous"))</code> = <b>' . var_export($result,true) . '</b><br/>'; $out .= '<br>'; $query = Piwik_Query($txtQuery, array('anonymous')); $fetched = $query->fetch(); $token_auth = $fetched['token_auth']; $out .= '<code>$query = Piwik_Query("'.$txtQuery.'", array("anonymous"))</code><br>'; $out .= '<code>$fetched = $query->fetch();</code><br>'; $out .= 'At this point, we have: <code>$fetched[\'token_auth\'] == <b>'.var_export($token_auth,true) . '</b></code><br/>'; $out .= '<h2>Example Sites information API</h2>'; $out .= '<code>Piwik_SitesManager_API::getSitesWithViewAccess()</code> = <b><pre>' .var_export(Piwik_SitesManager_API::getSitesWithViewAccess(),true) . '</pre></b><br/>'; $out .= '<code>Piwik_SitesManager_API::getSitesWithAdminAccess()</code> = <b><pre>' .var_export(Piwik_SitesManager_API::getSitesWithAdminAccess(),true) . '</pre></b><br/>'; $out .= '<h2>Example API Users information</h2>'; $out .= 'View the list of API methods you can call on <a href="http://dev.piwik.org/trac/wiki/API/Reference#Methods">API reference</a><br/>'; $out .= 'For example you can try <code>Piwik_UsersManager_API::getUsersSitesFromAccess("view");</code> or <code>Piwik_UsersManager_API::deleteUser("userToDelete");</code><br/>'; $out .= '<h2>Smarty plugins</h2>'; $out .= 'There are some builtin plugins for Smarty especially developped for Piwik. <br> You can find them on the <a href="http://dev.piwik.org/trac/browser/trunk/core/SmartyPlugins">SVN at /trunk/core/SmartyPlugins</a>. <br> More documentation to come about smarty plugins.<br/>'; echo $out; }
/** * Get current user email address * * @return string */ public static function getCurrentUserEmail() { if (!Piwik::isUserIsSuperUser()) { $user = Piwik_UsersManager_API::getInstance()->getUser(Piwik::getCurrentUserLogin()); return $user['email']; } $superuser = Zend_Registry::get('config')->superuser; return $superuser->email; }
private function buildDataTable($sites, $period, $date, $segment, $_restrictSitesToLogin, $enhanced) { $allWebsitesRequested = $sites == 'all'; if ($allWebsitesRequested) { if (Piwik::isUserIsSuperUser() && !Piwik_TaskScheduler::isTaskBeingExecuted()) { Piwik_Site::setSites(Piwik_SitesManager_API::getInstance()->getAllSites()); } else { Piwik_Site::setSitesFromArray(Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin)); } } // build the archive type used to query archive data $archive = Piwik_Archive::build($sites, $period, $date, $segment, $_restrictSitesToLogin); // determine what data will be displayed $fieldsToGet = array(); $columnNameRewrites = array(); $apiECommerceMetrics = array(); $apiMetrics = Piwik_MultiSites_API::getApiMetrics($enhanced); foreach ($apiMetrics as $metricName => $metricSettings) { $fieldsToGet[] = $metricSettings[self::METRIC_RECORD_NAME_KEY]; $columnNameRewrites[$metricSettings[self::METRIC_RECORD_NAME_KEY]] = $metricName; if ($metricSettings[self::METRIC_IS_ECOMMERCE_KEY]) { $apiECommerceMetrics[$metricName] = $metricSettings; } } // get the data // $dataTable instanceOf Piwik_DataTable_Array $dataTable = $archive->getDataTableFromNumeric($fieldsToGet); // get rid of the DataTable_Array that is created by the IndexedBySite archive type if ($dataTable instanceof Piwik_DataTable_Array && $allWebsitesRequested) { $dataTable = $dataTable->mergeChildren(); } else { if (!$dataTable instanceof Piwik_DataTable_Array) { $firstDataTableRow = $dataTable->getFirstRow(); $firstDataTableRow->setColumn('label', $sites); } } // if the period isn't a range & a lastN/previousN date isn't used, we get the same // data for the last period to show the evolution of visits/actions/revenue if ($period != 'range' && !preg_match('/(last|previous)([0-9]*)/', $date, $regs)) { if (strpos($date, ',')) { $rangePeriod = new Piwik_Period_Range($period, $date); $lastStartDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateStart(), $n = 1); $lastEndDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateEnd(), $n = 1); $strLastDate = "{$lastStartDate},{$lastEndDate}"; } else { $strLastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1)->toString(); } $pastArchive = Piwik_Archive::build('all', $period, $strLastDate, $segment, $_restrictSitesToLogin); $pastData = $pastArchive->getDataTableFromNumeric($fieldsToGet); $pastData = $pastData->mergeChildren(); // use past data to calculate evolution percentages $this->calculateEvolutionPercentages($dataTable, $pastData, $apiMetrics); } // remove eCommerce related metrics on non eCommerce Piwik sites // note: this is not optimal in terms of performance: those metrics should not be retrieved in the first place if ($enhanced) { // $dataTableRows instanceOf Piwik_DataTable_Row[] $dataTableRows = $dataTable->getRows(); foreach ($dataTableRows as $dataTableRow) { $siteId = $dataTableRow->getColumn('label'); if (!Piwik_Site::isEcommerceEnabledFor($siteId)) { foreach ($apiECommerceMetrics as $metricSettings) { $dataTableRow->deleteColumn($metricSettings[self::METRIC_RECORD_NAME_KEY]); $dataTableRow->deleteColumn($metricSettings[self::METRIC_EVOLUTION_COL_NAME_KEY]); } } } } // move the site id to a metadata column $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'idsite')); // set the label of each row to the site name if ($allWebsitesRequested) { $getNameFor = array('Piwik_Site', 'getNameFor'); $dataTable->filter('ColumnCallbackReplace', array('label', $getNameFor)); } else { $dataTable->filter('ColumnDelete', array('label')); } // replace record names with user friendly metric names $dataTable->filter('ReplaceColumnNames', array($columnNameRewrites)); // Ensures data set sorted, for Metadata output $dataTable->filter('Sort', array(self::NB_VISITS_METRIC, 'desc', $naturalSort = false)); // filter rows without visits // note: if only one website is queried and there are no visits, we can not remove the row otherwise Piwik_API_ResponseBuilder throws 'Call to a member function getColumns() on a non-object' if ($allWebsitesRequested) { $dataTable->filter('ColumnCallbackDeleteRow', array(self::NB_VISITS_METRIC, create_function('$value', 'return $value != 0;'))); } return $dataTable; }
/** * Returns the list of all the users * * @param string $userLogins Comma separated list of users to select. If not specified, will return all users * @return array the list of all the users */ public function getUsers($userLogins = '') { Piwik::checkUserHasSomeAdminAccess(); $where = ''; $bind = array(); if (!empty($userLogins)) { $userLogins = explode(',', $userLogins); $where = 'WHERE login IN (' . Piwik_Common::getSqlStringFieldsArray($userLogins) . ')'; $bind = $userLogins; } $db = Zend_Registry::get('db'); $users = $db->fetchAll("SELECT * \n\t\t\t\t\t\t\t\tFROM " . Piwik_Common::prefixTable("user") . "\n\t\t\t\t\t\t\t\t{$where} \n\t\t\t\t\t\t\t\tORDER BY login ASC", $bind); // Non Super user can only access login & alias if (!Piwik::isUserIsSuperUser()) { foreach ($users as &$user) { $user = array('login' => $user['login'], 'alias' => $user['alias']); } } return $users; }
private static function cleanVisitorDetails(&$visitorDetails) { $toUnset = array('config_md5config'); if (!Piwik::isUserIsSuperUser()) { $toUnset[] = 'visitor_idcookie'; $toUnset[] = 'location_ip'; } foreach ($toUnset as $keyName) { if (isset($visitorDetails[$keyName])) { unset($visitorDetails[$keyName]); } } }
/** * Tracker requests will automatically trigger the Scheduled tasks. * This is useful for users who don't setup the cron, * but still want daily/weekly/monthly PDF reports emailed automatically. * * This is similar to calling the API CoreAdminHome.runScheduledTasks (see misc/cron/archive.sh) * * @param int $now Current timestamp */ public static function runScheduledTasks($now) { // Currently, there is no hourly tasks. When there are some, // this could be too agressive minimum interval (some hours would be skipped in case of low traffic) $minimumInterval = Piwik_Config::getInstance()->Tracker['scheduled_tasks_min_interval']; // If the user disabled browser archiving, he has already setup a cron // To avoid parallel requests triggering the Scheduled Tasks, // Get last time tasks started executing $cache = Piwik_Common::getCacheGeneral(); if ($minimumInterval <= 0 || empty($cache['isBrowserTriggerArchivingEnabled'])) { printDebug("-> Scheduled tasks not running in Tracker: Browser archiving is disabled."); return; } $nextRunTime = $cache['lastTrackerCronRun'] + $minimumInterval; if (isset($GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS']) && $GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS'] || $cache['lastTrackerCronRun'] === false || $nextRunTime < $now) { $cache['lastTrackerCronRun'] = $now; Piwik_Common::setCacheGeneral($cache); Piwik_Common::initCorePiwikInTrackerMode(); Piwik_SetOption('lastTrackerCronRun', $cache['lastTrackerCronRun']); printDebug('-> Scheduled Tasks: Starting...'); // save current user privilege and temporarily assume super user privilege $isSuperUser = Piwik::isUserIsSuperUser(); // Scheduled tasks assume Super User is running Piwik::setUserIsSuperUser(); // While each plugins should ensure that necessary languages are loaded, // we ensure English translations at least are loaded Piwik_Translate::getInstance()->loadEnglishTranslation(); $resultTasks = Piwik_TaskScheduler::runTasks(); // restore original user privilege Piwik::setUserIsSuperUser($isSuperUser); printDebug($resultTasks); printDebug('Finished Scheduled Tasks.'); } else { printDebug("-> Scheduled tasks not triggered."); } printDebug("Next run will be from: " . date('Y-m-d H:i:s', $nextRunTime) . ' UTC'); }
/** * Saves the layout as default */ public function saveLayoutAsDefault() { $this->checkTokenInUrl(); if (Piwik::isUserIsSuperUser()) { $layout = Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('layout')); $paramsBind = array('', '1', $layout, $layout); Piwik_Query('INSERT INTO ' . Piwik_Common::prefixTable('user_dashboard') . ' (login, iddashboard, layout) VALUES (?,?,?) ON DUPLICATE KEY UPDATE layout=?', $paramsBind); } }
/** * 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; }
/** * Update an existing website. * If only one URL is specified then only the main url will be updated. * If several URLs are specified, both the main URL and the alias URLs will be updated. * * @param int website ID defining the website to edit * @param string website name * @param string|array the website URLs * @param string Comma separated list of IPs to exclude from being tracked (allows wildcards) * @param string Timezone * @param string Currency code * @param string Group name where this website belongs * @param string Date at which the statistics for this website will start. Defaults to today's date in YYYY-MM-DD format * * @exception if any of the parameter is not correct * * @return bool true on success */ public function updateSite( $idSite, $siteName, $urls = null, $ecommerce = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null) { Piwik::checkUserHasAdminAccess($idSite); $idSites = Piwik_SitesManager_API::getInstance()->getSitesId(); if(!in_array($idSite, $idSites)) { throw new Exception("website id = $idSite not found"); } $this->checkName($siteName); // SQL fields to update $bind = array(); if(!is_null($urls)) { $urls = $this->cleanParameterUrls($urls); $this->checkUrls($urls); $this->checkAtLeastOneUrl($urls); $url = $urls[0]; $bind['main_url'] = $url; } if(!is_null($currency)) { $currency = trim($currency); $this->checkValidCurrency($currency); $bind['currency'] = $currency; } if(!is_null($timezone)) { $timezone = trim($timezone); $this->checkValidTimezone($timezone); $bind['timezone'] = $timezone; } if(!is_null($group) && Piwik::isUserIsSuperUser()) { $bind['group'] = trim($group); } if(!is_null($ecommerce)) { $bind['ecommerce'] = (int)(bool)$ecommerce; } if(!is_null($startDate)) { $bind['ts_created'] = Piwik_Date::factory($startDate)->getDatetime(); } $bind['excluded_ips'] = $this->checkAndReturnExcludedIps($excludedIps); $bind['excluded_parameters'] = $this->checkAndReturnExcludedQueryParameters($excludedQueryParameters); $bind['name'] = $siteName; $db = Zend_Registry::get('db'); $db->update(Piwik_Common::prefixTable("site"), $bind, "idsite = $idSite" ); // we now update the main + alias URLs $this->deleteSiteAliasUrls($idSite); if(count($urls) > 1) { $insertedUrls = $this->addSiteAliasUrls($idSite, array_slice($urls,1)); } $this->postUpdateWebsite($idSite); }
/** * Returns the list of reports matching the passed parameters * * @param int $idSite If specified, will filter reports that belong to a specific idsite * @param string $period If specified, will filter reports that are scheduled for this period (day,week,month) * @param int $idReport If specified, will filter the report that has the given idReport * @return array * @throws Exception if $idReport was specified but the report wasn't found */ public function getReports($idSite = false, $period = false, $idReport = false, $ifSuperUserReturnOnlySuperUserReports = false) { Piwik::checkUserIsNotAnonymous(); $cacheKey = (int) $idSite . '.' . (string) $period . '.' . (int) $idReport . '.' . (int) $ifSuperUserReturnOnlySuperUserReports; if (isset(self::$cache[$cacheKey])) { return self::$cache[$cacheKey]; } $sqlWhere = ''; $bind = array(); // Super user gets all reports back, other users only their own if (!Piwik::isUserIsSuperUser() || $ifSuperUserReturnOnlySuperUserReports) { $sqlWhere .= "AND login = ?"; $bind[] = Piwik::getCurrentUserLogin(); } if (!empty($period)) { $this->validateReportPeriod($period); $sqlWhere .= " AND period = ? "; $bind[] = $period; } if (!empty($idSite)) { Piwik::checkUserHasViewAccess($idSite); $sqlWhere .= " AND " . Piwik_Common::prefixTable('site') . ".idsite = ?"; $bind[] = $idSite; } if (!empty($idReport)) { $sqlWhere .= " AND idreport = ?"; $bind[] = $idReport; } // Joining with the site table to work around pre-1.3 where reports could still be linked to a deleted site $reports = Piwik_FetchAll("SELECT * \n\t\t\t\t\t\t\t\tFROM " . Piwik_Common::prefixTable('report') . "\n\t\t\t\t\t\t\t\t\tJOIN " . Piwik_Common::prefixTable('site') . "\n\t\t\t\t\t\t\t\t\tUSING (idsite)\n\t\t\t\t\t\t\t\tWHERE deleted = 0\n\t\t\t\t\t\t\t\t\t{$sqlWhere}", $bind); // When a specific report was requested and not found, throw an error if ($idReport !== false && empty($reports)) { throw new Exception("Requested report couldn't be found."); } foreach ($reports as &$report) { // decode report parameters $report['parameters'] = Piwik_Common::json_decode($report['parameters'], true); // decode report list $report['reports'] = Piwik_Common::json_decode($report['reports'], true); } // static cache self::$cache[$cacheKey] = $reports; return $reports; }
protected static function isRequestAuthorizedToArchive() { return !self::$forceDisableArchiving && (self::isBrowserTriggerArchivingEnabled() || Piwik_Common::isPhpCliMode() || Piwik::isUserIsSuperUser() && Piwik_Common::isArchivePhpTriggered()); }