Used to check for the latest Piwik version and download updates.
 public function testWebArchiving()
 {
     if (self::isMysqli() && self::isTravisCI()) {
         $this->markTestSkipped('Skipping on Mysqli as it randomly fails.');
     }
     $host = Fixture::getRootUrl();
     $token = Fixture::getTokenAuth();
     $urlTmp = Option::get('piwikUrl');
     Option::set('piwikUrl', $host . 'tests/PHPUnit/proxy/index.php');
     $url = $host . 'tests/PHPUnit/proxy/archive.php?token_auth=' . $token;
     $output = Http::sendHttpRequest($url, 600);
     // ignore random build issues
     if (empty($output) || strpos($output, \Piwik\CronArchive::NO_ERROR) === false) {
         $message = "This test has failed. Because it sometimes randomly fails, we skip the test, and ignore this failure.\n";
         $message .= "If you see this message often, or in every build, please investigate as this should only be a random and rare occurence!\n";
         $message .= "\n\narchive web failed: " . $output . "\n\nurl used: {$url}";
         $this->markTestSkipped($message);
     }
     if (!empty($urlTmp)) {
         Option::set('piwikUrl', $urlTmp);
     } else {
         Option::delete('piwikUrl');
     }
     $this->assertContains('Starting Piwik reports archiving...', $output);
     $this->assertContains('Archived website id = 1', $output);
     $this->assertContains('Done archiving!', $output);
     $this->compareArchivePhpOutputAgainstExpected($output);
 }
