function runGeoLookup()
{
    global $GEOIP_REGION_NAME;
    $geoip = Net_GeoIP::getInstance(BT_ROOT . "/bt-config/GeoLiteCity.dat");
    $location = null;
    try {
        $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']);
    } catch (Exception $e) {
        //ignore it, seriously dude, friggin ignore it.
    }
    if ($location) {
        $country = DB::quote($location->countryCode);
        $country_full = DB::quote($location->countryName);
        $state = DB::quote($location->region);
        $state_full = @DB::quote($GEOIP_REGION_NAME[strtoupper($location->countryCode)][strtoupper($location->region)]);
        $city = DB::quote($location->city);
        $timezone = @DB::quote(get_time_zone($location->countryCode, $location->region));
        $postalcode = DB::quote($location->postalCode);
    } else {
        return 0;
    }
    $sql = "select location_id from bt_g_geo_locations where country='{$country}' and state='{$state}' and city='{$city}'";
    $id = DB::getVar($sql);
    if (!$id) {
        $sql = "insert into bt_g_geo_locations values ('','{$country}','{$country_full}','{$state}','{$state_full}','{$city}','{$timezone}','{$postalcode}')";
        DB::query($sql);
        $id = DB::insertId();
    }
    return $id;
}
Beispiel #2
0
 /**
  * Get GeoIP object instance
  *
  * @param null|string $filename true: auto; no .dat
  * @param null|string $method null: auto
  * @param boolean $reinit force re-initialization
  * @return Net_GeoIP
  */
 public function getGeoInstance($filename = null, $method = null, $reinit = false)
 {
     if ($this->_geoInstance && !$reinit) {
         return $this->_geoInstance;
     }
     $geoDir = Mage::getBaseDir('var') . '/geoip/';
     if (is_null($filename)) {
         $files = @glob($geoDir . '*.dat');
         if (sizeof($files) != 1) {
             Mage::throwException($this->__('There should be exactly 1 GeoIP dat file in var/geoip (GeoIP.dat, GeoIPCity.dat or GeoLiteCity.dat'));
         }
         $file = $files[0];
         $filename = str_replace(array($geoDir, '.dat'), '', $file);
     } else {
         $file = $geoDir . $filename . '.dat';
     }
     if (is_null($method)) {
         if (empty($this->_methods[$filename])) {
             Mage::throwException($this->__('Unknown method for file %s, and is not specified explicitly', $filename));
         }
         $method = $this->_methods[$filename];
     }
     $this->_geoLookupMethod = $method;
     $this->_geoInstance = Net_GeoIP::getInstance($file, Net_GeoIP::MEMORY_CACHE);
     $this->_geoLocation = null;
     return $this->_geoInstance;
 }
Beispiel #3
0
 public function testBug17262()
 {
     $path = dirname(dirname(__FILE__)) . '/data/GeoLiteCity.dat';
     if (!file_exists($path)) {
         $this->markTestSkipped("Could not find GeoLiteCity.dat in " . $path . "\nObtain from http://www.maxmind.com/app/geolitecity");
     }
     $geoip = Net_GeoIP::getInstance($path);
     $location = $geoip->lookupLocation('24.24.24.24');
     $this->assertSame(array('countryCode' => 'US', 'countryCode3' => 'USA', 'countryName' => 'United States', 'region' => 'NY', 'city' => 'Jamaica', 'postalCode' => '11434', 'latitude' => 40.6763, 'longitude' => -73.7752, 'areaCode' => 718, 'dmaCode' => 501.0), $location->getData());
 }
 /**
  * Get location record.
  *
  * @return array|false Location data or FALSE on failure
  */
 public function getLocation()
 {
     try {
         $location = $this->geoLiteCity->lookupLocation($this->ip);
         if ($location instanceof Net_GeoIP_Location) {
             return $location->getData();
         }
     } catch (Exception $exception) {
         return false;
     }
     return false;
 }
 /**
  * Find
  *
  * @param string $ipAddr The IP Address for which to find the location.
  * @return mixed Array of location data or null if no location found.
  * @access public
  */
 public function find($ipAddr)
 {
     $GeoIp = Net_GeoIP::getInstance(dirname(dirname(__FILE__)) . DS . 'data' . DS . 'GeoIP.dat');
     try {
         $location = $GeoIp->lookupLocation($ipAddr);
         if (!empty($location)) {
             $this->data = array($this->name => array('country_code' => $location->countryCode, 'country_code_3' => $location->countryCode3, 'country_name' => $location->countryName, 'region' => $location->region, 'city' => $location->city, 'postal_code' => $location->postalCode, 'latitude' => $location->latitude, 'longitude' => $location->longitude, 'area_code' => $location->areaCode, 'dma_code' => $location->dmaCode));
         }
     } catch (Exception $e) {
         return null;
     }
     return $this->data;
 }
 /**
  * Lookup an IP address and return a IpLocation_Results object containing 
  * the data found.
  *
  * @param string $ip The ip address to lookup.
  *
  * @return string The location
  */
 public function getIpLocation($ip)
 {
     // Create Net_GeoIP object.
     $geoip = Net_GeoIP::getInstance(dirname(__FILE__) . '/data/' . $this->geoIpDatFile);
     try {
         $country2Char = $geoip->lookupCountryCode($ip);
         $countryName = strtoupper($geoip->lookupCountryName($ip));
     } catch (Exception $e) {
         return false;
     }
     if ($country2Char == '' || $countryName == '') {
         return false;
     }
     return new IpLocation_Results($ip, $country2Char, strtoupper($countryName));
 }
 /**
  * @return array or boolean false
  */
 public function findLocationByIp()
 {
     $ip = $this->findIp();
     if (empty($ip)) {
         return false;
     }
     if (Validation::ip($ip)) {
         App::import('Vendor', 'geoip', ['file' => 'geoip' . DS . 'geoip.php']);
         $gi = Net_GeoIP::getInstance(APP . 'vendors' . DS . 'geoip' . DS . 'GeoLiteCity.dat');
         $record = $gi->lookupLocation($ip);
         $gi->close();
     } else {
         $this->log('Invalid IP \'' . h($ip) . '\'', LOG_WARNING);
     }
     return !empty($record) ? $this->findLocationByCoordinates($record->latitude, $record->longitude, 1) : false;
 }
Beispiel #8
0
/**
 * Convert an IP to a set of latitude and longitude
 *
 *  ip  string          the IP
 *  @return  array   array with latitude and longitude
 */
