php Piwik-IP类(方法)实例源码

下面列出了php Piwik-IP 类(方法)源码代码实例,从而了解它的用法。

作者:KiwiJuice    项目:handball-dacha   
/**
  * Uses a GeoIP database to get a visitor's location based on their IP address.
  *
  * This function will return different results based on the data used and based
  * on how the GeoIP module is configured.
  *
  * If a region database is used, it may return the country code, region code,
  * city name, area code, latitude, longitude and postal code of the visitor.
  *
  * Alternatively, only the country code may be returned for another database.
  *
  * If your HTTP server is not configured to include all GeoIP information, some
  * information will not be available to Piwik.
  *
  * @param array $info Must have an 'ip' field.
  * @return array
  */
 public function getLocation($info)
 {
     $ip = $this->getIpFromInfo($info);
     // geoip modules that are built into servers can't use a forced IP. in this case we try
     // to fallback to another version.
     $myIP = IP::getIpFromHeader();
     if (!self::isSameOrAnonymizedIp($ip, $myIP) && (!isset($info['disable_fallbacks']) || !$info['disable_fallbacks'])) {
         Common::printDebug("The request is for IP address: " . $info['ip'] . " but your IP is: {$myIP}. GeoIP Server Module (apache/nginx) does not support this use case... ");
         $fallbacks = array(Pecl::ID, Php::ID);
         foreach ($fallbacks as $fallbackProviderId) {
             $otherProvider = LocationProvider::getProviderById($fallbackProviderId);
             if ($otherProvider) {
                 Common::printDebug("Used {$fallbackProviderId} to detect this visitor IP");
                 return $otherProvider->getLocation($info);
             }
         }
         Common::printDebug("FAILED to lookup the geo location of this IP address, as no fallback location providers is configured. We recommend to configure Geolocation PECL module to fix this error.");
         return false;
     }
     $result = array();
     foreach (self::$geoIpServerVars as $resultKey => $geoipVarName) {
         if (!empty($_SERVER[$geoipVarName])) {
             $result[$resultKey] = $_SERVER[$geoipVarName];
         }
     }
     foreach (self::$geoIpUtfServerVars as $resultKey => $geoipVarName) {
         if (!empty($_SERVER[$geoipVarName])) {
             $result[$resultKey] = utf8_encode($_SERVER[$geoipVarName]);
         }
     }
     $this->completeLocationResult($result);
     return $result;
 }

作者:KingNoos    项目:Tekni   
function getIp()
 {
     if (isset($this->details['location_ip'])) {
         return IP::N2P($this->details['location_ip']);
     }
     return false;
 }

作者:KiwiJuice    项目:handball-dacha   
public function enrichVisitWithLocation(&$visitorInfo, \Piwik\Tracker\Request $request)
 {
     require_once PIWIK_INCLUDE_PATH . "/plugins/UserCountry/LocationProvider.php";
     $ipAddress = IP::N2P(Config::getInstance()->Tracker['use_anonymized_ip_for_visit_enrichment'] == 1 ? $visitorInfo['location_ip'] : $request->getIp());
     $userInfo = array('lang' => $visitorInfo['location_browser_lang'], 'ip' => $ipAddress);
     $id = Common::getCurrentLocationProviderId();
     $provider = LocationProvider::getProviderById($id);
     if ($provider === false) {
         $id = DefaultProvider::ID;
         $provider = LocationProvider::getProviderById($id);
         Common::printDebug("GEO: no current location provider sent, falling back to default '{$id}' one.");
     }
     $location = $provider->getLocation($userInfo);
     // if we can't find a location, use default provider
     if ($location === false) {
         $defaultId = DefaultProvider::ID;
         $provider = LocationProvider::getProviderById($defaultId);
         $location = $provider->getLocation($userInfo);
         Common::printDebug("GEO: couldn't find a location with Geo Module '{$id}', using Default '{$defaultId}' provider as fallback...");
         $id = $defaultId;
     }
     Common::printDebug("GEO: Found IP {$ipAddress} location (provider '" . $id . "'): " . var_export($location, true));
     if (empty($location['country_code'])) {
         // sanity check
         $location['country_code'] = \Piwik\Tracker\Visit::UNKNOWN_CODE;
     }
     // add optional location components
     $this->updateVisitInfoWithLocation($visitorInfo, $location);
 }