Exemple #2
0
 public function triggerWebtreesAdminTasks()
 {
     $settings = new Settings();
     $this->logger = \Piwik\Container\StaticContainer::get('Psr\\Log\\LoggerInterface');
     $this->logger->info('Webtrees Admin Task triggered');
     $rooturl = $settings->getSetting('webtreesRootUrl');
     if (!$rooturl || strlen($rooturl->getValue()) === 0) {
         return;
     }
     $token = $settings->getSetting('webtreesToken');
     if (!$token || strlen($token->getValue()) === 0) {
         return;
     }
     $taskname = $settings->getSetting('webtreesTaskName');
     if (!$taskname || strlen($taskname->getValue()) === 0) {
         return;
     }
     $url = sprintf('%1$s/module.php?mod=perso_admintasks&mod_action=trigger&force=%2$s&task=%3$s', $rooturl->getValue(), $token->getValue(), $taskname->getValue());
     $this->logger->info('webtrees url : {url}', array('url' => $url));
     try {
         \Piwik\Http::sendHttpRequest($url, Webtrees::SOCKET_TIMEOUT);
     } catch (Exception $e) {
         $this->logger->warning('an error occured', array('exception' => $e));
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $buildNumber = $input->getArgument('buildnumber');
     $screenshotsRegex = $input->getArgument('screenshotsRegex');
     if (empty($buildNumber)) {
         throw new \InvalidArgumentException('Missing build number.');
     }
     $urlBase = sprintf('http://builds-artifacts.piwik.org/ui-tests.master/%s', $buildNumber);
     $diffviewer = Http::sendHttpRequest($urlBase . "/screenshot-diffs/diffviewer.html", $timeout = 60);
     $diffviewer = str_replace('&', '&', $diffviewer);
     $dom = new \DOMDocument();
     $dom->loadHTML($diffviewer);
     foreach ($dom->getElementsByTagName("tr") as $row) {
         $columns = $row->getElementsByTagName("td");
         $nameColumn = $columns->item(0);
         $processedColumn = $columns->item(3);
         $testPlugin = null;
         if ($nameColumn && preg_match("/\\(for ([a-zA-Z_]+) plugin\\)/", $dom->saveXml($nameColumn), $matches)) {
             $testPlugin = $matches[1];
         }
         $file = null;
         if ($processedColumn && preg_match("/href=\".*\\/(.*)\"/", $dom->saveXml($processedColumn), $matches)) {
             $file = $matches[1];
         }
         if ($file !== null && preg_match("/" . $screenshotsRegex . "/", $file)) {
             if ($testPlugin == null) {
                 $downloadTo = "tests/PHPUnit/UI/expected-ui-screenshots/{$file}";
             } else {
                 $downloadTo = "plugins/{$testPlugin}/tests/UI/expected-ui-screenshots/{$file}";
             }
             $output->write("<info>Downloading {$file} to .{$downloadTo}...</info>\n");
             Http::sendHttpRequest("{$urlBase}/processed-ui-screenshots/{$file}", $timeout = 60, $userAgent = null, PIWIK_DOCUMENT_ROOT . "/" . $downloadTo);
         }
     }
 }
 /**
  * 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);
     }
 }
Exemple #5
0
 public function get()
 {
     try {
         $content = Http::fetchRemoteFile($this->url);
         $rss = simplexml_load_string($content);
     } catch (\Exception $e) {
         echo "Error while importing feed: {$e->getMessage()}\n";
         exit;
     }
     $output = '<div style="padding:10px 15px;"><ul class="rss">';
     $i = 0;
     $items = array();
     if (!empty($rss->channel->item)) {
         $items = $rss->channel->item;
     }
     foreach ($items as $post) {
         $title = $post->title;
         $date = @strftime("%B %e, %Y", strtotime($post->pubDate));
         $link = $post->link;
         $output .= '<li><a class="rss-title" title="" target="_blank" href="?module=Proxy&action=redirect&url=' . $link . '">' . $title . '</a>' . '<span class="rss-date">' . $date . '</span>';
         if ($this->showDescription) {
             $output .= '<div class="rss-description">' . $post->description . '</div>';
         }
         if ($this->showContent) {
             $output .= '<div class="rss-content">' . $post->content . '</div>';
         }
         $output .= '</li>';
         if (++$i == $this->count) {
             break;
         }
     }
     $output .= '</ul></div>';
     return $output;
 }
 /**
  * Web service proxy that retrieves the content at the specified URL
  *
  * @param string $url
  * @return string
  */
 private function getPage($url)
 {
     try {
         return str_replace('&nbsp;', ' ', Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT']));
     } catch (Exception $e) {
         return '';
     }
 }
 public function sendSMS($apiKey, $smsText, $phoneNumber, $from)
 {
     $account = explode(" ", $apiKey);
     $parameters = array('user' => $account[0], 'pass' => $account[1], 'msg' => $smsText);
     $url = self::API_URL . '?' . http_build_query($parameters, '', '&');
     $timeout = self::SOCKET_TIMEOUT;
     $result = Http::sendHttpRequestBy(Http::getTransportMethod(), $url, $timeout, $getExtendedInfo = true);
 }
Exemple #8
0
 private function trackVisits()
 {
     if (!$this->trackInvalidRequests) {
         return;
     }
     $dateTime = $this->dateTime;
     $idSite = $this->idSite;
     API::getInstance()->setSiteSpecificUserAgentExcludeEnabled(true);
     API::getInstance()->setGlobalExcludedUserAgents('globalexcludeduseragent');
     // Trigger empty request
     $trackerUrl = self::getTrackerUrl();
     $response = Http::fetchRemoteFile($trackerUrl);
     self::assertTrue(strpos($response, 'is a free open source web') !== false, 'Piwik empty request response not correct: ' . $response);
     $t = self::getTracker($idSite, $dateTime, $defaultInit = true);
     // test GoogleBot UA visitor
     $t->setUserAgent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
     self::checkResponse($t->doTrackPageView('bot visit, please do not record'));
     // Test IP Exclusion works with or without IP exclusion
     foreach (array(false, true) as $enable) {
         $excludedIp = '154.1.12.34';
         API::getInstance()->updateSite($idSite, 'new site name', $url = array('http://site.com'), $ecommerce = 0, $ss = 1, $ss_kwd = '', $ss_cat = '', $excludedIp . ',1.2.3.4', $excludedQueryParameters = null, $timezone = null, $currency = null, $group = null, $startDate = null, $excludedUserAgents = 'excludeduseragentstring');
         // Enable IP Anonymization
         $t->DEBUG_APPEND_URL = '&forceIpAnonymization=' . (int) $enable;
         // test with excluded User Agent
         $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (excludeduseragentstring)');
         $t->setIp('211.1.2.3');
         self::checkResponse($t->doTrackPageView('visit from excluded User Agent'));
         $t->setUserAgent('Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0 Google (+https://developers.google.com/+/web/snippet/)');
         self::checkResponse($t->doTrackPageView('visit from excluded User Agent'));
         // test w/ global excluded User Agent
         $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729) (globalexcludeduseragent)');
         $t->setIp('211.1.2.3');
         self::checkResponse($t->doTrackPageView('visit from global excluded User Agent'));
         // test with excluded IP
         $t->setUserAgent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)');
         // restore normal user agent
         $t->setIp($excludedIp);
         self::checkResponse($t->doTrackPageView('visit from IP excluded'));
         // test with global list of excluded IPs
         $excludedIpBis = '145.5.3.4';
         API::getInstance()->setGlobalExcludedIps($excludedIpBis);
         $t->setIp($excludedIpBis);
         self::checkResponse($t->doTrackPageView('visit from IP globally excluded'));
     }
     try {
         @$t->setAttributionInfo(array());
         self::fail();
     } catch (Exception $e) {
     }
     try {
         $t->setAttributionInfo(json_encode('test'));
         self::fail();
     } catch (Exception $e) {
     }
     $t->setAttributionInfo(json_encode(array()));
 }