function googlemap_IpToLocation($ip)
{
    $result = array();
    if (strlen($ip) > 0) {
        $geoip = Net_GeoIP::getInstance(GEOIP_DATABASE);
        $location = $geoip->lookupLocation($ip);
        $result["latitude"] = $location->latitude;
        $result["longitude"] = $location->longitude;
        if (!(strlen($result["latitude"]) > 0)) {
            $result["latitude"] = GEOIP_DEFAULT_LATITUDE;
        }
        if (!(strlen($result["longitude"]) > 0)) {
            $result["longitude"] = GEOIP_DEFAULT_LONGITUDE;
        }
    }
    return $result;
}
function runOrganizationLookup()
{
    $orgip = Net_GeoIP::getInstance(BT_ROOT . "/bt-config/GeoIPOrg.dat");
    $org = '';
    try {
        $org = $orgip->lookupOrg($_SERVER['REMOTE_ADDR']);
    } catch (Exception $e) {
        return 0;
    }
    if (!$org) {
        return 0;
    }
    $org = DB::quote($org);
    $sql = "select org_id from bt_g_organizations where name='{$org}'";
    $id = DB::getVar($sql);
    if (!$id) {
        $sql = "insert into bt_g_organizations values ('','{$org}')";
        DB::query($sql);
        $id = DB::insertId();
    }
    return $id;
}
Beispiel #10
0
    /**
     * Load into Location object all available data
     *
     * @param GeoIp_Location $location
     */
    public function loadLocation(GeoIp_Location $location) {
        require_once "Net/GeoIP.php";
        $flag = Net_GeoIP::STANDARD;
//TODO: on some hostings it failed to work (e.g. mosso.com), so we will disable option of shared memory until it will be solved
//        if (Gpf_Php::isFunctionEnabled('shmop_open')) {
//            $flag = Net_GeoIP::SHARED_MEMORY;
//        }

        $geoip = Net_GeoIP::getInstance($this->file->getFileName(), $flag);
        if ($geoipLocation = @$geoip->lookupLocation($location->getIpString())) {
            $location->setCountryCode($geoipLocation->countryCode);
            $location->setCity($geoipLocation->city);
            $location->setAreaCode($geoipLocation->areaCode);
            $location->setCountryName($geoipLocation->countryName);
            $location->setDmaCode($geoipLocation->dmaCode);
            $location->setLatitude($geoipLocation->latitude);
            $location->setLongitude($geoipLocation->longitude);
            $location->setPostalCode($geoipLocation->postalCode);
            $location->setRegion($geoipLocation->region);
        } else {
            throw new Gpf_Exception($this->_('Ip address %s is not in geoip database.', $location->getIpString()));
        }
    }