作者:carriercom    项目:piwi   
public function index()
 {
     Piwik::checkUserIsNotAnonymous();
     $view = new View('@MobileMessaging/index');
     $view->isSuperUser = Piwik::hasUserSuperUserAccess();
     $mobileMessagingAPI = API::getInstance();
     $view->delegatedManagement = $mobileMessagingAPI->getDelegatedManagement();
     $view->credentialSupplied = $mobileMessagingAPI->areSMSAPICredentialProvided();
     $view->accountManagedByCurrentUser = $view->isSuperUser || $view->delegatedManagement;
     $view->strHelpAddPhone = Piwik::translate('MobileMessaging_Settings_PhoneNumbers_HelpAdd', array(Piwik::translate('General_Settings'), Piwik::translate('MobileMessaging_SettingsMenu')));
     if ($view->credentialSupplied && $view->accountManagedByCurrentUser) {
         $view->provider = $mobileMessagingAPI->getSMSProvider();
         $view->creditLeft = $mobileMessagingAPI->getCreditLeft();
     }
     $view->smsProviders = SMSProvider::$availableSMSProviders;
     // construct the list of countries from the lang files
     $countries = array();
     foreach (Common::getCountriesList() as $countryCode => $continentCode) {
         if (isset(CountryCallingCodes::$countryCallingCodes[$countryCode])) {
             $countries[$countryCode] = array('countryName' => \Piwik\Plugins\UserCountry\countryTranslate($countryCode), 'countryCallingCode' => CountryCallingCodes::$countryCallingCodes[$countryCode]);
         }
     }
     $view->countries = $countries;
     $view->defaultCountry = Common::getCountry(LanguagesManager::getLanguageCodeForCurrentUser(), true, IP::getIpFromHeader());
     $view->phoneNumbers = $mobileMessagingAPI->getPhoneNumbers();
     $this->setBasicVariablesView($view);
     return $view->render();
 }

作者:TensorWrenchOS    项目:piwi   
/**
  * @dataProvider getipv6Addresses
  * @group Plugins
  */
 public function testApplyIPMask6($ip, $expected)
 {
     // each IP is tested with 0 to 4 octets masked
     for ($maskLength = 0; $maskLength < 4; $maskLength++) {
         $res = IPAnonymizer::applyIPMask(IP::P2N($ip), $maskLength);
         $this->assertEquals($expected[$maskLength], $res, "Got " . bin2hex($res) . ", Expected " . bin2hex($expected[$maskLength]) . ", Mask Level " . $maskLength);
     }
 }

作者:KiwiJuice    项目:handball-dacha   
/**
  * Hook on Tracker.Visit.setVisitorIp to anomymize visitor IP addresses
  */
 public function setVisitorIpAddress(&$ip)
 {
     if (!$this->isActiveInTracker()) {
         Common::printDebug("Visitor IP was _not_ anonymized: " . IP::N2P($ip));
         return;
     }
     $originalIp = $ip;
     $ip = self::applyIPMask($ip, Config::getInstance()->Tracker['ip_address_mask_length']);
     Common::printDebug("Visitor IP (was: " . IP::N2P($originalIp) . ") has been anonymized: " . IP::N2P($ip));
 }

作者:a4tunad    项目:piwi   
/**
  * Hook on Tracker.Visit.setVisitorIp to anomymize visitor IP addresses
  */
 public function setVisitorIpAddress(&$ip)
 {
     if (!$this->isActive()) {
         Common::printDebug("Visitor IP was _not_ anonymized: " . IP::N2P($ip));
         return;
     }
     $originalIp = $ip;
     $privacyConfig = new Config();
     $ip = self::applyIPMask($ip, $privacyConfig->ipAddressMaskLength);
     Common::printDebug("Visitor IP (was: " . IP::N2P($originalIp) . ") has been anonymized: " . IP::N2P($ip));
 }

