Inheritance: extends Piwik\Plugins\UserCountry\LocationProvider
Example #1
0
 public function getRegionName()
 {
     $region = $this->getRegionCode();
     if ($region != '' && $region != Visit::UNKNOWN_CODE) {
         return GeoIp::getRegionNameFromCodes($this->details['location_country'], $region);
     }
     return null;
 }
 /**
  * Test that redundant checks work.
  *
  * @group Plugins
  */
 public function testGeoIpUpdaterRedundantChecks()
 {
     GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files';
     LocationProvider::$providers = null;
     // create empty ISP & Org files
     $this->createEmptyISPOrgFiles();
     // run redundant checks
     $updater = new Piwik_UserCountry_GeoIPAutoUpdater_publictest();
     $updater->performRedundantDbChecks();
     // check that files are renamed correctly
     $this->checkBrokenGeoIPState();
     // create empty files again & run checks again
     $this->createEmptyISPOrgFiles();
     $updater->performRedundantDbChecks();
     // check that w/ broken files already there, redundant checks still work correctly
     $this->checkBrokenGeoIPState();
 }
Example #3
0
 private function setLocationProvider($file)
 {
     GeoIp::$dbNames['loc'] = array($file);
     GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files';
     LocationProvider::$providers = null;
     LocationProvider::setCurrentProvider(self::GEOIP_IMPL_TO_TEST);
     if (LocationProvider::getCurrentProviderId() !== self::GEOIP_IMPL_TO_TEST) {
         throw new Exception("Failed to set the current location provider to '" . self::GEOIP_IMPL_TO_TEST . "'.");
     }
     $possibleFiles = GeoIp::$dbNames['loc'];
     if (GeoIp::getPathToGeoIpDatabase($possibleFiles) === false) {
         throw new Exception("The GeoIP location provider cannot find the '{$file}' file! Tests will fail.");
     }
 }
Example #4
0
<?php

/**
 *  Proxy to normal piwik.php, but in testing mode
 *
 *  - Use the tests database to record Tracking data
 *  - Allows to overwrite the Visitor IP, and Server datetime
 *
 */
use Piwik\DataTable\Manager;
use Piwik\Option;
use Piwik\Plugins\UserCountry\LocationProvider\GeoIp;
use Piwik\Site;
use Piwik\Tracker\Cache;
use Piwik\Tracker;
require realpath(dirname(__FILE__)) . "/includes.php";
// Wrapping the request inside ob_start() calls to ensure that the Test
// calling us waits for the full request to process before unblocking
ob_start();
try {
    Piwik_TestingEnvironment::addHooks();
    GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files';
    Tracker::setTestEnvironment();
    Manager::getInstance()->deleteAll();
    Option::clearCache();
    Site::clearCache();
    include PIWIK_INCLUDE_PATH . '/piwik.php';
} catch (Exception $ex) {
    echo "Unexpected error during tracking: " . $ex->getMessage() . "\n" . $ex->getTraceAsString() . "\n";
}
ob_end_flush();
Example #5
0
 /**
  * Returns true if the PECL module that is installed can be successfully used
  * to get the location of an IP address.
  *
  * @return bool
  */
 public function isWorking()
 {
     // if no no location database is available, this implementation is not setup correctly
     if (!self::isLocationDatabaseAvailable()) {
         $dbDir = dirname(geoip_db_filename(GEOIP_COUNTRY_EDITION)) . '/';
         $quotedDir = "'{$dbDir}'";
         // check if the directory the PECL module is looking for exists
         if (!is_dir($dbDir)) {
             return Piwik::translate('UserCountry_PeclGeoIPNoDBDir', array($quotedDir, "'geoip.custom_directory'"));
         }
         // check if the user named the city database GeoLiteCity.dat
         if (file_exists($dbDir . 'GeoLiteCity.dat')) {
             return Piwik::translate('UserCountry_PeclGeoLiteError', array($quotedDir, "'GeoLiteCity.dat'", "'GeoIPCity.dat'"));
         }
         return Piwik::translate('UserCountry_CannotFindPeclGeoIPDb', array($quotedDir, "'GeoIP.dat'", "'GeoIPCity.dat'"));
     }
     return parent::isWorking();
 }
Example #6
0
/**
 * Returns the name of a city + the name of its region + the name of its country using
 * the label of a Visits by City report.
 *
 * @param string $label A label containing a city name, region code + country code,
 *                      separated by two '|' chars: 'Paris|A8|FR'
 * @return string|false eg. 'Paris, Ile de France, France' or false if $label ==
 *                      DataTable::LABEL_SUMMARY_ROW.
 */