Exemple #9
0
 /**
  * Update the social definitions
  *
  * @see https://github.com/piwik/searchengine-and-social-list
  */
 public function updateSocials()
 {
     $url = 'https://raw.githubusercontent.com/piwik/searchengine-and-social-list/master/Socials.yml';
     $list = Http::sendHttpRequest($url, 30);
     $socials = Social::getInstance()->loadYmlData($list);
     if (count($socials) < 50) {
         return;
     }
     Option::set(Social::OPTION_STORAGE_NAME, base64_encode(serialize($socials)));
 }
Exemple #10
0
 /**
  * Get the latest available version number for the currently active release channel. Eg '2.15.0-b4' or '2.15.0'.
  * Should return a semantic version number in format MAJOR.MINOR.PATCH (http://semver.org/).
  * Returns an empty string in case one cannot connect to the remote server.
  * @return string
  */
 private static function getLatestAvailableVersionNumber()
 {
     $channel = StaticContainer::get('\\Piwik\\Plugin\\ReleaseChannels')->getActiveReleaseChannel();
     $url = $channel->getUrlToCheckForLatestAvailableVersion();
     try {
         $latestVersion = Http::sendHttpRequest($url, self::SOCKET_TIMEOUT);
     } catch (\Exception $e) {
         // e.g., disable_functions = fsockopen; allow_url_open = Off
         $latestVersion = '';
     }
     return $latestVersion;
 }
 private function getAllTlds()
 {
     /** @var array $response */
     $response = \Piwik\Http::sendHttpRequest("http://data.iana.org/TLD/tlds-alpha-by-domain.txt", 30, null, null, null, null, null, true);
     $this->assertEquals("200", $response['status']);
     $tlds = explode("\n", $response['data']);
     foreach ($tlds as $key => $tld) {
         if (strpos($tld, '#') !== false || $tld == "") {
             unset($tlds[$key]);
         }
     }
     return $tlds;
 }
Exemple #12
0
 /**
  * @group Core
  * 
  * @dataProvider getMethodsToTest
  */
 public function testHEADOperation($method)
 {
     if ($method == 'fopen') {
         return;
         // not supported w/ this method
     }
     $result = Http::sendHttpRequestBy($method, 'http://builds.piwik.org/latest.zip', 30, $userAgent = null, $destinationPath = null, $file = null, $followDepth = 0, $acceptLanguage = false, $acceptInvalidSslCertificate = false, $byteRange = false, $getExtendedInfo = true, $httpMethod = 'HEAD');
     $this->assertEquals('', $result['data']);
     $this->assertEquals(200, $result['status']);
     $this->assertTrue(isset($result['headers']['Content-Length']), "Content-Length header not set!");
     $this->assertTrue(is_numeric($result['headers']['Content-Length']), "Content-Length header not numeric!");
     $this->assertEquals('application/zip', $result['headers']['Content-Type']);
 }
 public function fetchPageRank($domain)
 {
     $chwrite = $this->checkHash($this->hashURL($domain));
     $url = "http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=" . $chwrite . "&features=Rank&q=info:" . $domain . "&num=100&filter=0";
     try {
         $response = Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT']);
         preg_match('#Rank_[0-9]:[0-9]:([0-9]+){1,}#si', $response, $p);
         return isset($p[1]) ? $p[1] : null;
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Google PageRank for SEO stats: {message}', array('message' => $e->getMessage()));
         return null;
     }
 }
 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']);
 }
 public function execute()
 {
     $label = $this->translator->translate('Installation_SystemCheckOpenURL');
     $httpMethod = Http::getTransportMethod();
     if ($httpMethod) {
         return array(DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_OK, $httpMethod));
     }
     $canAutoUpdate = Filechecks::canAutoUpdate();
     $comment = $this->translator->translate('Installation_SystemCheckOpenURLHelp');
     if (!$canAutoUpdate) {
         $comment .= '<br/>' . $this->translator->translate('Installation_SystemCheckAutoUpdateHelp');
     }
     return array(DiagnosticResult::singleResult($label, DiagnosticResult::STATUS_WARNING, $comment));
 }