作者:brienomatt    项目:elmsl   
private function sendMail($subject, $body)
 {
     $feedbackEmailAddress = Config::getInstance()->General['feedback_email_address'];
     $subject = '[ Feedback Feature - Piwik ] ' . $subject;
     $body = Common::unsanitizeInputValue($body) . "\n" . 'Piwik ' . Version::VERSION . "\n" . 'IP: ' . IP::getIpFromHeader() . "\n" . 'URL: ' . Url::getReferrer() . "\n";
     $mail = new Mail();
     $mail->setFrom(Piwik::getCurrentUserEmail());
     $mail->addTo($feedbackEmailAddress, 'Piwik Team');
     $mail->setSubject($subject);
     $mail->setBodyText($body);
     @$mail->send();
 }

作者:KiwiJuice    项目:handball-dacha   
/**
  * Main view showing listing of websites and settings
  */
 public function index()
 {
     $view = new View('@SitesManager/index');
     Site::clearCache();
     if (Piwik::isUserIsSuperUser()) {
         $sitesRaw = API::getInstance()->getAllSites();
     } else {
         $sitesRaw = API::getInstance()->getSitesWithAdminAccess();
     }
     // Gets sites after Site.setSite hook was called
     $sites = array_values(Site::getSites());
     if (count($sites) != count($sitesRaw)) {
         throw new Exception("One or more website are missing or invalid.");
     }
     foreach ($sites as &$site) {
         $site['alias_urls'] = API::getInstance()->getSiteUrlsFromId($site['idsite']);
         $site['excluded_ips'] = explode(',', $site['excluded_ips']);
         $site['excluded_parameters'] = explode(',', $site['excluded_parameters']);
         $site['excluded_user_agents'] = explode(',', $site['excluded_user_agents']);
     }
     $view->adminSites = $sites;
     $view->adminSitesCount = count($sites);
     $timezones = API::getInstance()->getTimezonesList();
     $view->timezoneSupported = SettingsServer::isTimezoneSupportEnabled();
     $view->timezones = Common::json_encode($timezones);
     $view->defaultTimezone = API::getInstance()->getDefaultTimezone();
     $view->currencies = Common::json_encode(API::getInstance()->getCurrencyList());
     $view->defaultCurrency = API::getInstance()->getDefaultCurrency();
     $view->utcTime = Date::now()->getDatetime();
     $excludedIpsGlobal = API::getInstance()->getExcludedIpsGlobal();
     $view->globalExcludedIps = str_replace(',', "\n", $excludedIpsGlobal);
     $excludedQueryParametersGlobal = API::getInstance()->getExcludedQueryParametersGlobal();
     $view->globalExcludedQueryParameters = str_replace(',', "\n", $excludedQueryParametersGlobal);
     $globalExcludedUserAgents = API::getInstance()->getExcludedUserAgentsGlobal();
     $view->globalExcludedUserAgents = str_replace(',', "\n", $globalExcludedUserAgents);
     $view->globalSearchKeywordParameters = API::getInstance()->getSearchKeywordParametersGlobal();
     $view->globalSearchCategoryParameters = API::getInstance()->getSearchCategoryParametersGlobal();
     $view->isSearchCategoryTrackingEnabled = \Piwik\Plugin\Manager::getInstance()->isPluginActivated('CustomVariables');
     $view->allowSiteSpecificUserAgentExclude = API::getInstance()->isSiteSpecificUserAgentExcludeEnabled();
     $view->globalKeepURLFragments = API::getInstance()->getKeepURLFragmentsGlobal();
     $view->currentIpAddress = IP::getIpFromHeader();
     $view->showAddSite = (bool) Common::getRequestVar('showaddsite', false);
     $this->setBasicVariablesView($view);
     return $view->render();
 }