Beispiel #11
0
 /**
  * execute
  *
  * Main entry point for class
  *
  * @author Krzysztof Krzyżaniak <*****@*****.**>
  *
  * @return integer: wikia id or null if wikia is not handled by WikiFactory
  */
 public function execute()
 {
     wfProfileIn(__METHOD__);
     global $wgCityId, $wgDevelEnvironment, $wgDBservers, $wgLBFactoryConf, $wgDBserver, $wgContLang;
     /**
      * Hook to allow extensions to alter the initialization.  For example,
      * setting the mCityID then returning true will override which wiki
      * to use.
      *
      * @author Sean Colombo
      */
     if (!wfRunHooks('WikiFactory::execute', array(&$this))) {
         wfProfileOut(__METHOD__);
         return $this->mWikiID;
     }
     /**
      * load balancer uses one method which demand wgContLang defined
      * See BugId: 12474
      */
     $wgContLang = new StubObject('wgContLang');
     /**
      * local cache, change to CACHE_ACCEL for local
      */
     global $wgWikiFactoryCacheType;
     $oMemc = wfGetCache($wgWikiFactoryCacheType);
     if (empty($this->mAlwaysFromDB)) {
         /**
          * remember! for http requests we only known $this->mServerName
          * (domain), $this->mCityId is unknown (set to false in constructor)
          */
         wfProfileIn(__METHOD__ . "-domaincache");
         $key = WikiFactory::getDomainKey($this->mServerName);
         $this->mDomain = $oMemc->get($key);
         $this->mDomain = isset($this->mDomain["id"]) ? $this->mDomain : array();
         $this->debug("reading from cache, key {$key}");
         wfProfileOut(__METHOD__ . "-domaincache");
     }
     if (!isset($this->mDomain["id"]) || $this->mAlwaysFromDB) {
         wfProfileIn(__METHOD__ . "-domaindb");
         /**
          * first run or cache expired
          */
         $dbr = $this->getDB();
         /**
          * interactive/cmdline case. We know city_id so we don't have to
          * ask city_domains table
          */
         if ($this->mCityID || $this->mCityDB) {
             $oRow = $dbr->selectRow(array("city_list"), array("city_id", "city_public", "city_factory_timestamp", "city_url", "city_dbname"), $this->mCityID ? array("city_list.city_id" => $this->mCityID) : array("city_list.city_dbname" => $this->mCityDB), __METHOD__ . '::domaindb');
             if (isset($oRow->city_id)) {
                 preg_match("/http[s]*\\:\\/\\/(.+)\$/", $oRow->city_url, $matches);
                 $host = rtrim($matches[1], "/");
                 $this->mCityID = $oRow->city_id;
                 $this->mWikiID = $oRow->city_id;
                 $this->mIsWikiaActive = $oRow->city_public;
                 $this->mCityHost = $host;
                 $this->mCityDB = $oRow->city_dbname;
                 $this->mTimestamp = $oRow->city_factory_timestamp;
                 $this->mDomain = array("id" => $oRow->city_id, "host" => $host, "active" => $oRow->city_public, "time" => $oRow->city_factory_timestamp, "db" => $this->mCityDB);
             }
         } else {
             /**
              * request from HTTPD case. We only know server name so we
              * have to ask city_domains table
              */
             $oRow = $dbr->selectRow(array("city_domains", "city_list"), array("city_list.city_id", "city_public", "city_factory_timestamp", "city_domain", "city_url", "city_dbname"), array("city_domains.city_id = city_list.city_id", "city_domains.city_domain" => $this->mServerName), __METHOD__ . '::servername');
             if (isset($oRow->city_id) && $oRow->city_id > 0) {
                 $oRow->city_domain = strtolower($oRow->city_domain);
                 preg_match("/http[s]*\\:\\/\\/(.+)\$/", $oRow->city_url, $matches);
                 $host = rtrim($matches[1], "/");
                 if ($oRow->city_domain == $this->mServerName && $this->mServerName) {
                     $this->mWikiID = $oRow->city_id;
                     $this->mIsWikiaActive = $oRow->city_public;
                     $this->mCityHost = $host;
                     $this->mCityDB = $oRow->city_dbname;
                     $this->mTimestamp = $oRow->city_factory_timestamp;
                     $this->mDomain = array("id" => $oRow->city_id, "host" => $host, "active" => $oRow->city_public, "time" => $oRow->city_factory_timestamp, "db" => $oRow->city_dbname);
                 }
             }
         }
         if (empty($this->mAlwaysFromDB) && !empty($this->mWikiID)) {
             /**
              * store value in cache
              */
             $oMemc->set(WikiFactory::getDomainKey($this->mServerName), $this->mDomain, $this->mExpireDomainCacheTimeout);
         }
         $this->debug("city_id={$this->mWikiID}, reading from database key {$this->mServerName}");
         wfProfileOut(__METHOD__ . "-domaindb");
     } else {
         /**
          * data taken from cache
          */
         $this->mWikiID = $this->mDomain["id"];
         $this->mCityHost = $this->mDomain["host"];
         $this->mIsWikiaActive = $this->mDomain["active"];
         $this->mTimestamp = isset($this->mDomain["time"]) ? $this->mDomain["time"] : null;
         $this->mCityDB = isset($this->mDomain["db"]) ? $this->mDomain["db"] : false;
     }
     /**
      * save default var values for Special:WikiFactory
      * @todo this should be smarter...
      */
     if ($this->mWikiID == 177) {
         $this->mSaveDefaults = true;
     }
     /**
      * redirection to another url
      */
     if ($this->mIsWikiaActive == 2) {
         $this->debug("city_id={$this->mWikiID};city_public={$this->mIsWikiaActive}), redirected to {$this->mCityHost}");
         header("X-Redirected-By-WF: 2");
         header("Location: http://{$this->mCityHost}/", true, 301);
         wfProfileOut(__METHOD__);
         exit(0);
     }
     /**
      * if $this->mCityURL different from city_url we redirect to city_url
      * (as main server)
      *
      * mCityHost may contain path after url (memory-alpha, dofus), we just
      * split this for comparing hosts.
      */
     list($host, $path) = array_pad(explode("/", $this->mCityHost, 2), 2, false);
     /**
      * check if domain from browser is different than main domain for wiki
      */
     $cond1 = !empty($host) && !empty($this->mServerName) && strtolower($host) != $this->mServerName;
     /**
      * check if not additional domain was used (then we redirect anyway)
      */
     $cond2 = !empty($host) && $this->mAlternativeDomainUsed && $host != $this->mOldServerName;
     if (($cond1 || $cond2) && empty($wgDevelEnvironment)) {
         $url = wfGetCurrentUrl();
         /**
          * now recombine url from parts
          */
         if (preg_match("!^/{$path}!", $url["path"]) == 0) {
             $url["path"] = "/{$path}" . $url["path"];
         }
         $target = $url["scheme"] . "://" . $host . $url["path"];
         $target = isset($url["query"]) ? $target . "?" . $url["query"] : $target;
         $this->debug("redirected from {$url["url"]} to {$target}");
         header("X-Redirected-By-WF: NotPrimary");
         header("Location: {$target}", true, 301);
         wfProfileOut(__METHOD__);
         exit(0);
     }
     /**
      * if wikia is not defined or is marked for closing we redirect to
      * Not_a_valid_Wikia
      * @todo the -1 status should probably be removed or defined more precisely
      */
     if (empty($this->mWikiID) || $this->mIsWikiaActive == -1) {
         if (!$this->mCommandLine) {
             global $wgNotAValidWikia;
             $this->debug("redirected to {$wgNotAValidWikia}, {$this->mWikiID} {$this->mIsWikiaActive}");
             if ($this->mIsWikiaActive < 0) {
                 header("X-Redirected-By-WF: MarkedForClosing");
             } else {
                 header("X-Redirected-By-WF: NotAValidWikia");
             }
             header("Location: {$wgNotAValidWikia}");
             wfProfileOut(__METHOD__);
             exit(0);
         }
     }
     /**
      * if wikia is disabled and is not Commandline mode we redirect it to
      * dump directory.
      */
     if (empty($this->mIsWikiaActive) || $this->mIsWikiaActive == -2) {
         if (!$this->mCommandLine) {
             global $wgNotAValidWikia;
             if ($this->mCityDB) {
                 $database = strtolower($this->mCityDB);
                 $redirect = sprintf("http://%s/wiki/Special:CloseWiki/information/%s", $wgDevelEnvironment ? "www.awc.wikia-inc.com" : "community.wikia.com", $database);
             } else {
                 $redirect = $wgNotAValidWikia;
             }
             $this->debug("disabled and not commandline, redirected to {$redirect}, {$this->mWikiID} {$this->mIsWikiaActive}");
             header("X-Redirected-By-WF: Dump");
             header("Location: {$redirect}");
             wfProfileOut(__METHOD__);
             exit(0);
         }
     }
     /**
      * for yellowikis.wikia check geolocation and for GB -> redirect to owikis
      * @author Przemek Piotrowski (Nef)
      */
     if (0 === strpos($this->mServerName, 'yellowikis.')) {
         header("X-Redirected-By-WF: Geo");
         global $wgLocationOfGeoIPDatabase;
         if (!empty($wgLocationOfGeoIPDatabase) && file_exists($wgLocationOfGeoIPDatabase)) {
             /**
              * ProxyTools methods cannot be used because PT is not loaded at this point.
              * PT cannot be just included as it requires a lot to be initialized first )-:
              *
              * Order is *important* here! Proxy are added "from the right side"
              * to the combined HTTP_X_FORWARDED_FOR + REMOTE_ADDR.
              */
             $ips = array();
             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                 $ips = preg_split('/\\s*,\\s*/', $_SERVER['HTTP_X_FORWARDED_FOR']);
             }
             if (!empty($_SERVER['REMOTE_ADDR'])) {
                 $ips[] = $_SERVER['REMOTE_ADDR'];
             }
             if (!empty($ips[0])) {
                 require_once 'Net/GeoIP.php';
                 try {
                     $geoip = Net_GeoIP::getInstance($wgLocationOfGeoIPDatabase);
                     if ('GB' == $geoip->lookupCountryCode($ips[0])) {
                         header("X-Redirected-By-WF: Geo");
                         /**
                          * just exit, no redirect at all
                          */
                         wfProfileOut(__METHOD__);
                         exit(0);
                     }
                 } catch (Exception $e) {
                     #--- ignore exception, redirect is an option, not a necessity
                 }
             }
         }
     }
     /**
      * get info about city variables from memcached and then check,
      * maybe memcached is down and returned only error code
      */
     if (empty($this->mAlwaysFromDB)) {
         wfProfileIn(__METHOD__ . "-varscache");
         /**
          * first from serialized file
          */
         $key = WikiFactory::getVarsKey($this->mWikiID);
         $data = $oMemc->get($key);
         if (isset($data["stamp"]) && $data["stamp"] == $this->mTimestamp) {
             $this->mVariables = isset($data["data"]) && is_array($data["data"]) ? $data["data"] : array();
             $this->debug("wikifactory: reading from cache, key {$key}, count " . count($this->mVariables));
         } else {
             $this->debug("wikifactory: timestamp doesn't match. Cache expired");
         }
         wfProfileOut(__METHOD__ . "-varscache");
     }
     /**
      * if wgDBname is not defined we get all variables from database
      */
     if (!isset($this->mVariables["wgDBname"])) {
         wfProfileIn(__METHOD__ . "-varsdb");
         $dbr = $this->getDB();
         $oRes = $dbr->select(array("city_variables", "city_variables_pool"), array("cv_name", "cv_value"), array("cv_id = cv_variable_id", "cv_city_id = {$this->mWikiID}"), __METHOD__ . '::varsdb');
         while ($oRow = $dbr->fetchObject($oRes)) {
             #--- some magic, rewritting path, etc legacy data
             global $_variable_key, $_variable_value;
             set_error_handler("wfUnserializeHandler");
             $_variable_key = $oRow->cv_name;
             $_variable_value = $oRow->cv_value;
             $tUnserVal = unserialize($oRow->cv_value);
             restore_error_handler();
             if (!empty($wgDevelEnvironment) && $oRow->cv_name === "wgServer") {
                 /**
                  * skip this variable
                  */
                 unset($this->mVariables[$oRow->cv_name]);
                 $this->debug("{$oRow->cv_name} with value {$tUnserVal} skipped");
             } else {
                 $this->mVariables[$oRow->cv_name] = $tUnserVal;
             }
         }
         $dbr->freeResult($oRes);
         /**
          * wgArticlePath
          */
         if (!isset($this->mVariables['wgArticlePath'])) {
             $this->mVariables['wgArticlePath'] = $GLOBALS['wgArticlePath'];
         }
         /**
          * read tags for this wiki, store in global variable as array
          * @name $wgWikiFactoryTags
          */
         wfProfileIn(__METHOD__ . "-tagsdb");
         $this->mVariables["wgWikiFactoryTags"] = array();
         $sth = $dbr->select(array("city_tag", "city_tag_map"), array("id", "name"), array("city_tag.id = city_tag_map.tag_id", "city_id = {$this->mWikiID}"), __METHOD__ . '::tagsdb');
         while ($row = $dbr->fetchObject($sth)) {
             $this->mVariables["wgWikiFactoryTags"][$row->id] = $row->name;
         }
         $dbr->freeResult($sth);
         $this->debug("reading tags from database, id {$this->mWikiID}, count " . count($this->mVariables["wgWikiFactoryTags"]));
         wfProfileOut(__METHOD__ . "-tagsdb");
         if (empty($this->mAlwaysFromDB)) {
             /**
              * cache as well some values even if they are not defined in database
              * it will prevent GlobalTitle from doing empty selects
              * BugId: 12463
              */
             foreach ($this->mCacheAnyway as $cvar) {
                 if (!isset($this->mVariables[$cvar]) && isset($GLOBALS[$cvar])) {
                     $this->mVariables[$cvar] = $GLOBALS[$cvar];
                 }
             }
             /**
              * store values in memcache
              */
             $oMemc->set(WikiFactory::getVarsKey($this->mWikiID), array("stamp" => $this->mTimestamp, "data" => $this->mVariables), $this->mExpireValuesCacheTimeout);
         }
         $this->debug("reading from database, id {$this->mWikiID}, count " . count($this->mVariables));
         wfProfileOut(__METHOD__ . "-varsdb");
         /**
          * maybe upgrade database to current schema
          */
         if ($this->mCheckUpgrade === true) {
             $this->maybeUpgrade();
         }
     }
     // @author macbre
     wfRunHooks('WikiFactory::executeBeforeTransferToGlobals', array(&$this));
     /**
      * transfer configuration variables from database to GLOBALS
      */
     if (is_array($this->mVariables)) {
         foreach ($this->mVariables as $key => $value) {
             $tValue = $value;
             #--- check, maybe there are variables in variable
             if (is_string($tValue)) {
                 preg_match_all('/(\\$\\w+)[^\\w]*/', $tValue, $aMatches);
                 if (is_array($aMatches[1])) {
                     foreach ($aMatches[1] as $tKey) {
                         /**
                          * dolar sign in key should be removed
                          * (str_replace is faster than regexp)
                          */
                         $tKeyParsed = str_replace('$', '', $tKey);
                         if (!is_numeric($tKeyParsed)) {
                             #--- replace only if key is not $1, $2 etc.
                             if (array_key_exists($tKeyParsed, $this->mVariables)) {
                                 $tValue = str_replace($tKey, $this->mVariables[$tKeyParsed], $tValue);
                             } else {
                                 if (isset($GLOBALS[$tKeyParsed])) {
                                     $tValue = str_replace($tKey, $GLOBALS[$tKeyParsed], $tValue);
                                 }
                             }
                         }
                     }
                 }
             }
             /**
              * merge local values with global
              */
             switch ($key) {
                 case "wgNamespacesWithSubpagesLocal":
                     $this->LocalToGlobalArray($tValue, $GLOBALS["wgNamespacesWithSubpages"]);
                     break;
                 case "wgExtraNamespacesLocal":
                     $this->LocalToGlobalArray($tValue, $GLOBALS["wgExtraNamespaces"]);
                     break;
                 case "wgFileExtensionsLocal":
                     $this->LocalToGlobalArray($tValue, $GLOBALS["wgFileExtensions"], true);
                     break;
                 case "wgTrustedMediaFormatsLocal":
                     $this->LocalToGlobalArray($tValue, $GLOBALS["wgTrustedMediaFormats"]);
                     break;
                 case "wgFileBlacklistLocal":
                     $this->LocalToGlobalArray($tValue, $GLOBALS["wgFileBlacklist"]);
                     break;
             }
             if ($key == 'wgServer') {
                 $headers = Wikia::getAllHeaders();
                 if (array_key_exists('X-Original-Host', $headers) && !empty($headers['X-Original-Host'])) {
                     global $wgConf;
                     $tValue = 'http://' . $headers['X-Original-Host'];
                     $wgConf->localVHosts = array_merge($wgConf->localVHosts, array($headers['X-Original-Host']));
                 }
             }
             try {
                 if ($this->mSaveDefaults) {
                     $GLOBALS['wgPreWikiFactoryValues'][$key] = $tValue;
                 }
                 $GLOBALS[$key] = $tValue;
             } catch (Exception $e) {
                 #--- so far do nothing
             }
         }
     }
     $wgCityId = $this->mWikiID;
     /**
      * set/replace $wgDBname in $wgDBservers
      */
     if (isset($wgDBservers) && is_array($wgDBservers) && isset($this->mVariables["wgDBname"])) {
         foreach ($wgDBservers as $index => $server) {
             $wgDBservers[$index]["dbname"] = $this->mVariables["wgDBname"];
         }
     }
     if (isset($wgLBFactoryConf) && is_array($wgLBFactoryConf) && isset($this->mVariables["wgDBname"])) {
         $wgLBFactoryConf['serverTemplate']['dbname'] = $this->mVariables["wgDBname"];
         /**
          * set wgDBserver for cluster based on $wgLBFactoryConf
          */
         $cluster = isset($this->mVariables["wgDBcluster"]) ? $this->mVariables["wgDBcluster"] : "DEFAULT";
         if (isset($wgLBFactoryConf["sectionLoads"][$cluster])) {
             $keys = array_keys($wgLBFactoryConf["sectionLoads"][$cluster]);
             $db = array_shift($keys);
             if (isset($wgLBFactoryConf["hostsByName"][$db])) {
                 $wgDBserver = $wgLBFactoryConf["hostsByName"][$db];
                 $this->debug("wgDBserver for cluster {$cluster} set to {$wgDBserver}");
             }
         }
     }
     wfRunHooks('WikiFactory::onExecuteComplete', array(&$this));
     wfProfileOut(__METHOD__);
     /**
      * cleanup and finally return wiki id
      */
     LBFactory::destroyInstance();
     return $this->mWikiID;
 }
 /**
  * The main function recognizes the browser's preferred languages and
  * reloads the page accordingly. Exits if successful.
  *
  * @param string $content HTML content
  * @param array $conf The mandatory configuration array
  * @return string
  */
 public function main($content, $conf)
 {
     $this->conf = $conf;
     $this->cookieLifetime = (int) $conf['cookieLifetime'];
     $this->domainRecord = $this->getCurrentDomainRecord();
     // Break out if domain record is disabled
     if ($this->domainRecord["disable_language_detection"]) {
         return $content;
     }
     // Break out if language already selected
     if (!$this->conf['dontBreakIfLanguageIsAlreadySelected'] && GeneralUtility::_GP($this->conf['languageGPVar']) !== NULL) {
         if (TYPO3_DLOG) {
             GeneralUtility::devLog('Break out since language is already selected', $this->extKey);
         }
         return $content;
     }
     // Break out if the last page visited was also on our site:
     $referrer = (string) GeneralUtility::getIndpEnv('HTTP_REFERER');
     if (TYPO3_DLOG) {
         GeneralUtility::devLog('Referrer: ' . $referrer, $this->extKey);
     }
     if (!$this->conf['dontBreakIfLastPageWasOnSite'] && $referrer !== '' && (stripos($referrer, GeneralUtility::getIndpEnv('TYPO3_SITE_URL')) !== FALSE || stripos($referrer, $this->getTSFE()->baseUrl) !== FALSE || stripos($referrer . '/', GeneralUtility::getIndpEnv('TYPO3_SITE_URL')) !== FALSE || stripos($referrer . '/', $this->getTSFE()->baseUrl) !== FALSE)) {
         return $content;
     }
     // Break out if the session tells us that the user has selected language
     if (!$this->conf['dontBreakIfLanguageIsAlreadySelected']) {
         if ($this->cookieLifetime) {
             // read from browser-cookie
             $languageSessionKey = $_COOKIE[$this->extKey . '_languageSelected'];
         } else {
             $languageSessionKey = $this->getTSFE()->fe_user->getKey('ses', $this->extKey . '_languageSelected');
         }
         // If session key exists but no language GP var -
         // we should redirect client to selected language
         if (isset($languageSessionKey)) {
             // Can redirect only in one tree method for now
             if ($this->conf['useOneTreeMethod'] && is_numeric($languageSessionKey)) {
                 $this->doRedirect($languageSessionKey, $referrer);
                 return '';
             }
             return $content;
         }
     }
     //GATHER DATA
     //Get available languages
     $availableLanguagesArr = $this->conf['useOneTreeMethod'] ? $this->getSysLanguages() : $this->getMultipleTreeLanguages();
     if (TYPO3_DLOG) {
         GeneralUtility::devLog('Detecting available languages in installation', $this->extKey, 0, $availableLanguagesArr);
     }
     //Collect language aliases
     $languageAliases = array();
     if ($this->conf['useLanguageAliases']) {
         $tmp = $conf['languageAliases.'];
         foreach ($tmp as $key => $languageAlias) {
             $languageAliases[strtolower($key)] = GeneralUtility::trimExplode(',', strtolower($languageAlias), TRUE);
         }
     }
     $testOrder = GeneralUtility::trimExplode(',', $conf['testOrder'], TRUE);
     $preferredLanguageOrPageUid = FALSE;
     for ($i = 0; $i < count($testOrder) && $preferredLanguageOrPageUid === FALSE; $i++) {
         switch ($testOrder[$i]) {
             //Browser information
             case 'browser':
                 //Get Accepted Languages from Browser
                 $acceptedLanguagesArr = $this->getAcceptedLanguages();
                 if (TYPO3_DLOG) {
                     GeneralUtility::devLog('Detecting user browser languages', $this->extKey, 0, $acceptedLanguagesArr);
                 }
                 //Break out if the default languange is already selected
                 //Thanks to Stefan Mielke
                 $first = substr(key($acceptedLanguagesArr), 0, 2);
                 if ($first === $this->conf['defaultLang']) {
                     $preferredLanguageOrPageUid = 0;
                     break;
                 }
                 //Iterate through the user's accepted languages
                 for ($j = 0; $j < count($acceptedLanguagesArr); $j++) {
                     $currentLanguage = array_values($acceptedLanguagesArr);
                     $currentLanguage = $currentLanguage[$j];
                     if (TYPO3_DLOG) {
                         GeneralUtility::devLog('Testing language: ' . $currentLanguage, $this->extKey);
                     }
                     //If the current language is available (full "US_en" type check)
                     if (isset($availableLanguagesArr[$currentLanguage])) {
                         $preferredLanguageOrPageUid = $availableLanguagesArr[$currentLanguage];
                         if (TYPO3_DLOG) {
                             GeneralUtility::devLog('Found: ' . $preferredLanguageOrPageUid . ' (full check)', $this->extKey);
                         }
                         break;
                     }
                     //Old-fashioned 2-char test ("en")
                     if (strlen($currentLanguage) > 2 && $preferredLanguageOrPageUid === FALSE) {
                         $currentLanguageShort = substr($currentLanguage, 0, 2);
                         if (isset($availableLanguagesArr[$currentLanguageShort])) {
                             $preferredLanguageOrPageUid = $availableLanguagesArr[$currentLanguageShort];
                             if (TYPO3_DLOG) {
                                 GeneralUtility::devLog('Found: ' . $preferredLanguageOrPageUid . ' (normal check)', $this->extKey);
                             }
                             break;
                         }
                     }
                     //If the user's language is in language aliases
                     if ($this->conf['useLanguageAliases'] && array_key_exists($currentLanguage, $languageAliases) && $preferredLanguageOrPageUid === FALSE) {
                         $values = $languageAliases[$currentLanguage];
                         //Iterate through aliases and choose the first possible
                         foreach ($values as $value) {
                             if (isset($availableLanguagesArr[$value])) {
                                 $preferredLanguageOrPageUid = $availableLanguagesArr[$value];
                                 if (TYPO3_DLOG) {
                                     GeneralUtility::devLog('Found: ' . $preferredLanguageOrPageUid . ' (alias check)', $this->extKey);
                                 }
                                 break 2;
                             }
                         }
                     }
                 }
                 break;
                 //GeoIP
             //GeoIP
             case 'ip':
                 $countryCode = '';
                 if ($this->conf['pearDirectory']) {
                     $pearDirectory = $this->conf['pearDirectory'];
                 } else {
                     $pearDirectory = PEAR_INSTALL_DIR;
                 }
                 if (file_exists($pearDirectory . '/Net/GeoIP.php') && $this->conf['pathToDatabaseForGeoIPData']) {
                     require_once $pearDirectory . '/Net/GeoIP.php';
                     $pathToDatabase = GeneralUtility::getFileAbsFileName($this->conf['pathToDatabaseForGeoIPData']);
                     $geoIp = new \Net_GeoIP($pathToDatabase);
                     // Get country code from geoip
                     if (TYPO3_DLOG) {
                         GeneralUtility::devLog('IP: ' . $this->getUserIP(), $this->extKey);
                     }
                     $countryCode = strtolower($geoIp->lookupCountryCode($this->getUserIP()));
                     if (TYPO3_DLOG) {
                         GeneralUtility::devLog('GeoIP Country Code: ' . $countryCode, $this->extKey);
                     }
                     unset($geoIp);
                 }
                 // PHP module geoip
                 if (!$countryCode && function_exists('geoip_country_code_by_name')) {
                     // Get country code from geoip
                     if (TYPO3_DLOG) {
                         GeneralUtility::devLog('IP: ' . $this->getUserIP(), $this->extKey);
                     }
                     $countryCode = strtolower(geoip_country_code_by_name($this->getUserIP()));
                     if (TYPO3_DLOG) {
                         GeneralUtility::devLog('GeoIP Country Code: ' . $countryCode, $this->extKey);
                     }
                 }
                 if ($countryCode) {
                     //Check for the country code in the configured list of country to languages
                     if (array_key_exists($countryCode, $this->conf['countryCodeToLanguageCode.']) && array_key_exists($this->conf['countryCodeToLanguageCode.'][$countryCode], $availableLanguagesArr)) {
                         if (TYPO3_DLOG) {
                             GeneralUtility::devLog('Available language found in configured: ' . $countryCode, $this->extKey);
                         }
                         $preferredLanguageOrPageUid = $availableLanguagesArr[$this->conf['countryCodeToLanguageCode.'][$countryCode]];
                         //Use the static_info_tables lg_collate_locale to attempt to find a country to language relation.
                     } elseif (ExtensionManagementUtility::isLoaded('static_info_tables')) {
                         if (TYPO3_DLOG) {
                             GeneralUtility::devLog('Checking in static_info_tables.', $this->extKey);
                         }
                         //Get the language codes from lg_collate_locate
                         $values = $this->getLanguageCodesForCountry($countryCode);
                         foreach ($values as $value) {
                             //If one of the languages exist
                             if (array_key_exists($value, $availableLanguagesArr)) {
                                 if (TYPO3_DLOG) {
                                     GeneralUtility::devLog('Found in static_info_tables: ' . $value, $this->extKey);
                                 }
                                 $preferredLanguageOrPageUid = $availableLanguagesArr[$value];
                                 break;
                             }
                         }
                     }
                 }
                 break;
                 //Handle hooks
             //Handle hooks
             default:
                 //Hook for adding other language processing
                 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['rlmp_language_detection']['preferredLanguageHooks'])) {
                     foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['rlmp_language_detection']['preferredLanguageHooks'] as $key => $_funcRef) {
                         if ($key == $testOrder[$i]) {
                             $preferredLanguageOrPageUid = GeneralUtility::callUserFunction($_funcRef, $availableLanguagesArr, $this);
                             if ($preferredLanguageOrPageUid) {
                                 break;
                             }
                         }
                     }
                 }
                 break;
         }
     }
     if (TYPO3_DLOG) {
         GeneralUtility::devLog('END result: Preferred=' . $preferredLanguageOrPageUid, $this->extKey);
     }
     if ($preferredLanguageOrPageUid !== FALSE) {
         $this->doRedirect($preferredLanguageOrPageUid, $referrer);
     }
     return '';
 }