Exemple #16
0
 public function getMetrics($domain)
 {
     try {
         $response = Http::sendHttpRequest(self::URL . urlencode($domain), $timeout = 10, @$_SERVER['HTTP_USER_AGENT']);
         $xml = @simplexml_load_string($response);
         $value = $xml ? (string) $xml->SD->POPULARITY['TEXT'] : null;
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Alexa SEO stats: {message}', array('message' => $e->getMessage()));
         $value = null;
     }
     $logo = \Piwik\Plugins\Referrers\getSearchEngineLogoFromUrl('http://alexa.com');
     $link = self::LINK . urlencode($domain);
     return array(new Metric('alexa', 'SEO_AlexaRank', $value, $logo, $link));
 }
 private function getAllTlds()
 {
     /** @var array $response */
     $response = \Piwik\Http::sendHttpRequest("http://data.iana.org/TLD/tlds-alpha-by-domain.txt", 30, null, null, null, null, null, true);
     $this->assertEquals("200", $response['status']);
     $tlds = explode("\n", $response['data']);
     foreach ($tlds as $key => $tld) {
         if (strpos($tld, '#') !== false || $tld == "") {
             unset($tlds[$key]);
         }
     }
     $minimumTlds = 1200;
     $this->assertGreaterThan($minimumTlds, count($tlds), "expected to download at least {$minimumTlds} domain names");
     return $tlds;
 }