作者:piwi    项目:piwi   
private function setManageVariables(View $view)
 {
     $view->isSuperUser = Piwik::hasUserSuperUserAccess();
     $mobileMessagingAPI = API::getInstance();
     $view->delegatedManagement = $mobileMessagingAPI->getDelegatedManagement();
     $view->credentialSupplied = $mobileMessagingAPI->areSMSAPICredentialProvided();
     $view->accountManagedByCurrentUser = $view->isSuperUser || $view->delegatedManagement;
     $view->strHelpAddPhone = $this->translator->translate('MobileMessaging_Settings_PhoneNumbers_HelpAdd', array($this->translator->translate('General_Settings'), $this->translator->translate('MobileMessaging_SettingsMenu')));
     $view->creditLeft = 0;
     $currentProvider = '';
     if ($view->credentialSupplied && $view->accountManagedByCurrentUser) {
         $currentProvider = $mobileMessagingAPI->getSMSProvider();
         $view->creditLeft = $mobileMessagingAPI->getCreditLeft();
     }
     $view->delegateManagementOptions = array(array('key' => '0', 'value' => Piwik::translate('General_No'), 'description' => Piwik::translate('General_Default') . '. ' . Piwik::translate('MobileMessaging_Settings_LetUsersManageAPICredential_No_Help')), array('key' => '1', 'value' => Piwik::translate('General_Yes'), 'description' => Piwik::translate('MobileMessaging_Settings_LetUsersManageAPICredential_Yes_Help')));
     $providers = array();
     $providerOptions = array();
     foreach (SMSProvider::findAvailableSmsProviders() as $provider) {
         if (empty($currentProvider)) {
             $currentProvider = $provider->getId();
         }
         $providers[$provider->getId()] = $provider->getDescription();
         $providerOptions[$provider->getId()] = $provider->getId();
     }
     $view->provider = $currentProvider;
     $view->smsProviders = $providers;
     $view->smsProviderOptions = $providerOptions;
     $defaultCountry = Common::getCountry(LanguagesManager::getLanguageCodeForCurrentUser(), true, IP::getIpFromHeader());
     $view->defaultCallingCode = '';
     // construct the list of countries from the lang files
     $countries = array(array('key' => '', 'value' => ''));
     foreach ($this->regionDataProvider->getCountryList() as $countryCode => $continentCode) {
         if (isset(CountryCallingCodes::$countryCallingCodes[$countryCode])) {
             if ($countryCode == $defaultCountry) {
                 $view->defaultCallingCode = CountryCallingCodes::$countryCallingCodes[$countryCode];
             }
             $countries[] = array('key' => CountryCallingCodes::$countryCallingCodes[$countryCode], 'value' => \Piwik\Plugins\UserCountry\countryTranslate($countryCode));
         }
     }
     $view->countries = $countries;
     $view->phoneNumbers = $mobileMessagingAPI->getPhoneNumbers();
     $this->setBasicVariablesView($view);
 }

作者:TensorWrenchOS    项目:piwi   
private function printVisitorInformation()
 {
     $debugVisitInfo = $this->visitorInfo;
     $debugVisitInfo['idvisitor'] = bin2hex($debugVisitInfo['idvisitor']);
     $debugVisitInfo['config_id'] = bin2hex($debugVisitInfo['config_id']);
     $debugVisitInfo['location_ip'] = IP::N2P($debugVisitInfo['location_ip']);
     Common::printDebug($debugVisitInfo);
 }

作者:carriercom    项目:piwi   
/**
  * Returns hostname, without port numbers
  *
  * @param $host
  * @return array
  */
 public static function getHostSanitized($host)
 {
     return IP::sanitizeIp($host);
 }

作者:mgou-ne    项目:piwi   
/**
  * Returns the most accurate IP address availble for the current user, in
  * IPv4 format. This could be the proxy client's IP address.
  *
  * @return string IP address in presentation format.
  */
 public function getIpFromHeader()
 {
     Piwik::checkUserHasSomeViewAccess();
     return IP::getIpFromHeader();
 }

