/** * Check for a newer version * * @param bool $force Force check * @param int $interval Interval used for update checks */ public static function check($force = false, $interval = null) { if (!self::isAutoUpdateEnabled()) { return; } if ($interval === null) { $interval = self::CHECK_INTERVAL; } $lastTimeChecked = Option::get(self::LAST_TIME_CHECKED); if ($force || $lastTimeChecked === false || time() - $interval > $lastTimeChecked) { // set the time checked first, so that parallel Piwik requests don't all trigger the http requests Option::set(self::LAST_TIME_CHECKED, time(), $autoLoad = 1); $parameters = array('piwik_version' => Version::VERSION, 'php_version' => PHP_VERSION, 'url' => Url::getCurrentUrlWithoutQueryString(), 'trigger' => Common::getRequestVar('module', '', 'string'), 'timezone' => API::getInstance()->getDefaultTimezone()); $url = Config::getInstance()->General['api_service_url'] . '/1.0/getLatestVersion/' . '?' . http_build_query($parameters, '', '&'); $timeout = self::SOCKET_TIMEOUT; if (@Config::getInstance()->Debug['allow_upgrades_to_beta']) { $url = 'http://builds.piwik.org/LATEST_BETA'; } try { $latestVersion = Http::sendHttpRequest($url, $timeout); if (!preg_match('~^[0-9][0-9a-zA-Z_.-]*$~D', $latestVersion)) { $latestVersion = ''; } } catch (Exception $e) { // e.g., disable_functions = fsockopen; allow_url_open = Off $latestVersion = ''; } Option::set(self::LATEST_VERSION, $latestVersion); } }
public function test_getUrlToCheckForLatestAvailableVersion() { $version = Version::VERSION; $phpVersion = urlencode(PHP_VERSION); $url = urlencode(Url::getCurrentUrlWithoutQueryString()); $urlToCheck = $this->channel->getUrlToCheckForLatestAvailableVersion(); $this->assertStringStartsWith("http://api.piwik.org/1.0/getLatestVersion/?piwik_version={$version}&php_version={$phpVersion}&release_channel=my_channel&url={$url}&trigger=&timezone=", $urlToCheck); }
/** * @group Core */ public function testAllMethods() { $this->assertEquals(Url::getCurrentQueryStringWithParametersModified(array()), Url::getCurrentQueryString()); $this->assertEquals(Url::getCurrentUrl(), Url::getCurrentUrlWithoutQueryString()); $this->assertEquals(Url::getCurrentUrl(), Url::getCurrentScheme() . '://' . Url::getCurrentHost() . Url::getCurrentScriptName()); $_SERVER['QUERY_STRING'] = 'q=test'; $parameters = array_keys(Url::getArrayFromCurrentQueryString()); $parametersNameToValue = array(); foreach ($parameters as $name) { $parametersNameToValue[$name] = null; } $this->assertEquals('', Url::getCurrentQueryStringWithParametersModified($parametersNameToValue)); }
private function isPageSpeedEnabled() { $url = Url::getCurrentUrlWithoutQueryString() . '?module=Installation&action=getEmptyPageForSystemCheck'; try { $page = Http::sendHttpRequest($url, $timeout = 1, $userAgent = null, $destinationPath = null, $followDepth = 0, $acceptLanguage = false, $byteRange = false, $getExtendedInfo = true); } catch (\Exception $e) { $this->logger->info('Unable to test if mod_pagespeed is enabled: the request to {url} failed', array('url' => $url)); // If the test failed, we assume Page speed is not enabled return false; } $headers = $page['headers']; return isset($headers['X-Mod-Pagespeed']) || isset($headers['X-Page-Speed']); }
/** * Authenticate user and password. Redirect if successful. * * @param string $login user name * @param string $password md5 password * @param bool $rememberMe Remember me? * @param string $urlToRedirect URL to redirect to, if successfully authenticated * @return string failure message if unable to authenticate */ protected function authenticateAndRedirect($login, $password, $rememberMe, $urlToRedirect = false, $passwordHashed = false) { Nonce::discardNonce('Login.login'); $this->auth->setLogin($login); if ($passwordHashed === false) { $this->auth->setPassword($password); } else { $this->auth->setPasswordHash($password); } $this->sessionInitializer->initSession($this->auth, $rememberMe); // remove password reset entry if it exists $this->passwordResetter->removePasswordResetInfo($login); if (empty($urlToRedirect)) { $urlToRedirect = Url::getCurrentUrlWithoutQueryString(); } Url::redirectToUrl($urlToRedirect); }
/** * @param $email * @param $newsletterPiwikORG * @param $newsletterPiwikPRO */ protected function registerNewsletter($email, $newsletterPiwikORG, $newsletterPiwikPRO) { $url = Config::getInstance()->General['api_service_url']; $url .= '/1.0/subscribeNewsletter/'; $params = array('email' => $email, 'piwikorg' => $newsletterPiwikORG, 'piwikpro' => $newsletterPiwikPRO, 'url' => Url::getCurrentUrlWithoutQueryString()); if ($params['piwikorg'] == '1' || $params['piwikpro'] == '1') { if (!isset($params['piwikorg'])) { $params['piwikorg'] = '0'; } if (!isset($params['piwikpro'])) { $params['piwikpro'] = '0'; } $url .= '?' . http_build_query($params, '', '&'); try { Http::sendHttpRequest($url, $timeout = 2); } catch (Exception $e) { // e.g., disable_functions = fsockopen; allow_url_open = Off } } }
/** * Checks if the current host is valid and sets variables on the given view, including: * * - **isValidHost** - true if host is valid, false if otherwise * - **invalidHostMessage** - message to display if host is invalid (only set if host is invalid) * - **invalidHost** - the invalid hostname (only set if host is invalid) * - **mailLinkStart** - the open tag of a link to email the Super User of this problem (only set * if host is invalid) * * @param View $view * @api */ public static function setHostValidationVariablesView($view) { // check if host is valid $view->isValidHost = Url::isValidHost(); if (!$view->isValidHost) { // invalid host, so display warning to user $validHosts = Url::getTrustedHostsFromConfig(); $validHost = $validHosts[0]; $invalidHost = Common::sanitizeInputValue($_SERVER['HTTP_HOST']); $emailSubject = rawurlencode(Piwik::translate('CoreHome_InjectedHostEmailSubject', $invalidHost)); $emailBody = rawurlencode(Piwik::translate('CoreHome_InjectedHostEmailBody')); $superUserEmail = implode(',', Piwik::getAllSuperUserAccessEmailAddresses()); $mailToUrl = "mailto:{$superUserEmail}?subject={$emailSubject}&body={$emailBody}"; $mailLinkStart = "<a href=\"{$mailToUrl}\">"; $invalidUrl = Url::getCurrentUrlWithoutQueryString($checkIfTrusted = false); $validUrl = Url::getCurrentScheme() . '://' . $validHost . Url::getCurrentScriptName(); $invalidUrl = Common::sanitizeInputValue($invalidUrl); $validUrl = Common::sanitizeInputValue($validUrl); $changeTrustedHostsUrl = "index.php" . Url::getCurrentQueryStringWithParametersModified(array('module' => 'CoreAdminHome', 'action' => 'generalSettings')) . "#trustedHostsSection"; $warningStart = Piwik::translate('CoreHome_InjectedHostWarningIntro', array('<strong>' . $invalidUrl . '</strong>', '<strong>' . $validUrl . '</strong>')) . ' <br/>'; if (Piwik::hasUserSuperUserAccess()) { $view->invalidHostMessage = $warningStart . ' ' . Piwik::translate('CoreHome_InjectedHostSuperUserWarning', array("<a href=\"{$changeTrustedHostsUrl}\">", $invalidHost, '</a>', "<br/><a href=\"{$validUrl}\">", $validHost, '</a>')); } else { if (Piwik::isUserIsAnonymous()) { $view->invalidHostMessage = $warningStart . ' ' . Piwik::translate('CoreHome_InjectedHostNonSuperUserWarning', array("<br/><a href=\"{$validUrl}\">", '</a>', '<span style="display:none">', '</span>')); } else { $view->invalidHostMessage = $warningStart . ' ' . Piwik::translate('CoreHome_InjectedHostNonSuperUserWarning', array("<br/><a href=\"{$validUrl}\">", '</a>', $mailLinkStart, '</a>')); } } $view->invalidHostMessageHowToFix = '<p><b>How do I fix this problem and how do I login again?</b><br/> The Piwik Super User can manually edit the file piwik/config/config.ini.php and add the following lines: <pre>[General]' . "\n" . 'trusted_hosts[] = "' . $invalidHost . '"</pre>After making the change, you will be able to login again.</p> <p>You may also <i>disable this security feature (not recommended)</i>. To do so edit config/config.ini.php and add: <pre>[General]' . "\n" . 'enable_trusted_host_check=0</pre>'; $view->invalidHost = $invalidHost; // for UserSettings warning $view->invalidHostMailLinkStart = $mailLinkStart; } }
/** * @group Core * @dataProvider urlWithoutQueryStringProvider */ public function testGetCurrentUrlWithoutQueryString($url, $expected, $pathInfo = null) { $this->resetGlobalVariables(); $this->setGlobalVariablesFromUrl($url, $pathInfo); $this->assertEquals($expected, Url::getCurrentUrlWithoutQueryString()); }
/** * Action to generate a new Google Authenticator secret for the current user * * @return string * @throws \Exception * @throws \Piwik\NoAccessException */ public function regenerate() { Piwik::checkUserIsNotAnonymous(); $view = new View('@GoogleAuthenticator/regenerate'); $this->setGeneralVariablesView($view); $googleAuth = new PHPGangsta\GoogleAuthenticator(); $storage = new Storage(Piwik::getCurrentUserLogin()); $secret = Common::getRequestVar('gasecret', '', 'string'); $authCode = Common::getRequestVar('gaauthcode', '', 'string'); $authCodeNonce = Common::getRequestVar('authCodeNonce', '', 'string'); $title = Common::getRequestVar('gatitle', $storage->getTitle(), 'string'); $description = Common::getRequestVar('gadescription', $storage->getDescription(), 'string'); if (!empty($secret) && !empty($authCode) && Nonce::verifyNonce(self::AUTH_CODE_NONCE, $authCodeNonce) && $googleAuth->verifyCode($secret, $authCode, 2)) { $storage->setSecret($secret); $storage->setDescription($description); $storage->setTitle($title); $this->auth->setAuthCode($authCode); $this->auth->validateAuthCode(); Url::redirectToUrl(Url::getCurrentUrlWithoutQueryString() . Url::getCurrentQueryStringWithParametersModified(array('action' => 'settings', 'activate' => '1'))); } if (empty($secret)) { $secret = $googleAuth->createSecret(32); } $view->title = $title; $view->description = $description; $view->authCodeNonce = Nonce::getNonce(self::AUTH_CODE_NONCE); $view->newSecret = $secret; $view->googleAuthImage = $googleAuth->getQRCodeGoogleUrl($description, $secret, $title); return $view->render(); }
/** * Sends email confirmation link for a password reset request. * * @param array $user User info for the requested password reset. */ private function sendEmailConfirmationLink($user) { $login = $user['login']; $email = $user['email']; // construct a password reset token from user information $resetToken = self::generatePasswordResetToken($user); $ip = IP::getIpFromHeader(); $url = Url::getCurrentUrlWithoutQueryString() . "?module=Login&action=confirmResetPassword&login="******"&resetToken=" . urlencode($resetToken); // send email with new password $mail = new Mail(); $mail->addTo($email, $login); $mail->setSubject(Piwik::translate('Login_MailTopicPasswordChange')); $bodyText = str_replace('\\n', "\n", sprintf(Piwik::translate('Login_MailPasswordChangeBody'), $login, $ip, $url)) . "\n"; $mail->setBodyText($bodyText); $fromEmailName = Config::getInstance()->General['login_password_recovery_email_name']; $fromEmailAddress = Config::getInstance()->General['login_password_recovery_email_address']; $mail->setFrom($fromEmailAddress, $fromEmailName); $replytoEmailName = Config::getInstance()->General['login_password_recovery_replyto_email_name']; $replytoEmailAddress = Config::getInstance()->General['login_password_recovery_replyto_email_address']; $mail->setReplyTo($replytoEmailAddress, $replytoEmailName); @$mail->send(); }
/** * Installation Step 6: General Set-up (superuser login/password/email and subscriptions) */ function generalSetup() { $this->checkPreviousStepIsValid(__FUNCTION__); $view = new View('@Installation/generalSetup', $this->getInstallationSteps(), __FUNCTION__); $this->skipThisStep(__FUNCTION__); $form = new FormGeneralSetup(); if ($form->validate()) { $superUserInfos = array('login' => $form->getSubmitValue('login'), 'password' => md5($form->getSubmitValue('password')), 'email' => $form->getSubmitValue('email'), 'salt' => Common::generateUniqId()); $this->session->superuser_infos = $superUserInfos; $url = Config::getInstance()->General['api_service_url']; $url .= '/1.0/subscribeNewsletter/'; $params = array('email' => $form->getSubmitValue('email'), 'security' => $form->getSubmitValue('subscribe_newsletter_security'), 'community' => $form->getSubmitValue('subscribe_newsletter_community'), 'url' => Url::getCurrentUrlWithoutQueryString()); if ($params['security'] == '1' || $params['community'] == '1') { if (!isset($params['security'])) { $params['security'] = '0'; } if (!isset($params['community'])) { $params['community'] = '0'; } $url .= '?' . http_build_query($params, '', '&'); try { Http::sendHttpRequest($url, $timeout = 2); } catch (Exception $e) { // e.g., disable_functions = fsockopen; allow_url_open = Off } } $this->redirectToNextStep(__FUNCTION__); } $view->addForm($form); return $view->render(); }
public function getUrlToCheckForLatestAvailableVersion() { $parameters = array('piwik_version' => Version::VERSION, 'php_version' => PHP_VERSION, 'release_channel' => $this->getId(), 'url' => Url::getCurrentUrlWithoutQueryString(), 'trigger' => Common::getRequestVar('module', '', 'string'), 'timezone' => API::getInstance()->getDefaultTimezone()); $url = Config::getInstance()->General['api_service_url'] . '/1.0/getLatestVersion/' . '?' . http_build_query($parameters, '', '&'); return $url; }