/** * Mobile Messaging Settings tab : * - set delegated management * - provide & validate SMS API credential * - add & activate phone numbers * - check remaining credits */ public function index() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@MobileMessaging/index'); $this->setManageVariables($view); return $view->render(); }
public function index() { Piwik::checkUserHasSuperUserAccess(); $limit = Common::getRequestVar('limit', 100, 'int'); // Render the Twig template templates/index.twig and assign the view variable answerToLife to the view. return $this->renderTemplate('index', array('limit' => $limit)); }
public function index() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@TasksTimetable/index.twig'); $this->setGeneralVariablesView($view); $tasks = Option::get('TaskScheduler.timetable'); if (!empty($tasks)) { $tasks = unserialize($tasks); } if (empty($tasks)) { $tasks = array(); } else { asort($tasks); } $tsNow = Date::now()->getTimestamp(); $dateFormat = Piwik::translate(Date::DATE_FORMAT_LONG) . ' h:mm:ss'; $formatter = new Formatter(); $tasksFormatted = array(); foreach ($tasks as $name => $timestamp) { $tasksFormatted[] = array('name' => $name, 'executionDate' => Date::factory($timestamp)->getLocalized($dateFormat), 'ts_difference' => $formatter->getPrettyTimeFromSeconds($timestamp - $tsNow)); } $view->currentTime = Date::now()->getLocalized($dateFormat); $view->tasks = $tasksFormatted; return $view->render(); }
public function configfile() { Piwik::checkUserHasSuperUserAccess(); $allSettings = Settings\Manager::getAllPluginSettings(); $configValues = $this->configReader->getConfigValuesFromFiles(); $configValues = $this->configReader->addConfigValuesFromPluginSettings($configValues, $allSettings); $configValues = $this->sortConfigValues($configValues); return $this->renderTemplate('configfile', array('allConfigValues' => $configValues)); }
public function index() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@IP2Location/index'); $view->language = LanguagesManager::getLanguageCodeForCurrentUser(); $this->setBasicVariablesView($view); $view->adminMenu = MenuAdmin::getInstance()->getMenu(); $view->topMenu = MenuTop::getInstance()->getMenu(); $view->notifications = NotificationManager::getAllNotificationsToDisplay(); $view->userMenu = MenuUser::getInstance()->getMenu(); $view->phpVersion = phpversion(); $view->phpIsNewEnough = version_compare($view->phpVersion, '5.3.0', '>='); $view->assign('userMenu', 'IP2Location'); $view->assign('dbNotFound', false); $view->assign('dbOutDated', false); $view->assign('showResults', false); $view->assign('fileName', '-'); $view->assign('date', '-'); $view->assign('country', ''); $view->assign('regionName', ''); $view->assign('cityName', ''); $view->assign('position', ''); $ipAddress = trim(Common::getRequestVar('ipAddress', $_SERVER['REMOTE_ADDR'])); $view->assign('ipAddress', $ipAddress); $dbPath = PIWIK_INCLUDE_PATH . '/plugins/IP2Location/data/'; $dbFile = ''; if ($handle = opendir($dbPath)) { while (false !== ($file = readdir($handle))) { if (strtoupper(substr($file, -4)) == '.BIN') { $dbFile = $dbPath . $file; break; } } closedir($handle); } if (!$dbFile) { $view->assign('dbNotFound', true); } if ($dbFile) { $view->assign('fileName', $file); if (filemtime($dbFile) < strtotime('-2 months')) { $view->assign('dbOutDated', true); } else { $view->assign('date', date('d M, Y', filemtime($dbFile))); } if (!empty($_POST)) { $view->assign('showResults', true); $result = IP2LocationAPI::lookup($ipAddress, $dbFile); $view->assign('country', $result['countryCode'] != '-' ? $result['countryName'] . ' (' . $result['countryCode'] . ')' : '-'); $view->assign('regionName', !preg_match('/not supported/', $result['regionName']) ? $result['regionName'] : '-'); $view->assign('cityName', !preg_match('/not supported/', $result['cityName']) ? $result['cityName'] : '-'); $view->assign('position', !preg_match('/not supported/', $result['latitude']) && $result['latitude'] != '-' ? $result['latitude'] . ', ' . $result['longitude'] : '-'); } } echo $view->render(); }
public function configfile() { Piwik::checkUserHasSuperUserAccess(); $settings = new SettingsProvider(\Piwik\Plugin\Manager::getInstance()); $allSettings = $settings->getAllSystemSettings(); $configValues = $this->configReader->getConfigValuesFromFiles(); $configValues = $this->configReader->addConfigValuesFromSystemSettings($configValues, $allSettings); $configValues = $this->sortConfigValues($configValues); return $this->renderTemplate('configfile', array('allConfigValues' => $configValues)); }
public function testAllSizes() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@ImageGraph/testAllSizes'); $this->setGeneralVariablesView($view); $period = Common::getRequestVar('period', 'day', 'string'); $date = Common::getRequestVar('date', 'today', 'string'); $_GET['token_auth'] = Piwik::getCurrentUserTokenAuth(); $availableReports = APIPlugins::getInstance()->getReportMetadata($this->idSite, $period, $date); $view->availableReports = $availableReports; $view->graphTypes = array(''); $view->graphSizes = array(array(null, null), array(460, 150), array(300, 150), array(240, 150), array(800, 150), array(600, 300, $fontSize = 18, 300, 150)); return $view->render(); }
/** * Returns the index for this plugin. Shows every other report defined by this plugin, * except the '...ByYear' reports. These can be loaded as related reports. * * Also, the 'getIndividual...Summary' reports are loaded by AJAX, as they can take * a significant amount of time to load on setups w/ lots of websites. */ public function index() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@DBStats/index'); $this->setBasicVariablesView($view); $view->databaseUsageSummary = $this->renderReport(new GetDatabaseUsageSummary()); $view->trackerDataSummary = $this->renderReport(new GetTrackerDataSummary()); $view->metricDataSummary = $this->renderReport(new GetMetricDataSummary()); $view->reportDataSummary = $this->renderReport(new GetReportDataSummary()); $view->adminDataSummary = $this->renderReport(new GetAdminDataSummary()); list($siteCount, $userCount, $totalSpaceUsed) = API::getInstance()->getGeneralInformation(); $view->siteCount = MetricsFormatter::getPrettyNumber($siteCount); $view->userCount = MetricsFormatter::getPrettyNumber($userCount); $view->totalSpaceUsed = MetricsFormatter::getPrettySizeFromBytes($totalSpaceUsed); return $view->render(); }
public function oneClickUpdate() { Piwik::checkUserHasSuperUserAccess(); $view = new OneClickDone(Piwik::getCurrentUserTokenAuth()); $useHttps = Common::getRequestVar('https', 1, 'int'); try { $messages = $this->updater->updatePiwik($useHttps); } catch (ArchiveDownloadException $e) { $view->httpsFail = $useHttps; $view->error = $e->getMessage(); $messages = $e->getUpdateLogMessages(); } catch (UpdaterException $e) { $view->error = $e->getMessage(); $messages = $e->getUpdateLogMessages(); } $view->feedbackMessages = $messages; $this->addCustomLogoInfo($view); return $view->render(); }
/** * Saves the given license key in case the key is actually valid (exists on the Piwik Marketplace and is not * yet expired). * * @param string $licenseKey * @return bool * * @throws Exception In case of an invalid license key * @throws Service\Exception In case of any network problems */ public function saveLicenseKey($licenseKey) { Piwik::checkUserHasSuperUserAccess(); $licenseKey = trim($licenseKey); // we are currently using the Marketplace service directly to 1) change LicenseKey and 2) not use any cache $this->marketplaceService->authenticate($licenseKey); try { $consumer = $this->marketplaceService->fetch('consumer/validate', array()); } catch (Api\Service\Exception $e) { if ($e->getCode() === Api\Service\Exception::HTTP_ERROR) { throw $e; } $consumer = array(); } if (empty($consumer['isValid'])) { throw new Exception(Piwik::translate('Marketplace_ExceptionLinceseKeyIsNotValid')); } $this->setLicenseKey($licenseKey); return true; }
public function adminIndex() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@GeoIpChain/adminIndex'); $providerHandler = new LocationProvider(); $providers = []; foreach ($providerHandler->getProviders() as $provider) { /* @var $provider \Piwik\Plugins\GeoIpChain\Provider\AbstractProvider */ $data = ['name' => $provider->getName(), 'isWorking' => $provider->isWorking(), 'usedFile' => null, 'doesSupportIpV4' => $provider->doesSupportIpV4(), 'doesSupportIpV6' => $provider->doesSupportIpV6(), 'supportFields' => $provider->getSupportedFields()]; if ($provider instanceof LocaleAwareProvider) { $provider->setLocale(\Locale::acceptFromHttp($this->getUsedAcceptLanguage())); } if ($provider instanceof FileAwareProvider) { $data['usedFile'] = $provider->getFile(); } $data['result'] = false; if ($provider->isWorking() === true) { try { /* @var $result \Geocoder\Model\AddressCollection */ $result = $provider->geocode($this->getUsedIp()); /* @var $firstResult \Geocoder\Model\Address */ $firstResult = $result->first(); $data['result'] = $firstResult->toArray(); } catch (NoResult $ex) { } catch (UnsupportedOperation $ex) { } } $providers[] = $data; } $view->usedIp = $this->getUsedIp(); $view->defaultIp = $this->getDefaultIp(); $view->usedAcceptLanguage = $this->getUsedAcceptLanguage(); $view->defaultAcceptLanguage = $this->getDefaultAcceptLanguage(); $view->providers = $providers; $this->setBasicVariablesView($view); $this->setBasicVariablesAdminView($view); return $view->render(); }
public function oneClickUpdate() { Piwik::checkUserHasSuperUserAccess(); $this->newVersion = $this->checkNewVersionIsAvailableOrDie(); SettingsServer::setMaxExecutionTime(0); $url = self::getLatestZipUrl($this->newVersion); $steps = array(array('oneClick_Download', Piwik::translate('CoreUpdater_DownloadingUpdateFromX', $url)), array('oneClick_Unpack', Piwik::translate('CoreUpdater_UnpackingTheUpdate')), array('oneClick_Verify', Piwik::translate('CoreUpdater_VerifyingUnpackedFiles')), array('oneClick_CreateConfigFileBackup', Piwik::translate('CoreUpdater_CreatingBackupOfConfigurationFile', self::CONFIG_FILE_BACKUP))); $incompatiblePlugins = $this->getIncompatiblePlugins($this->newVersion); if (!empty($incompatiblePlugins)) { $namesToDisable = array(); foreach ($incompatiblePlugins as $incompatiblePlugin) { $namesToDisable[] = $incompatiblePlugin->getPluginName(); } $steps[] = array('oneClick_DisableIncompatiblePlugins', Piwik::translate('CoreUpdater_DisablingIncompatiblePlugins', implode(', ', $namesToDisable))); } $steps[] = array('oneClick_Copy', Piwik::translate('CoreUpdater_InstallingTheLatestVersion')); $steps[] = array('oneClick_Finished', Piwik::translate('CoreUpdater_PiwikUpdatedSuccessfully')); $errorMessage = false; $messages = array(); foreach ($steps as $step) { try { $method = $step[0]; $message = $step[1]; $this->{$method}(); $messages[] = $message; } catch (Exception $e) { $errorMessage = $e->getMessage(); break; } } $view = new OneClickDone(Piwik::getCurrentUserTokenAuth()); $view->coreError = $errorMessage; $view->feedbackMessages = $messages; $this->addCustomLogoInfo($view); return $view->render(); }
/** * @return string */ public function admin() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@LoginLdap/index'); ControllerAdmin::setBasicVariablesAdminView($view); if (!function_exists('ldap_connect')) { $notification = new Notification(Piwik::translate('LoginLdap_LdapFunctionsMissing')); $notification->context = Notification::CONTEXT_ERROR; $notification->type = Notification::TYPE_PERSISTENT; Notification\Manager::notify('LoginLdap_LdapFunctionsMissing', $notification); } $this->setBasicVariablesView($view); $serverNames = Config::getServerNameList() ?: array(); $view->servers = array(); if (empty($serverNames)) { try { $serverInfo = ServerInfo::makeFromOldConfig()->getProperties(); $serverInfo['name'] = 'server'; $view->servers[] = $serverInfo; } catch (Exception $ex) { // ignore } } else { foreach ($serverNames as $server) { $serverConfig = Config::getServerConfig($server); if (!empty($serverConfig)) { $serverConfig['name'] = $server; $view->servers[] = $serverConfig; } } } $view->ldapConfig = Config::getPluginOptionValuesWithDefaults(); $view->isLoginControllerActivated = PluginManager::getInstance()->isPluginActivated('Login'); $view->updatedFromPre30 = Option::get('LoginLdap_updatedFromPre3_0'); return $view->render(); }
/** * This controller action renders an admin tab that runs the installation * system check, so people can see if there are any issues w/ their running * Piwik installation. * * This admin tab is only viewable by the Super User. */ public function systemCheckPage() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@Installation/systemCheckPage', $this->getInstallationSteps(), __FUNCTION__); $this->setBasicVariablesView($view); $view->duringInstall = false; $this->setupSystemCheckView($view); $infos = $view->infos; $infos['extra'] = SystemCheck::performAdminPageOnlySystemCheck(); $view->infos = $infos; return $view->render(); }
/** * Will run all scheduled tasks due to run at this time. * * @return array */ public function runScheduledTasks() { Piwik::checkUserHasSuperUserAccess(); return TaskScheduler::runTasks(); }
/** * Records settings for the anonymous users (default report, default date) */ public function recordAnonymousUserSettings() { $response = new ResponseBuilder(Common::getRequestVar('format')); try { Piwik::checkUserHasSuperUserAccess(); $this->checkTokenInUrl(); $anonymousDefaultReport = Common::getRequestVar('anonymousDefaultReport'); $anonymousDefaultDate = Common::getRequestVar('anonymousDefaultDate'); $userLogin = '******'; APIUsersManager::getInstance()->setUserPreference($userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT, $anonymousDefaultReport); APIUsersManager::getInstance()->setUserPreference($userLogin, APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE, $anonymousDefaultDate); $toReturn = $response->getResponse(); } catch (Exception $e) { $toReturn = $response->getResponseException($e); } return $toReturn; }
public function renameGroup($oldGroupName, $newGroupName) { Piwik::checkUserHasSuperUserAccess(); if ($oldGroupName == $newGroupName) { return true; } $sitesHavingOldGroup = $this->getSitesFromGroup($oldGroupName); foreach ($sitesHavingOldGroup as $site) { $this->updateSite($site['idsite'], $siteName = null, $urls = null, $ecommerce = null, $siteSearch = null, $searchKeywordParameters = null, $searchCategoryParameters = null, $excludedIps = null, $excludedQueryParameters = null, $timezone = null, $currency = null, $newGroupName); } return true; }
/** * This controller action renders an admin tab that runs the installation * system check, so people can see if there are any issues w/ their running * Piwik installation. * * This admin tab is only viewable by the Super User. */ public function systemCheckPage() { Piwik::checkUserHasSuperUserAccess(); $view = new View('@Installation/systemCheckPage', $this->getInstallationSteps(), __FUNCTION__); $this->setBasicVariablesView($view); /** @var DiagnosticService $diagnosticService */ $diagnosticService = StaticContainer::get('Piwik\\Plugins\\Diagnostics\\DiagnosticService'); $view->diagnosticReport = $diagnosticService->runDiagnostics(); return $view->render(); }
/** * Specify if normal users can manage their own SMS API credential * * @param bool $delegatedManagement false if SMS API credential only manageable by super admin, true otherwise */ public function setDelegatedManagement($delegatedManagement) { Piwik::checkUserHasSuperUserAccess(); Option::set(MobileMessaging::DELEGATED_MANAGEMENT_OPTION, $delegatedManagement); }
public function uploadCustomLogo() { Piwik::checkUserHasSuperUserAccess(); $logo = new CustomLogo(); $successLogo = $logo->copyUploadedLogoToFilesystem(); $successFavicon = $logo->copyUploadedFaviconToFilesystem(); if ($successLogo || $successFavicon) { return '1'; } return '0'; }
/** * Check that the current user is either the specified user or the superuser. * * @param string $theUser A username. * @throws NoAccessException If the user is neither the Super User nor the user `$theUser`. * @api */ public static function checkUserHasSuperUserAccessOrIsTheUser($theUser) { try { if (Piwik::getCurrentUserLogin() !== $theUser) { // or to the Super User Piwik::checkUserHasSuperUserAccess(); } } catch (NoAccessException $e) { throw new NoAccessException(Piwik::translate('General_ExceptionCheckUserHasSuperUserAccessOrIsTheUser', array($theUser))); } }
use Piwik\Db; use Piwik\FrontController; use Piwik\IP; use Piwik\Log; use Piwik\Piwik; use Piwik\Plugins\UserCountry\LocationProvider\GeoIp\Pecl; use Piwik\Plugins\UserCountry\LocationProvider; use Piwik\Plugins\UserCountry\LocationProvider\GeoIp\Php; require_once './cli-script-bootstrap.php'; ini_set("memory_limit", "512M"); $query = "SELECT count(*) FROM " . Common::prefixTable('log_visit'); $count = Db::fetchOne($query); // when script run via browser, check for Super User & output html page to do conversion via AJAX if (!Common::isPhpCliMode()) { try { Piwik::checkUserHasSuperUserAccess(); } catch (Exception $e) { Log::error('[error] You must be logged in as Super User to run this script. Please login in to Piwik and refresh this page.'); exit; } // the 'start' query param will be supplied by the AJAX requests, so if it's not there, the // user is viewing the page in the browser. if (Common::getRequestVar('start', false) === false) { // output HTML page that runs update via AJAX ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script type="text/javascript" src="../../libs/jquery/jquery.js"></script> <script type="text/javascript"> (function ($) {
/** * Removes all settings for this plugin from the database. Useful when uninstalling * a plugin. */ public function removeAllPluginSettings() { Piwik::checkUserHasSuperUserAccess(); Option::delete($this->getOptionKey()); $this->settingsValues = array(); }
/** * @internal * @return array * @throws \Piwik\NoAccessException */ public function getSystemSettings() { Piwik::checkUserHasSuperUserAccess(); $systemSettings = $this->settingsProvider->getAllSystemSettings(); return $this->settingsMetadata->formatSettings($systemSettings); }
protected function initPluginModification($nonceName) { Piwik::checkUserHasSuperUserAccess(); $nonce = Common::getRequestVar('nonce', null, 'string'); if (!Nonce::verifyNonce($nonceName, $nonce)) { throw new \Exception($this->translator->translate('General_ExceptionNonceMismatch')); } Nonce::discardNonce($nonceName); $pluginName = Common::getRequestVar('pluginName', null, 'string'); return $pluginName; }
/** * Initiates cron archiving via web request. * * @hideExceptForSuperUser */ public function runCronArchiving() { Piwik::checkUserHasSuperUserAccess(); // HTTP request: logs needs to be dumped in the HTTP response (on top of existing log destinations) /** @var \Monolog\Logger $logger */ $logger = StaticContainer::get('Psr\\Log\\LoggerInterface'); $handler = new StreamHandler('php://output', Logger::INFO); $handler->setFormatter(StaticContainer::get('Piwik\\Plugins\\Monolog\\Formatter\\LineMessageFormatter')); $logger->pushHandler($handler); $archiver = new CronArchive(); $archiver->main(); }
/** * Returns a list of all configured log readers that are supported (available). * * @return string[] */ public function getLogConfig() { Piwik::checkUserHasSuperUserAccess(); return Config::getInstance()->log; }
public function activateDoNotTrack() { Piwik::checkUserHasSuperUserAccess(); Nonce::checkNonce(self::ACTIVATE_DNT_NONCE); DoNotTrackHeaderChecker::activate(); $this->redirectToIndex('PrivacyManager', 'privacySettings'); }
/** * Set the location provider * * @param string $providerId The ID of the provider to use eg 'default', 'geoip_php', ... * @throws Exception if ID is invalid */ public function setLocationProvider($providerId) { Piwik::checkUserHasSuperUserAccess(); if (!UserCountry::isGeoLocationAdminEnabled()) { throw new \Exception('Setting geo location has been disabled in config.'); } $provider = LocationProvider::setCurrentProvider($providerId); if ($provider === false) { throw new Exception("Invalid provider ID: '{$providerId}'."); } }
/** * Removes all settings for this plugin from the database. Useful when uninstalling * a plugin. */ public function removeAllPluginSettings() { Piwik::checkUserHasSuperUserAccess(); $this->storage->deleteAllValues(); SettingsStorage::clearCache(); }