function fn_get_country_by_ip($ip)
{
    if (function_exists('geoip_country_code_by_name')) {
        $code = @geoip_country_code_by_name(long2ip($ip));
        $code = !empty($code) ? $code : '';
    } else {
        $geoip = Net_GeoIP::getInstance(Registry::get('config.dir.lib') . 'pear/data/geoip.dat');
        $code = $geoip->lookupCountryCode(long2ip($ip));
    }
    return $code;
}
Beispiel #14
0
/**
 * Returns location information
 * @param string $ip
 * @return array
 */
function iplookup_find_location($ip)
{
    global $CFG;
    $info = array('city' => null, 'country' => null, 'longitude' => null, 'latitude' => null, 'error' => null, 'note' => '', 'title' => array());
    if (!empty($CFG->geoipfile) and file_exists($CFG->geoipfile)) {
        require_once 'Net/GeoIP.php';
        $geoip = Net_GeoIP::getInstance($CFG->geoipfile, Net_GeoIP::STANDARD);
        $location = $geoip->lookupLocation($ip);
        $geoip->close();
        if (empty($location)) {
            $info['error'] = get_string('iplookupfailed', 'error', $ip);
            return $info;
        }
        if (!empty($location->city)) {
            $info['city'] = textlib::convert($location->city, 'iso-8859-1', 'utf-8');
            $info['title'][] = $info['city'];
        }
        if (!empty($location->country_code)) {
            $countries = get_string_manager()->get_list_of_countries(true);
            if (isset($countries[$location->country_code])) {
                // prefer our localized country names
                $info['country'] = $countries[$location->country_code];
            } else {
                $info['country'] = $location->country_name;
            }
            $info['title'][] = $info['country'];
        }
        $info['longitude'] = $location->longitude;
        $info['latitude'] = $location->latitude;
        $info['note'] = get_string('iplookupmaxmindnote', 'admin');
        return $info;
    } else {
        require_once $CFG->libdir . '/filelib.php';
        $ipdata = download_file_content('http://netgeo.caida.org/perl/netgeo.cgi?target=' . $ip);
        if ($ipdata === false) {
            $info['error'] = get_string('cannotnetgeo', 'error');
            return $info;
        }
        $matches = null;
        if (!preg_match('/LAT:\\s*(-?\\d+\\.\\d+)/s', $ipdata, $matches)) {
            $info['error'] = get_string('iplookupfailed', 'error', $ip);
            return $info;
        }
        $info['latitude'] = (double) $matches[1];
        if (!preg_match('/LONG:\\s*(-?\\d+\\.\\d+)/s', $ipdata, $matches)) {
            $info['error'] = get_string('iplookupfailed', 'error', $ip);
            return $info;
        }
        $info['longitude'] = (double) $matches[1];
        if (preg_match('/CITY:\\s*([^<]*)/', $ipdata, $matches)) {
            if (!empty($matches[1])) {
                $info['city'] = s($matches[1]);
                $info['title'][] = $info['city'];
            }
        }
        if (preg_match('/COUNTRY:\\s*([^<]*)/', $ipdata, $matches)) {
            if (!empty($matches[1])) {
                $countrycode = $matches[1];
                $countries = get_string_manager()->get_list_of_countries(true);
                if (isset($countries[$countrycode])) {
                    // prefer our localized country names
                    $info['country'] = $countries[$countrycode];
                } else {
                    $info['country'] = $countrycode;
                }
                $info['title'][] = $info['country'];
            }
        }
        $info['note'] = get_string('iplookupnetgeonote', 'admin');
        return $info;
    }
}
 /**
  * Fetches the location from the Maxmind local db
  *
  * @param string $ip
  */
 function getLocation($location_map)
 {
     if (!$this->isDbReady()) {
         return $location_map;
     }
     if (!array_key_exists('ip_address', $location_map)) {
         return $location_map;
     }
     // check for shared memory capability
     if (function_exists('shmop_open')) {
         $flag = Net_GeoIP::SHARED_MEMORY;
     } else {
         $flag = Net_GeoIp::STANDARD;
     }
     $geoip = Net_GeoIP::getInstance($this->db_file_path, $flag);
     $location = $geoip->lookupLocation(trim($location_map['ip_address']));
     if ($location) {
         $location_map['city'] = utf8_encode(strtolower(trim($location->__get('city'))));
         $location_map['state'] = utf8_encode(strtolower(trim($location->__get('region'))));
         $location_map['country'] = utf8_encode(strtolower(trim($location->__get('countryName'))));
         $location_map['country_code'] = strtoupper(trim($location->__get('countryCode')));
         $location_map['country_code3'] = strtoupper(trim($location->__get('countryCode3')));
         $location_map['latitude'] = trim($location->__get('latitude'));
         $location_map['longitude'] = trim($location->__get('longitude'));
         $location_map['dma_code'] = trim($location->__get('dmaCode'));
         $location_map['area_code'] = trim($location->__get('areaCode'));
         $location_map['postal_code'] = trim($location->__get('postalCode'));
     }
     return $location_map;
 }