作者:carriercom    项目:piwi   
/**
  * In the case of a new visit, we have to do the following actions:
  *
  * 1) Insert the new action
  *
  * 2) Insert the visit information
  *
  * @param Action $action
  * @param bool $visitIsConverted
  */
 protected function handleNewVisit($action, $visitIsConverted)
 {
     Common::printDebug("New Visit (IP = " . IP::N2P($this->getVisitorIp()) . ")");
     $this->visitorInfo = $this->getNewVisitorInformation($action);
     // Add Custom variable key,value to the visitor array
     $this->visitorInfo = array_merge($this->visitorInfo, $this->visitorCustomVariables);
     $this->visitorInfo['visit_goal_converted'] = $visitIsConverted ? 1 : 0;
     $this->visitorInfo['referer_name'] = substr($this->visitorInfo['referer_name'], 0, 70);
     $this->visitorInfo['referer_keyword'] = substr($this->visitorInfo['referer_keyword'], 0, 255);
     $this->visitorInfo['config_resolution'] = substr($this->visitorInfo['config_resolution'], 0, 9);
     /**
      * Triggered before a new [visit entity](/guides/persistence-and-the-mysql-backend#visits) is persisted.
      * 
      * This event can be used to modify the visit entity or add new information to it before it is persisted.
      * The UserCountry plugin, for example, uses this event to add location information for each visit.
      *
      * @param array &$visit The visit entity. Read [this](/guides/persistence-and-the-mysql-backend#visits) to see
      *                      what information it contains.
      * @param \Piwik\Tracker\Request $request An object describing the tracking request being processed.
      */
     Piwik::postEvent('Tracker.newVisitorInformation', array(&$this->visitorInfo, $this->request));
     $this->request->overrideLocation($this->visitorInfo);
     $this->printVisitorInformation();
     $idVisit = $this->insertNewVisit($this->visitorInfo);
     $this->visitorInfo['idvisit'] = $idVisit;
     $this->visitorInfo['visit_first_action_time'] = $this->request->getCurrentTimestamp();
     $this->visitorInfo['visit_last_action_time'] = $this->request->getCurrentTimestamp();
 }

作者:jos    项目:CGE-File-Sharin   
/**
  * In the case of a new visit, we have to do the following actions:
  *
  * 1) Insert the new action
  *
  * 2) Insert the visit information
  *
  * @param Visitor $visitor
  * @param Action $action
  * @param bool $visitIsConverted
  */
 protected function handleNewVisit($visitor, $action, $visitIsConverted)
 {
     Common::printDebug("New Visit (IP = " . IP::N2P($this->getVisitorIp()) . ")");
     $this->visitorInfo = $this->getNewVisitorInformation($visitor);
     // Add Custom variable key,value to the visitor array
     $this->visitorInfo = array_merge($this->visitorInfo, $this->visitorCustomVariables);
     $visitor->clearVisitorInfo();
     foreach ($this->visitorInfo as $key => $value) {
         $visitor->setVisitorColumn($key, $value);
     }
     $dimensions = $this->getAllVisitDimensions();
     $this->triggerHookOnDimensions($dimensions, 'onNewVisit', $visitor, $action);
     if ($visitIsConverted) {
         $this->triggerHookOnDimensions($dimensions, 'onConvertedVisit', $visitor, $action);
     }
     /**
      * Triggered before a new [visit entity](/guides/persistence-and-the-mysql-backend#visits) is persisted.
      *
      * This event can be used to modify the visit entity or add new information to it before it is persisted.
      * The UserCountry plugin, for example, uses this event to add location information for each visit.
      *
      * @param array &$visit The visit entity. Read [this](/guides/persistence-and-the-mysql-backend#visits) to see
      *                      what information it contains.
      * @param \Piwik\Tracker\Request $request An object describing the tracking request being processed.
      */
     Piwik::postEvent('Tracker.newVisitorInformation', array(&$this->visitorInfo, $this->request));
     $this->printVisitorInformation();
     $idVisit = $this->insertNewVisit($this->visitorInfo);
     $this->visitorInfo['idvisit'] = $idVisit;
     $this->visitorInfo['visit_first_action_time'] = $this->request->getCurrentTimestamp();
     $this->visitorInfo['visit_last_action_time'] = $this->request->getCurrentTimestamp();
     $visitor->setVisitorColumn('idvisit', $this->visitorInfo['idvisit']);
     $visitor->setVisitorColumn('visit_first_action_time', $this->visitorInfo['visit_first_action_time']);
     $visitor->setVisitorColumn('visit_last_action_time', $this->visitorInfo['visit_last_action_time']);
 }