function getPrettyCityName($label)
{
    if ($label == DataTable::LABEL_SUMMARY_ROW) {
        return $label;
    }
    if ($label == '') {
        return Piwik::translate('General_Unknown');
    }
    // get city name, region code & country code
    $parts = explode(Archiver::LOCATION_SEPARATOR, $label);
    $cityName = $parts[0];
    $regionCode = $parts[1];
    $countryCode = @$parts[2];
    if ($cityName == Visit::UNKNOWN_CODE || $cityName == '') {
        $cityName = Piwik::translate('General_Unknown');
    }
    $result = $cityName;
    if ($countryCode != Visit::UNKNOWN_CODE && $countryCode != '') {
        if ($regionCode != '' && $regionCode != Visit::UNKNOWN_CODE) {
            $regionName = GeoIp::getRegionNameFromCodes($countryCode, $regionCode);
            $result .= ', ' . $regionName;
        }
        $result .= ', ' . countryTranslate($countryCode);
    }
    return $result;
}
Example #7
0
 /**
  * Returns a GeoIP instance. Creates it if necessary.
  *
  * @param string $key 'loc', 'isp' or 'org'. Determines the type of GeoIP database
  *                    to load.
  * @return object|false
  */
 private function getGeoIpInstance($key)
 {
     if (empty($this->geoIpCache[$key])) {
         // make sure region names are loaded & saved first
         parent::getRegionNames();
         require_once PIWIK_INCLUDE_PATH . '/libs/MaxMindGeoIP/geoipcity.inc';
         $pathToDb = self::getPathToGeoIpDatabase($this->customDbNames[$key]);
         if ($pathToDb !== false) {
             $this->geoIpCache[$key] = geoip_open($pathToDb, GEOIP_STANDARD);
             // TODO support shared memory
         }
     }
     return empty($this->geoIpCache[$key]) ? false : $this->geoIpCache[$key];
 }
 private function isAtLeastOneGeoIpDbOutOfDate($rescheduledTime)
 {
     $previousScheduledRuntime = $this->getPreviousScheduledTime($rescheduledTime)->setTime("00:00:00")->getTimestamp();
     foreach (GeoIp::$dbNames as $type => $dbNames) {
         $dbUrl = Option::get(self::$urlOptions[$type]);
         $dbPath = GeoIp::getPathToGeoIpDatabase($dbNames);
         // if there is a URL for this DB type and the GeoIP DB file's last modified time is before
         // the time the updater should have been previously run, then **the file is out of date**
         if (!empty($dbUrl) && filemtime($dbPath) < $previousScheduledRuntime) {
             return true;
         }
     }
     return false;
 }
 public function tearDown()
 {
     LocationProvider::$providers = null;
     GeoIp::$geoIPDatabaseDir = 'tests/lib/geoip-files';
     ManyVisitsWithGeoIP::unsetLocationProvider();
 }
Example #10
0
 /**
  * Starts or continues a download for a missing GeoIP database. A database is missing if
  * it has an update URL configured, but the actual database is not available in the misc
  * directory.
  *
  * Input:
  *   'url' - The URL to download the database from.
  *   'continue' - 1 if we're continuing a download, 0 if we're starting one.
  *
  * Output:
  *   'error' - If an error occurs this describes the error.
  *   'to_download' - The URL of a missing database that should be downloaded next (if any).
  *   'to_download_label' - The label to use w/ the progress bar that describes what we're
  *                         downloading.
  *   'current_size' - Size of the current file on disk.
  *   'expected_file_size' - Size of the completely downloaded file.
  */
 public function downloadMissingGeoIpDb()
 {
     $this->dieIfGeolocationAdminIsDisabled();
     Piwik::checkUserHasSuperUserAccess();
     if ($_SERVER["REQUEST_METHOD"] == "POST") {
         try {
             $this->checkTokenInUrl();
             Json::sendHeaderJSON();
             // based on the database type (provided by the 'key' query param) determine the
             // url & output file name
             $key = Common::getRequestVar('key', null, 'string');
             $url = GeoIPAutoUpdater::getConfiguredUrl($key);
             $ext = GeoIPAutoUpdater::getGeoIPUrlExtension($url);
             $filename = GeoIp::$dbNames[$key][0] . '.' . $ext;
             if (substr($filename, 0, 15) == 'GeoLiteCity.dat') {
                 $filename = 'GeoIPCity.dat' . substr($filename, 15);
             }
             $outputPath = GeoIp::getPathForGeoIpDatabase($filename);
             // download part of the file
             $result = Http::downloadChunk($url, $outputPath, Common::getRequestVar('continue', true, 'int'));
             // if the file is done
             if ($result['current_size'] >= $result['expected_file_size']) {
                 GeoIPAutoUpdater::unzipDownloadedFile($outputPath, $unlink = true);
                 $info = $this->getNextMissingDbUrlInfo();
                 if ($info !== false) {
                     return json_encode($info);
                 }
             }
             return json_encode($result);
         } catch (Exception $ex) {
             return json_encode(array('error' => $ex->getMessage()));
         }
     }
 }