Beispiel #16
0
 /**
  * get location detail using geoip
  */
 public function getGeoIp()
 {
     $enableGeoIp = Mage::getStoreConfig('onestepcheckout/general/enable_geoip');
     $database = Mage::getStoreConfig('onestepcheckout/general/geoip_database');
     try {
         require_once 'Net/GeoIP.php';
         $ipaddress = Mage::helper('core/http')->getRemoteAddr();
         $geoip = Net_GeoIP::getInstance($database);
         $location = $geoip->lookupLocation($ipaddress);
         /**
          * IF PEAR NET_GEOIP IS INSTALLED AND PHP CAN ACCESS THIS THEN YOU WILL SEE YOUR COUNTRY CODE DETECTED IF NOT THEN YOU SEE ERRORS INSTEAD
          */
         if ($enableGeoIp == 1) {
             return $location;
         }
     } catch (Exception $e) {
         return $e->getMessage();
     }
 }
Beispiel #17
0
 /**
  * Create a GeoIP wrapper object
  *
  * @param String $filename the filename of the GeoIP data file (optional)
  * @return GeoIP a new GeoIP wrapper object
  */
 public function __construct($filename = self::DEFAULT_FILENAME)
 {
     load_plugin('Net/GeoIP');
     $this->geoip = Net_GeoIP::getInstance($filename);
 }
