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); }
protected function setGeneralVariablesView($view) { // date $view->date = $this->strDate; $oDate = new Piwik_Date($this->strDate); $view->prettyDate = $oDate->getLocalized(Piwik_Translate('Home_LocalizedDateFormat')); // period $currentPeriod = Piwik_Common::getRequestVar('period'); $otherPeriodsAvailable = array('day', 'week', 'month', 'year'); $otherPeriodsNames = array('day' => Piwik_Translate('Home_PeriodDay'), 'week' => Piwik_Translate('Home_PeriodWeek'), 'month' => Piwik_Translate('Home_PeriodMonth'), 'year' => Piwik_Translate('Home_PeriodYear')); $found = array_search($currentPeriod, $otherPeriodsAvailable); if ($found !== false) { unset($otherPeriodsAvailable[$found]); } $view->period = $currentPeriod; $view->otherPeriods = $otherPeriodsAvailable; $view->periodsNames = $otherPeriodsNames; // other $view->idSite = Piwik_Common::getRequestVar('idSite'); $view->userLogin = Piwik::getCurrentUserLogin(); $view->sites = Piwik_SitesManager_API::getSitesWithAtLeastViewAccess(); $view->url = Piwik_Url::getCurrentUrl(); $view->menu = Piwik_GetMenu(); $view->menuJson = json_encode($view->menu); //var_dump($view->menuJson); }
/** * Renders the current view. * * @return string Generated template */ public function render() { try { $this->currentModule = Piwik::getModule(); $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); }
function redirectToCoreHomeIndex() { // redirect to Login only for anonymous user if ((bool) Zend_Registry::get('config')->General->default_module_login == true && Piwik::getCurrentUserLogin() == 'anonymous') { return Piwik_FrontController::dispatch('Login', false); } parent::redirectToIndex('CoreHome', 'index'); }
/** * Function called to save the Feedburner ID entered in the form * */ function saveFeedburnerName() { // we save the value in the DB for an authenticated user if (Piwik::getCurrentUserLogin() != 'anonymous') { Piwik_Query('UPDATE ' . Piwik::prefixTable('site') . ' SET feedburnerName = ? WHERE idsite = ?', array(Piwik_Common::getRequestVar('name', '', 'string'), Piwik_Common::getRequestVar('idSite', 1, 'int'))); } }
/** * 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; }
/** * anonymous = in the session * authenticated user = in the session and in DB */ public function saveLanguage() { $language = Piwik_Common::getRequestVar('language'); $currentUser = Piwik::getCurrentUserLogin(); $_SESSION['language'] = $language; if ($currentUser !== 'anonymous') { Piwik_LanguagesManager_API::setLanguageForUser($currentUser, $language); } Piwik_Url::redirectToReferer(); }
/** * anonymous = in the session * authenticated user = in the session and in DB */ public function saveLanguage() { $language = Piwik_Common::getRequestVar('language'); $currentUser = Piwik::getCurrentUserLogin(); $session = new Zend_Session_Namespace("LanguagesManager"); $session->language = $language; if ($currentUser !== 'anonymous') { Piwik_LanguagesManager_API::setLanguageForUser($currentUser, $language); } Piwik_Url::redirectToReferer(); }
/** * anonymous = in the session * authenticated user = in the session and in DB */ public function saveLanguage() { $language = Piwik_Common::getRequestVar('language'); Piwik_LanguagesManager::setLanguageForSession($language); if (Zend_Registry::isRegistered('access')) { $currentUser = Piwik::getCurrentUserLogin(); if ($currentUser && $currentUser !== 'anonymous') { Piwik_LanguagesManager_API::getInstance()->setLanguageForUser($currentUser, $language); } } Piwik_Url::redirectToReferer(); }
function index() { $view = Piwik_View::factory('UsersManager'); $IdSitesAdmin = Piwik_SitesManager_API::getSitesIdWithAdminAccess(); $idSiteSelected = 1; if(count($IdSitesAdmin) > 0) { $defaultWebsiteId = $IdSitesAdmin[0]; $idSiteSelected = Piwik_Common::getRequestVar('idsite', $defaultWebsiteId); } if($idSiteSelected==='all') { $usersAccessByWebsite = array(); } else { $usersAccessByWebsite = Piwik_UsersManager_API::getUsersAccessFromSite( $idSiteSelected ); } // requires super user access $usersLogin = Piwik_UsersManager_API::getUsersLogin(); // we dont want to display the user currently logged so that the user can't change his settings from admin to view... $currentlyLogged = Piwik::getCurrentUserLogin(); foreach($usersLogin as $login) { if(!isset($usersAccessByWebsite[$login])) { $usersAccessByWebsite[$login] = 'noaccess'; } } unset($usersAccessByWebsite[$currentlyLogged]); ksort($usersAccessByWebsite); $users = array(); if(Zend_Registry::get('access')->isSuperUser()) { $users = Piwik_UsersManager_API::getUsers(); } $view->idSiteSelected = $idSiteSelected; $view->users = $users; $view->usersAccessByWebsite = $usersAccessByWebsite; $view->formUrl = Piwik_Url::getCurrentUrl(); $view->websites = Piwik_SitesManager_API::getSitesWithAdminAccess(); $this->setGeneralVariablesView($view); $view->menu = Piwik_GetAdminMenu(); echo $view->render(); }
protected function getDefaultIndexView() { $view = new Piwik_View('AdminHome/templates/index.tpl'); $view->menu = Piwik_GetAdminMenu(); $view->menuJson = json_encode($view->menu); $view->userLogin = Piwik::getCurrentUserLogin(); $view->sites = Piwik_SitesManager_API::getSitesWithAtLeastViewAccess(); $view->url = Piwik_Url::getCurrentUrl(); $view->basicHtmlView = false; $view->content = ''; return $view; }
function redirectToCoreHomeIndex() { $defaultReport = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT); $module = 'CoreHome'; $action = 'index'; // User preference: default report to load is the All Websites dashboard if ($defaultReport == 'MultiSites' && Piwik_PluginsManager::getInstance()->isPluginActivated('MultiSites')) { $module = 'MultiSites'; } if ($defaultReport == Piwik::getLoginPluginName()) { $module = Piwik::getLoginPluginName(); } $idSite = Piwik_Common::getRequestVar('idSite', false, 'int'); parent::redirectToIndex($module, $action, !empty($idSite) ? $idSite : null); }
public function addMenus() { Piwik_AddMenu('Dashboard_Dashboard', '', array('module' => 'Dashboard', 'action' => 'embeddedIndex', 'idDashboard' => 1), true, 5); if (!Piwik::isUserIsAnonymous()) { $login = Piwik::getCurrentUserLogin(); $dashboards = self::getAllDashboards($login); if (count($dashboards) > 1) { $pos = 0; foreach ($dashboards as $dashboard) { Piwik_AddMenu('Dashboard_Dashboard', $dashboard['name'], array('module' => 'Dashboard', 'action' => 'embeddedIndex', 'idDashboard' => $dashboard['iddashboard']), true, $pos); $pos++; } } } }
/** * 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); }
private function getCurrentUserSettings() { return $this->getUserSettings(Piwik::getCurrentUserLogin()); }
/** * Is user the anonymous user? * * @return bool True if anonymouse; false otherwise */ public static function isUserIsAnonymous() { return Piwik::getCurrentUserLogin() == 'anonymous'; }
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; }
/** * Get the dashboard layout for the current user (anonymous or loggued user) * * @return string $layout */ protected function getLayout() { $idDashboard = Piwik_Common::getRequestVar('idDashboard', 1, 'int' ); $currentUser = Piwik::getCurrentUserLogin(); if($currentUser == 'anonymous') { $session = new Zend_Session_Namespace("Piwik_Dashboard"); if(!isset($session->dashboardLayout)) { return false; } $layout = $session->dashboardLayout; } else { $layout = $this->getLayoutForUser($currentUser,$idDashboard); } // layout was JSON.stringified $layout = html_entity_decode($layout); $layout = str_replace("\\\"", "\"", $layout); // compatibility with the old layout format if(!empty($layout) && strstr($layout, '[[') == false) { $layout = "'$layout'"; } $layout = $this->removeDisabledPluginFromLayout($layout); return $layout; }
/** * @return string|false if language preference could not be loaded */ protected static function getLanguageFromPreferences() { if (($language = self::getLanguageForSession()) != null) { return $language; } try { $currentUser = Piwik::getCurrentUserLogin(); return Piwik_LanguagesManager_API::getInstance()->getLanguageForUser($currentUser); } catch (Exception $e) { return false; } }
/** * @param Piwik_Event_Notification $notification notification object */ function sendReport($notification) { if (self::manageEvent($notification)) { $notificationInfo = $notification->getNotificationInfo(); $report = $notificationInfo[Piwik_PDFReports_API::REPORT_KEY]; $websiteName = $notificationInfo[Piwik_PDFReports_API::WEBSITE_NAME_KEY]; $prettyDate = $notificationInfo[Piwik_PDFReports_API::PRETTY_DATE_KEY]; $contents = $notificationInfo[Piwik_PDFReports_API::REPORT_CONTENT_KEY]; $filename = $notificationInfo[Piwik_PDFReports_API::FILENAME_KEY]; $additionalFiles = $notificationInfo[Piwik_PDFReports_API::ADDITIONAL_FILES_KEY]; $periods = self::getPeriodToFrequency(); $message = Piwik_Translate('PDFReports_EmailHello'); $subject = Piwik_Translate('General_Report') . ' ' . $websiteName . " - " . $prettyDate; $mail = new Piwik_Mail(); $mail->setSubject($subject); $fromEmailName = Piwik_Config::getInstance()->branding['use_custom_logo'] ? Piwik_Translate('CoreHome_WebAnalyticsReports') : Piwik_Translate('PDFReports_PiwikReports'); $fromEmailAddress = Piwik_Config::getInstance()->General['noreply_email_address']; $attachmentName = $subject; $mail->setFrom($fromEmailAddress, $fromEmailName); switch ($report['format']) { case 'html': // Needed when using images as attachment with cid $mail->setType(Zend_Mime::MULTIPART_RELATED); $message .= "<br/>" . Piwik_Translate('PDFReports_PleaseFindBelow', array($periods[$report['period']], $websiteName)); $mail->setBodyHtml($message . "<br/><br/>" . $contents); break; default: case 'pdf': $message .= "\n" . Piwik_Translate('PDFReports_PleaseFindAttachedFile', array($periods[$report['period']], $websiteName)); $mail->setBodyText($message); $mail->createAttachment($contents, 'application/pdf', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, $attachmentName . '.pdf'); break; } foreach ($additionalFiles as $additionalFile) { $fileContent = $additionalFile['content']; $at = $mail->createAttachment($fileContent, $additionalFile['mimeType'], Zend_Mime::DISPOSITION_INLINE, $additionalFile['encoding'], $additionalFile['filename']); $at->id = $additionalFile['cid']; unset($fileContent); } // Get user emails and languages $reportParameters = $report['parameters']; $emails = array(); if (isset($reportParameters[self::ADDITIONAL_EMAILS_PARAMETER])) { $emails = $reportParameters[self::ADDITIONAL_EMAILS_PARAMETER]; } if ($reportParameters[self::EMAIL_ME_PARAMETER] == 1) { if (Piwik::getCurrentUserLogin() == $report['login']) { $emails[] = Piwik::getCurrentUserEmail(); } elseif ($report['login'] == Piwik_Config::getInstance()->superuser['login']) { $emails[] = Piwik::getSuperUserEmail(); } else { try { $user = Piwik_UsersManager_API::getInstance()->getUser($report['login']); } catch (Exception $e) { return; } $emails[] = $user['email']; } } foreach ($emails as $email) { if (empty($email)) { continue; } $mail->addTo($email); try { $mail->send(); } catch (Exception $e) { // If running from piwik.php with debug, we ignore the 'email not sent' error if (!isset($GLOBALS['PIWIK_TRACKER_DEBUG']) || !$GLOBALS['PIWIK_TRACKER_DEBUG']) { throw new Exception("An error occured while sending '{$filename}' " . " to " . implode(', ', $mail->getRecipients()) . ". Error was '" . $e->getMessage() . "'"); } } $mail->clearRecipients(); } } }
/** * 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; }
public function sendEmailReport($idReport, $idSite) { $reports = $this->getReports($idSite, $period = false, $idReport); $report = reset($reports); if ($report['period'] == 'never') { $report['period'] = 'day'; } // Get user emails and languages $emails = self::getEmailsFromString($report['additional_emails']); if ($report['email_me'] == 1) { if (Piwik::getCurrentUserLogin() == $report['login']) { $emails[] = Piwik::getCurrentUserEmail(); } elseif ($report['login'] == Zend_Registry::get('config')->superuser->login) { $emails[] = Zend_Registry::get('config')->superuser->email; } else { try { $user = Piwik_UsersManager_API::getInstance()->getUser($report['login']); } catch (Exception $e) { return; } $emails[] = $user['email']; } } $language = Piwik_LanguagesManager_API::getInstance()->getLanguageForUser($report['login']); list($outputFilename, $prettyDate, $websiteName) = $this->generateReport($idReport, Piwik_Date::now()->subPeriod(1, $report['period'])->toString(), $idSite, $language, $outputType = Piwik_PDFReports_API::OUTPUT_PDF_SAVE_ON_DISK); $this->sendReportEmailPdfAttached($emails, $outputFilename, $prettyDate, $websiteName, $report); }
public function sendEmailReport($idReport, $idSite, $period = false, $date = false) { Piwik::checkUserIsNotAnonymous(); $reports = $this->getReports($idSite, false, $idReport); $report = reset($reports); if ($report['period'] == 'never') { $report['period'] = 'day'; } if (!empty($period)) { $report['period'] = $period; } if (empty($date)) { $date = Piwik_Date::now()->subPeriod(1, $report['period'])->toString(); } // Get user emails and languages $emails = self::getEmailsFromString($report['additional_emails']); if ($report['email_me'] == 1) { if (Piwik::getCurrentUserLogin() == $report['login']) { $emails[] = Piwik::getCurrentUserEmail(); } elseif ($report['login'] == Piwik_Config::getInstance()->superuser['login']) { $emails[] = Piwik::getSuperUserEmail(); } else { try { $user = Piwik_UsersManager_API::getInstance()->getUser($report['login']); } catch (Exception $e) { return; } $emails[] = $user['email']; } } $language = Piwik_LanguagesManager_API::getInstance()->getLanguageForUser($report['login']); list($outputFilename, $prettyDate, $websiteName, $reportFormat, $additionalFiles) = $this->generateReport($idReport, $date, $idSite, $language, self::OUTPUT_SAVE_ON_DISK, $report['period']); $this->sendReportEmail($emails, $outputFilename, $prettyDate, $websiteName, $report, $reportFormat, $additionalFiles); }
/** * 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; }
/** * @param string $theUser * @throws exception if the user is neither the super user nor the user $theUser */ public static function checkUserIsSuperUserOrTheUser($theUser) { try { if (Piwik::getCurrentUserLogin() !== $theUser) { // or to the super user Piwik::checkUserIsSuperUser(); } } catch (Piwik_Access_NoAccessException $e) { throw new Piwik_Access_NoAccessException("The user has to be either the Super User or the user '{$theUser}' itself."); } }
/** * Records settings from the "User Settings" page */ public function recordUserSettings() { $response = new Piwik_API_ResponseBuilder(Piwik_Common::getRequestVar('format')); try { $this->checkTokenInUrl(); $alias = Piwik_Common::getRequestVar('alias'); $email = Piwik_Common::getRequestVar('email'); $defaultReport = Piwik_Common::getRequestVar('defaultReport'); $defaultDate = Piwik_Common::getRequestVar('defaultDate'); $newPassword = false; $password = Piwik_Common::getRequestvar('password', false); $passwordBis = Piwik_Common::getRequestvar('passwordBis', false); if(!empty($password) || !empty($passwordBis)) { if($password != $passwordBis) { throw new Exception(Piwik_Translate('Login_PasswordsDoNotMatch')); } $newPassword = $password; } $userLogin = Piwik::getCurrentUserLogin(); if(Piwik::isUserIsSuperUser()) { $superUser = Zend_Registry::get('config')->superuser; $updatedSuperUser = false; if($newPassword !== false) { $newPassword = Piwik_Common::unsanitizeInputValue($newPassword); $md5PasswordSuperUser = md5($newPassword); $superUser->password = $md5PasswordSuperUser; $updatedSuperUser = true; } if($superUser->email != $email) { $superUser->email = $email; $updatedSuperUser = true; } if($updatedSuperUser) { Zend_Registry::get('config')->superuser = $superUser->toArray(); } } else { Piwik_UsersManager_API::getInstance()->updateUser($userLogin, $newPassword, $email, $alias); if($newPassword !== false) { $newPassword = Piwik_Common::unsanitizeInputValue($newPassword); } } // logs the user in with the new password if($newPassword !== false) { $info = array( 'login' => $userLogin, 'md5Password' => md5($newPassword), 'rememberMe' => false, ); Piwik_PostEvent('Login.initSession', $info); } Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT, $defaultReport); Piwik_UsersManager_API::getInstance()->setUserPreference($userLogin, Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE, $defaultDate); $toReturn = $response->getResponse(); } catch(Exception $e ) { $toReturn = $response->getResponseException( $e ); } echo $toReturn; }
/** * Returns default date for Piwik reports * * @return string today, 2010-01-01, etc. */ protected function getDefaultPeriod() { $userSettingsDate = Piwik_UsersManager_API::getInstance()->getUserPreference(Piwik::getCurrentUserLogin(), Piwik_UsersManager_API::PREFERENCE_DEFAULT_REPORT_DATE); if ($userSettingsDate === false) { return Piwik_Config::getInstance()->General['default_period']; } if (in_array($userSettingsDate, array('today', 'yesterday'))) { return 'day'; } if (strpos($userSettingsDate, 'last') === 0 || strpos($userSettingsDate, 'previous') === 0) { return 'range'; } return $userSettingsDate; }
/** * Get the dashboard layout for the current user (anonymous or loggued user) * * @param int $idDashboard * @return string $layout */ protected function getLayout($idDashboard) { if (Piwik::isUserIsAnonymous()) { $session = new Piwik_Session_Namespace("Piwik_Dashboard"); if (!isset($session->dashboardLayout)) { return $this->getDefaultLayout(); } $layout = $session->dashboardLayout; } else { $layout = $this->getLayoutForUser(Piwik::getCurrentUserLogin(), $idDashboard); } if (!empty($layout)) { $layout = $this->removeDisabledPluginFromLayout($layout); } if ($layout === false) { $layout = $this->getDefaultLayout(); } return $layout; }
/** * Get the dashboard layout for the current user (anonymous or loggued user) * * @return string $layout */ protected function getLayout() { $idDashboard = Piwik_Common::getRequestVar('idDashboard', 1, 'int'); $currentUser = Piwik::getCurrentUserLogin(); if ($currentUser == 'anonymous') { $session = new Zend_Session_Namespace("Piwik_Dashboard"); if (!isset($session->idDashboard)) { return false; } return $session->idDashboard; } else { return $this->getLayoutForUser($currentUser, $idDashboard); } }
/** * Returns the list of websites ID associated with a URL. * * @param string $url * @return array list of websites ID */ public function getSitesIdFromSiteUrl( $url ) { $url = $this->removeTrailingSlash($url); list($url, $urlBis) = $this->getNormalizedUrls($url); if(Piwik::isUserIsSuperUser()) { $ids = Zend_Registry::get('db')->fetchAll( 'SELECT idsite FROM ' . Piwik_Common::prefixTable('site') . ' WHERE (main_url = ? OR main_url = ?) ' . 'UNION SELECT idsite FROM ' . Piwik_Common::prefixTable('site_url') . ' WHERE (url = ? OR url = ?) ', array($url, $urlBis, $url, $urlBis)); } else { $login = Piwik::getCurrentUserLogin(); $ids = Zend_Registry::get('db')->fetchAll( 'SELECT idsite FROM ' . Piwik_Common::prefixTable('site') . ' WHERE (main_url = ? OR main_url = ?)' . 'AND idsite IN (' . Piwik_Access::getSqlAccessSite('idsite') . ') ' . 'UNION SELECT idsite FROM ' . Piwik_Common::prefixTable('site_url') . ' WHERE (url = ? OR url = ?)' . 'AND idsite IN (' . Piwik_Access::getSqlAccessSite('idsite') . ')', array($url, $urlBis, $login, $url, $urlBis, $login)); } return $ids; }