作者:NikitaEgoro    项目:plugin-clickhea   
}
    }
    $f = fopen($clickheatConf['logPath'] . $final . '/' . date('Y-m-d') . '.log', 'a');
}
if (is_resource($f)) {
    $logMe = true;
    if (isset($_COOKIE['clickheat-admin'])) {
        echo 'OK, but click not logged as you selected it in the admin panel ("Log my clicks/Enregistrer mes clics")';
        $logMe = false;
    } elseif (IS_PIWIK_MODULE === true) {
        $site = (string) (int) $site;
        // prevents path injection
        if (file_exists(PIWIK_INCLUDE_PATH . '/tmp/cache/tracker/' . $site . '.php')) {
            require_once PIWIK_INCLUDE_PATH . '/tmp/cache/tracker/' . $site . '.php';
            if (isset($content['excluded_ips'])) {
                $ip = IPUtils::stringToBinaryIP(\Piwik\Network\IP::fromStringIP(IP::getIpFromHeader()));
                if (isIpInRange($ip, $content['excluded_ips']) === true) {
                    echo 'OK, but click not logged as you prevent this IP to be tracked in Piwik\'s configuration';
                    $logMe = false;
                }
            }
        }
    }
    if ($logMe === true) {
        echo 'OK';
        fputs($f, (int) $_GET['x'] . '|' . (int) $_GET['y'] . '|' . (int) $_GET['w'] . '|' . $browser . '|' . (int) $_GET['c'] . "\n");
    }
    fclose($f);
} else {
    echo 'KO, file not writable';
}

作者:a4tunad    项目:piwi   
$rows = Db::fetchAll("SELECT idvisit, location_ip, " . implode(',', array_keys($logVisitFieldsToUpdate)) . "\n\t\t\t\t\t\tFROM " . Common::prefixTable('log_visit') . "\n\t\t\t\t\t\tLIMIT {$start}, {$limit}");
 if (!count($rows)) {
     continue;
 }
 foreach ($rows as $row) {
     $fieldsToSet = array();
     foreach ($logVisitFieldsToUpdate as $field => $ignore) {
         if (empty($fieldsToSet[$field])) {
             $fieldsToSet[] = $field;
         }
     }
     // skip if it already has a location
     if (empty($fieldsToSet)) {
         continue;
     }
     $ip = IP::N2P($row['location_ip']);
     $location = $provider->getLocation(array('ip' => $ip));
     if (!empty($location[LocationProvider::COUNTRY_CODE_KEY])) {
         $location[LocationProvider::COUNTRY_CODE_KEY] = strtolower($location[LocationProvider::COUNTRY_CODE_KEY]);
     }
     $row['location_country'] = strtolower($row['location_country']);
     $columnsToSet = array();
     $bind = array();
     foreach ($logVisitFieldsToUpdate as $column => $locationKey) {
         if (!empty($location[$locationKey]) && $location[$locationKey] != $row[$column]) {
             $columnsToSet[] = $column . ' = ?';
             $bind[] = $location[$locationKey];
         }
     }
     if (empty($columnsToSet)) {
         continue;

作者:piwi    项目:piwi   
/**
  * Echo's a pretty formatted location using a specific LocationProvider.
  *
  * Input:
  *   The 'id' query parameter must be set to the ID of the LocationProvider to use.
  *
  * Output:
  *   The pretty formatted location that was obtained. Will be HTML.
  */
 public function getLocationUsingProvider()
 {
     $providerId = Common::getRequestVar('id');
     $provider = LocationProvider::getProviderById($providerId);
     if (empty($provider)) {
         throw new Exception("Invalid provider ID: '{$providerId}'.");
     }
     $location = $provider->getLocation(array('ip' => IP::getIpFromHeader(), 'lang' => Common::getBrowserLanguage(), 'disable_fallbacks' => true));
     $location = LocationProvider::prettyFormatLocation($location, $newline = '<br/>', $includeExtra = true);
     return $location;
 }

作者:normimu    项目:piwi   
/**
  * @return mixed|string
  * @throws Exception
  */
 public function getIpString()
 {
     $cip = $this->getParam('cip');
     if (empty($cip)) {
         return IP::getIpFromHeader();
     }
     if (!$this->isAuthenticated()) {
         Common::printDebug("WARN: Tracker API 'cip' was used with invalid token_auth");
         return IP::getIpFromHeader();
     }
     return $cip;
 }

作者:ThaDafinse    项目:Piwik-GeoIpChai   
private function getDefaultIp()
 {
     return IP::getIpFromHeader();
 }


问题


面经


文章

微信
公众号

扫码关注公众号