Beispiel #18
0
 * actually installed it in).
 * 
 * Based on code from http://pear.php.net/package/Net_GeoIP/ with the PEAR
 * dependencies removed. Adapted by Pete Warden <*****@*****.**>
 * For more details see http://petewarden.typepad.com/
 * 
 * The classes are licensed under the LGPL, but this test script is freely reusable
 * with no restrictions.
 */
require './GeoIP.php';
if (isset($_REQUEST['ip_address'])) {
    $ip_address = urldecode($_REQUEST['ip_address']);
} else {
    $ip_address = $_SERVER['REMOTE_ADDR'];
}
$geoip = Net_GeoIP::getInstance('/usr/local/share/GeoIP/GeoLiteCity.dat');
$location = $geoip->lookupLocation($ip_address);
?>
<html>
<head>
<title>Test page for the GeoIP module</title>
<style>
div {
    padding:20px; 
    width:600px; 
    margin-left: auto; 
    margin-right: auto; 
    border: 1px solid #000; 
    margin-top: 5px; 
}</style>
</head>
Beispiel #19
0
 * TODO: 
 *	- Extend with Bootstrip for pretty URL
 *	- AJAX form submits (jquery form upload)
 * 	- execute nc to enrich with whois data
 *	- textual summaries (for reporting)
 * 	- develop options in formset that are currently disabled
 *
 * Requires PEAR GeoIP & IPv4
 * GeoLiteCity.dat needs to be in path
 *
 */