Exemple #18
0
 public function fetchIndexedPagesCount($domain)
 {
     $url = self::SEARCH_URL . urlencode($domain);
     try {
         $response = str_replace('&nbsp;', ' ', Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT']));
         if (preg_match('#([0-9,\\.]+) results#i', $response, $p)) {
             return NumberFormatter::getInstance()->formatNumber((int) str_replace(array(',', '.'), '', $p[1]));
         } else {
             return 0;
         }
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Google search SEO stats: {message}', array('message' => $e->getMessage()));
         return null;
     }
 }
Exemple #19
0
 private function issueApiCall($apiKey, $resource, $additionalParameters = array())
 {
     $accountParameters = array('Key' => $apiKey);
     $parameters = array_merge($accountParameters, $additionalParameters);
     $url = self::BASE_API_URL . $resource . '?' . http_build_query($parameters, '', '&');
     $timeout = self::SOCKET_TIMEOUT;
     try {
         $result = Http::sendHttpRequestBy(Http::getTransportMethod(), $url, $timeout, $userAgent = null, $destinationPath = null, $file = null, $followDepth = 0, $acceptLanguage = false, $acceptInvalidSslCertificate = true);
     } catch (Exception $e) {
         $result = self::ERROR_STRING . " " . $e->getMessage();
     }
     if (strpos($result, self::ERROR_STRING) !== false) {
         throw new APIException('Clockwork API returned the following error message : ' . $result);
     }
     return $result;
 }
Exemple #20
0
 public function getMetrics($domain)
 {
     $url = self::URL . urlencode($domain);
     try {
         $response = str_replace('&nbsp;', ' ', Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT']));
         if (preg_match('#([0-9,\\.]+) results#i', $response, $p)) {
             $pageCount = NumberFormatter::getInstance()->formatNumber((int) str_replace(array(',', '.'), '', $p[1]));
         } else {
             $pageCount = 0;
         }
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Bing SEO stats: {message}', array('message' => $e->getMessage()));
         $pageCount = null;
     }
     $logo = SearchEngine::getInstance()->getLogoFromUrl('http://bing.com');
     return array(new Metric('bing-index', 'SEO_Bing_IndexedPages', $pageCount, $logo, null, null, 'General_Pages'));
 }
Exemple #21
0
 /**
  * Returns backlink statistics including the count of backlinks and count of
  * referrer domains (domains with backlinks).
  *
  * This method issues an HTTP request and waits for it to return.
  *
  * @param string $siteDomain The domain of the website to get stats for.
  * @param int $timeout The number of seconds to wait before aborting
  *                     the HTTP request.
  * @return array An array containing the backlink count and referrer
  *               domain count:
  *               array(
  *                   'backlink_count' => X,
  *                   'referrer_domains_count' => Y
  *               )
  *               If either stat is false, either the API returned an
  *               error, or the IP was blocked for this request.
  */
 public function getBacklinkStats($siteDomain, $timeout = 300)
 {
     $apiUrl = $this->getApiUrl($method = 'GetBacklinkStats', $args = array('items' => '1', 'item0' => $siteDomain));
     $apiResponse = Http::sendHttpRequest($apiUrl, $timeout);
     $result = array('backlink_count' => false, 'referrer_domains_count' => false);
     $apiResponse = Common::json_decode($apiResponse, $assoc = true);
     if (!empty($apiResponse) && !empty($apiResponse['Data'])) {
         $siteSeoStats = reset($apiResponse['Data']);
         if (isset($siteSeoStats['ExtBackLinks']) && $siteSeoStats['ExtBackLinks'] !== -1) {
             $result['backlink_count'] = $siteSeoStats['ExtBackLinks'];
         }
         if (isset($siteSeoStats['RefDomains']) && $siteSeoStats['RefDomains'] !== -1) {
             $result['referrer_domains_count'] = $siteSeoStats['RefDomains'];
         }
     }
     return $result;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $branch = $input->getOption('branch');
     $buildNumber = $input->getArgument('buildnumber');
     $targetDir = PIWIK_INCLUDE_PATH . '/' . dirname($this->targetDir);
     $tmpDir = StaticContainer::get('path.tmp');
     $this->validate($buildNumber, $targetDir, $tmpDir);
     $filename = sprintf('processed.%s.tar.bz2', $buildNumber);
     $urlBase = sprintf('http://builds-artifacts.piwik.org/%s/%s/%s', $branch, $buildNumber, $filename);
     $tests = Http::sendHttpRequest($urlBase, $timeout = 120);
     $tarFile = $tmpDir . $filename;
     file_put_contents($tarFile, $tests);
     $tar = new Tar($tarFile, 'bz2');
     $tar->extract($targetDir);
     $this->writeSuccessMessage($output, array('All processed system test results were copied to <comment>' . $this->targetDir . '</comment>', 'Compare them with the expected test results and commit them if needed.'));
     unlink($tarFile);
 }
Exemple #23
0
 public function getMetrics($domain)
 {
     try {
         $response = Http::sendHttpRequest(self::URL . urlencode($domain), $timeout = 10, @$_SERVER['HTTP_USER_AGENT']);
         preg_match('#DMOZ Sites[^\\(]+\\([0-9]-[0-9]+ of ([0-9]+)\\)#', $response, $p);
         if (!empty($p[1])) {
             $value = NumberFormatter::getInstance()->formatNumber((int) $p[1]);
         } else {
             $value = 0;
         }
         // Add DMOZ only if > 0 entries found
         if ($value == 0) {
             return array();
         }
     } catch (\Exception $e) {
         $this->logger->warning('Error while getting Dmoz SEO stats: {message}', array('message' => $e->getMessage()));
         $value = null;
     }
     $logo = SearchEngine::getInstance()->getLogoFromUrl('http://dmoz.org');
     return array(new Metric('dmoz', 'SEO_Dmoz', $value, $logo));
 }
 public function test_WebArchiving()
 {
     if (self::isMysqli() && self::isTravisCI()) {
         $this->markTestSkipped('Skipping on Mysqli as it randomly fails.');
     }
     $host = Fixture::getRootUrl();
     $token = Fixture::getTokenAuth();
     $urlTmp = Option::get('piwikUrl');
     Option::set('piwikUrl', $host . 'tests/PHPUnit/proxy/index.php');
     $url = $host . 'tests/PHPUnit/proxy/archive.php?token_auth=' . $token;
     $output = Http::sendHttpRequest($url, 600);
     // ignore random build issues
     if (empty($output) || strpos($output, \Piwik\CronArchive::NO_ERROR) === false) {
         $this->fail("archive web failed: " . $output . "\n\nurl used: {$url}");
     }
     if (!empty($urlTmp)) {
         Option::set('piwikUrl', $urlTmp);
     } else {
         Option::delete('piwikUrl');
     }
     $this->assertWebArchivingDone($output);
 }
Exemple #25
0
 private function downloadScreenshot($url, $repository, $screenshot, $httpUser, $httpPassword)
 {
     $downloadTo = $this->getDownloadToPath($repository) . $screenshot;
     $url = 'http://builds-artifacts.piwik.org' . $url;
     $this->logger->debug("Downloading {url} to {destination}", array('url' => $url, 'destination' => $downloadTo));
     Http::sendHttpRequest($url, $timeout = 60, $userAgent = null, $downloadTo, $followDepth = 0, $acceptLanguage = false, $byteRange = false, $getExtendedInfo = true, $httpMethod = 'GET', $httpUser, $httpPassword);
 }
Exemple #26
0
 private function oneClick_Download()
 {
     $pathPiwikZip = PIWIK_USER_PATH . self::PATH_TO_EXTRACT_LATEST_VERSION . 'latest.zip';
     $this->pathPiwikZip = SettingsPiwik::rewriteTmpPathWithInstanceId($pathPiwikZip);
     Filechecks::dieIfDirectoriesNotWritable(array(self::PATH_TO_EXTRACT_LATEST_VERSION));
     // we catch exceptions in the caller (i.e., oneClickUpdate)
     $url = self::getLatestZipUrl($this->newVersion) . '?cb=' . $this->newVersion;
     Http::fetchRemoteFile($url, $this->pathPiwikZip);
 }
 private function fetch($action, $params)
 {
     ksort($params);
     $query = http_build_query($params);
     $cacheId = $this->getCacheKey($action, $query);
     $cache = $this->buildCache();
     $result = $cache->fetch($cacheId);
     if (false === $result) {
         $endpoint = $this->domain . '/api/1.0/';
         $url = sprintf('%s%s?%s', $endpoint, $action, $query);
         $response = Http::sendHttpRequest($url, static::HTTP_REQUEST_TIMEOUT);
         $result = json_decode($response, true);
         if (is_null($result)) {
             $message = sprintf('There was an error reading the response from the Marketplace: %s. Please try again later.', substr($response, 0, 50));
             throw new MarketplaceApiException($message);
         }
         if (!empty($result['error'])) {
             throw new MarketplaceApiException($result['error']);
         }
         $cache->save($cacheId, $result, self::CACHE_TIMEOUT_IN_SECONDS);
     }
     return $result;
 }
 /**
  * Returns true if the Piwik server appears to be working.
  *
  * If the Piwik server is in an error state (eg. some directories are not writable and Piwik displays error message),
  * or if the Piwik server is "offline",
  * this will return false..
  *
  * @param $piwikServerUrl
  * @param bool $acceptInvalidSSLCertificates
  * @throws Exception
  * @return bool
  */
 public static function checkPiwikServerWorking($piwikServerUrl, $acceptInvalidSSLCertificates = false)
 {
     // Now testing if the webserver is running
     try {
         $fetched = Http::sendHttpRequestBy('curl', $piwikServerUrl, $timeout = 45, $userAgent = null, $destinationPath = null, $file = null, $followDepth = 0, $acceptLanguage = false, $acceptInvalidSSLCertificates);
     } catch (Exception $e) {
         $fetched = "ERROR fetching: " . $e->getMessage();
     }
     // this will match when Piwik not installed yet, or favicon not customised
     $expectedStringAlt = 'plugins/CoreHome/images/favicon.ico';
     // this will match when Piwik is installed and favicon has been customised
     $expectedString = 'misc/user/';
     // see checkPiwikIsNotInstalled()
     $expectedStringAlreadyInstalled = 'piwik-is-already-installed';
     $expectedStringNotFound = strpos($fetched, $expectedString) === false && strpos($fetched, $expectedStringAlt) === false && strpos($fetched, $expectedStringAlreadyInstalled) === false;
     $hasError = false !== strpos($fetched, PAGE_TITLE_WHEN_ERROR);
     if ($hasError || $expectedStringNotFound) {
         throw new Exception("\nPiwik should be running at: " . $piwikServerUrl . " but this URL returned an unexpected response: '" . $fetched . "'\n\n");
     }
 }
Exemple #29
0
 /**
  * @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
         }
     }
 }
 public static function isUpdatingOverHttps()
 {
     $openSslEnabled = extension_loaded('openssl');
     $usingMethodSupportingHttps = Http::getTransportMethod() !== 'socket';
     return $openSslEnabled && $usingMethodSupportingHttps;
 }