if (isset($_FILES["datafile"])) {
    $datafile = $_FILES["datafile"]["tmp_name"];
    require_once "Net/GeoIP.php";
    require_once 'Net/IPv4.php';
    $geoip = Net_GeoIP::getInstance("GeoLiteCity.dat");
    $iplist = array();
    $json = "";
    $file_handle = fopen($datafile, "r");
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        if (Net_IPv4::validateIP(trim($line))) {
            array_push($iplist, trim($line));
        }
    }
    fclose($file_handle);
    if (count($iplist) > 0) {
        $json = "{ 'items': " . count($iplist) . ", 'map_width': 0, 'map_length': 0, 'map_title': 'none', 'markers': [ ";
        $first = true;
        foreach ($iplist as $ip) {
            try {
 /**
  * Get GeoIp data by user ip address
  * @param Mage_Sales_Model_Quote $quote
  * @return array
  */
 public function getAddressGeoIP(Mage_Sales_Model_Quote $quote)
 {
     $data = array();
     $ipaddress = $_SERVER['REMOTE_ADDR'];
     $geoip = false;
     $enabled = Mage::getStoreConfig('onestepcheckout/general/enable_geoip', $quote->getStore());
     $database = Mage::getBaseDir('base') . DS . Mage::getStoreConfig('onestepcheckout/general/geoip_database', $quote->getStore());
     if (!$enabled || !file_exists($database) || !$ipaddress) {
         return $data;
     }
     try {
         if (!@(include_once 'Net/GeoIP.php')) {
             Mage::throwException(Mage::helper('onestepcheckout')->__('Net/GeoIP pear package is not installed or inaccessible'));
         } else {
             require_once 'Net/GeoIP.php';
             $geoip = Net_GeoIP::getInstance($database);
         }
     } catch (Exception $e) {
         Mage::logException($e);
     }
     try {
         // city database
         if (is_object($geoip) && method_exists($geoip, 'lookupLocation')) {
             $location = $geoip->lookupLocation($ipaddress);
             $data['country_id'] = $location->countryCode;
             $data['region_id'] = Mage::getModel('directory/region')->loadByCode($location->region, $location->countryCode)->getRegionId();
             $data['city'] = $location->city ? utf8_encode($location->city) : '';
             $data['postcode'] = $location->postalCode ? $location->postalCode : '';
             // country database
         } else {
             if (is_object($geoip) && method_exists($geoip, 'lookupCountryCode')) {
                 $data['country_id'] = $geoip->lookupCountryCode($ipaddress);
                 //no database
             } else {
                 Mage::throwException(Mage::helper('onestepcheckout')->__('Net/GeoIP database %s is not installed properly or is inaccessible', $database));
             }
         }
     } catch (Exception $e) {
         Mage::logException($e);
     }
     return $data;
 }
Beispiel #21
0
/**
 * Called for login tasks, returns an array with success = true if they logged
 * in and their autofinger list
 */
function doLoginTask()
{
    $response = array("message" => "", "success" => false);
    $user = User::login($_POST['username'], $_POST['password']);
    if (!$user) {
        $response['message'] = "Invalid username or password.";
    } else {
        $response['success'] = true;
        $geoip = Net_GeoIP::getInstance(GEO_DATABASE);
        try {
            $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']);
            $user->Location->country = $location->countryCode;
            $user->Location->region = $location->region;
            $user->Location->city = $location->city;
            $user->Location->latitude = $location->latitude;
            $user->Location->longitude = $location->longitude;
            $user->Location->save();
        } catch (Exception $e) {
            // Ignore
        }
        $user->save();
        $response['autofingerList'] = getAutofingerList();
    }
    return $response;
}
Beispiel #22
0
 public function getGeoIp()
 {
     $enableGeoIp = Mage::getStoreConfig('onestepcheckout/general/enable_geoip');
     $database = Mage::getStoreConfig('onestepcheckout/general/geoip_database');
     try {
         require_once 'Net/GeoIP.php';
         $ipaddress = $_SERVER['REMOTE_ADDR'];
         $database = $database;
         $geoip = Net_GeoIP::getInstance($database);
         $location = $geoip->lookupLocation($ipaddress);
         $strCountryCode = $this->settings['default_country_id'];
         $country = Mage::getStoreConfig('onestepcheckout/general/default_country_id');
         /**
          * IF PEAR NET_GEOIP IS INSTALLED AND PHP CAN ACCESS THIS THEN YOU WILL SEE YOUR COUNTRY CODE DETECTED IF NOT THEN YOU SEE ERRORS INSTEAD
          */
         if ($enableGeoIp == 1) {
             //$countrycode = $location->countryCode;
             //$citycode = $location->city;
             return $location;
         }
     } catch (Exception $e) {
         return $e->getMessage();
     }
 }
Beispiel #23
0
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    musxpand is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with musxpand.  If not, see <http://www.gnu.org/licenses/>.

    Copyright � 2010 by Philippe Hilger
 */
/* module Net_GeoIP installed via pecl */
require_once "Net/GeoIP.php";
$geoip = Net_GeoIP::getInstance("/usr/share/GeoIP/GeoIPCity.dat");
function mx_region($location)
{
    global $mxdb;
    $region = '';
    if ($location) {
        $region = $mxdb->getregionname($location->countryCode, $location->region);
    }
    if (!$region) {
        return $location->region;
    }
    return $region;
    //return '-';
}
function mx_locate($address = null)
{
Beispiel #24
0
/**
 * Returns location information
 * @param string $ip
 * @return array
 */
function iplookup_find_location($ip)
{
    global $CFG;
    $info = array('city' => null, 'country' => null, 'longitude' => null, 'latitude' => null, 'error' => null, 'note' => '', 'title' => array());
    if (!empty($CFG->geoipfile) and file_exists($CFG->geoipfile)) {
        require_once 'Net/GeoIP.php';
        $geoip = Net_GeoIP::getInstance($CFG->geoipfile, Net_GeoIP::STANDARD);
        $location = $geoip->lookupLocation($ip);
        $geoip->close();
        if (empty($location)) {
            $info['error'] = get_string('iplookupfailed', 'error', $ip);
            return $info;
        }
        if (!empty($location->city)) {
            $info['city'] = textlib::convert($location->city, 'iso-8859-1', 'utf-8');
            $info['title'][] = $info['city'];
        }
        if (!empty($location->countryCode)) {
            $countries = get_string_manager()->get_list_of_countries(true);
            if (isset($countries[$location->countryCode])) {
                // prefer our localized country names
                $info['country'] = $countries[$location->countryCode];
            } else {
                $info['country'] = $location->countryName;
            }
            $info['title'][] = $info['country'];
        } else {
            if (!empty($location->countryName)) {
                $info['country'] = $location->countryName;
                $info['title'][] = $info['country'];
            }
        }
        $info['longitude'] = $location->longitude;
        $info['latitude'] = $location->latitude;
        $info['note'] = get_string('iplookupmaxmindnote', 'admin');
        return $info;
    } else {
        require_once $CFG->libdir . '/filelib.php';
        $ipdata = download_file_content('http://www.geoplugin.net/json.gp?ip=' . $ip);
        if ($ipdata) {
            $ipdata = preg_replace('/^geoPlugin\\((.*)\\)\\s*$/s', '$1', $ipdata);
            $ipdata = json_decode($ipdata, true);
        }
        if (!is_array($ipdata)) {
            $info['error'] = get_string('cannotgeoplugin', 'error');
            return $info;
        }
        $info['latitude'] = (double) $ipdata['geoplugin_latitude'];
        $info['longitude'] = (double) $ipdata['geoplugin_longitude'];
        $info['city'] = s($ipdata['geoplugin_city']);
        $countrycode = $ipdata['geoplugin_countryCode'];
        $countries = get_string_manager()->get_list_of_countries(true);
        if (isset($countries[$countrycode])) {
            // prefer our localized country names
            $info['country'] = $countries[$countrycode];
        } else {
            $info['country'] = s($ipdata['geoplugin_countryName']);
        }
        $info['note'] = get_string('iplookupgeoplugin', 'admin');
        $info['title'][] = $info['city'];
        $info['title'][] = $info['country'];
        return $info;
    }
}
 /**
  * Tries to guess the user preferred language.
  * 
  * @access public
  * @return string The language guess, or an empty string when the guessing was not possible
  */
 function guessLanguage()
 {
     $guess = '';
     switch (Configure::read('Tradutore.guessingMethod')) {
         case 'http':
             $I18n =& I18n::getInstance();
             $I18n->l10n->get();
             $guess = $I18n->l10n->catalog($I18n->l10n->lang);
             $guess = $guess['localeFallback'];
             break;
         case 'ip':
             App::import('Vendor', 'Tradutore.Net_GeoIP', array('file' => 'geoip' . DS . 'Net' . DS . 'GeoIP.php'));
             $databaseFile = dirname(dirname(dirname(__FILE__))) . DS . 'vendors' . DS . 'geoip' . DS . 'data' . DS . 'GeoIP.dat';
             $geoip = Net_GeoIP::getInstance($databaseFile, Net_GeoIP::STANDARD);
             $country = $geoip->lookupCountryName($this->getClientIP());
             if (isset(self::$_countryLanguage[$country])) {
                 $guess = self::$_countryLanguage[$country];
             } else {
                 $guess = Configure::read('Tradutore.guessingFallback');
             }
             break;
     }
     return $guess;
 }
Beispiel #26
0
/**
* Find the closest location in the list to the destination server
*
* @param mixed $url
*/
function GetClosestLocation($url, $browser)
{
    $location = null;
    $locations = parse_ini_file('./settings/closest.ini', true);
    // filter the locations so only those that match the browser are included
    if (count($locations)) {
        foreach ($locations as $name => &$data) {
            if (strlen($browser)) {
                if (!array_key_exists('browsers', $data) || stripos($data['browsers'], $browser) === false) {
                    unset($locations[$name]);
                }
            } else {
                if (array_key_exists('browsers', $data)) {
                    unset($locations[$name]);
                }
            }
        }
    }
    if (count($locations)) {
        // figure out the IP address of the server
        if (strncasecmp($url, 'http:', 5) && strncasecmp($url, 'https:', 6)) {
            $url = 'http://' . $url;
        }
        $parts = parse_url($url);
        $host = $parts['host'];
        if (strlen($host)) {
            //first see if we have a domain-based match
            $tld = substr($host, strrpos($host, '.'));
            if (strlen($tld)) {
                foreach ($locations as $loc => $pos) {
                    if (array_key_exists('domains', $pos)) {
                        $domains = explode(',', $pos['domains']);
                        foreach ($domains as $d) {
                            if (strcasecmp($tld, ".{$d}") == 0) {
                                $location = $loc;
                                break 2;
                            }
                        }
                    }
                }
            }
            if (!isset($location)) {
                $ip = gethostbyname($host);
                if (is_file('./lib/maxmind/GeoLiteCity.dat')) {
                    try {
                        require_once './lib/maxmind/GeoIP.php';
                        $geoip = Net_GeoIP::getInstance('./lib/maxmind/GeoLiteCity.dat', Net_GeoIP::MEMORY_CACHE);
                        if ($geoip) {
                            $host_location = $geoip->lookupLocation($ip);
                            if ($host_location) {
                                $lat = $host_location->latitude;
                                $lng = $host_location->longitude;
                                // calculate the distance to each location and see which is closest
                                $distance = 0;
                                foreach ($locations as $loc => $pos) {
                                    $r = 6371;
                                    // km
                                    $dLat = deg2rad($pos['lat'] - $lat);
                                    $dLon = deg2rad($pos['lng'] - $lng);
                                    $a = sin($dLat / 2) * sin($dLat / 2) + sin($dLon / 2) * sin($dLon / 2) * cos(deg2rad($lat)) * cos(deg2rad($pos['lat']));
                                    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
                                    $dist = $r * $c;
                                    if (!isset($location) || $dist < $distance) {
                                        $location = $loc;
                                        $distance = $dist;
                                    }
                                }
                            }
                        }
                    } catch (Exception $e) {
                    }
                }
            }
        }
        if (!isset($location)) {
            foreach ($locations as $loc => $pos) {
                $location = $loc;
                break;
            }
        }
    }
    return $location;
}
Beispiel #27
0
    $msg = 'You have been successfully logged out.';
} else {
    if (User::logged_in()) {
        Redirect('home.php');
    } else {
        if (isset($_POST['submit'])) {
            if (isset($_POST['guest'])) {
                Redirect('home.php');
            } else {
                $user = User::login($_POST['username'], $_POST['password']);
                if (!$user) {
                    $msg = 'Invalid username or password.</a>';
                } else {
                    $user->JsStatus->status = $_POST['js_test_value'];
                    try {
                        $geoip = Net_GeoIP::getInstance(GEO_DATABASE);
                        $location = $geoip->lookupLocation($_SERVER['REMOTE_ADDR']);
                        $user->Location->country = $location->countryCode;
                        $user->Location->region = $location->region;
                        $user->Location->city = $location->city;
                        $user->Location->latitude = $location->latitude;
                        $user->Location->longitude = $location->longitude;
                        $user->Location->save();
                    } catch (Exception $e) {
                        // Ignore
                    }
                    $user->save();
                    Redirect('home.php');
                }
            }
        }