/** * 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 = Piwik_IP::getIpFromHeader(); if (!self::isSameOrAnonymizedIp($ip, $myIP) && (!isset($info['disable_fallbacks']) || !$info['disable_fallbacks'])) { 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(Piwik_UserCountry_LocationProvider_GeoIp_Pecl::ID, Piwik_UserCountry_LocationProvider_GeoIp_Php::ID); foreach ($fallbacks as $fallbackProviderId) { $otherProvider = Piwik_UserCountry_LocationProvider::getProviderById($fallbackProviderId); if ($otherProvider) { printDebug("Used {$fallbackProviderId} to detect this visitor IP"); return $otherProvider->getLocation($info); } } 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; }
function writeListsToFile($useragent, $majorArray, $minorArray) { //$answer_data = serialize($majorArray); //$name_data = serialize($majorNamesArray); printDebug("LM: useragent: " . $useragent); printDebug("LM: major lines:" . count($majorArray)); printDebug("LM: minor lines:" . count($minorArray)); /* // test debug printout // use the global, match answers to names global $majorNamesArray; global $minorNamesArray; $lines = array(); for ($i = 0; $i < count($majorArray); $i++) { $lines[$i] = $majorNamesArray[$i] . ": " . $majorArray[$i]; printDebug("LM: " . $lines[$i]); } $j = count($majorArray); for ($i = 0; $i < count($minorArray); $i++) { $lines[$j] = $minorNamesArray[$i] . ": " . $minorArray[$i]; printDebug("LM: " . $lines[$j]); $j++; } */ //file_put_contents("your-file.txt", $lines); }
/** * @param Piwik_Event_Notification $notification notification object */ function checkHeader($notification) { if (isset($_SERVER['HTTP_X_DO_NOT_TRACK']) && $_SERVER['HTTP_X_DO_NOT_TRACK'] === '1' || isset($_SERVER['HTTP_DNT']) && substr($_SERVER['HTTP_DNT'], 0, 1) === '1') { $exclude =& $notification->getNotificationObject(); $exclude = true; printDebug("DoNotTrack found."); $trackingCookie = Piwik_Tracker_IgnoreCookie::getTrackingCookie(); $trackingCookie->delete(); // this is an optional supplement to the site's tracking status resource at: // /.well-known/dnt // per Tracking Preference Expression (draft) header('Tk: 1'); } }
/** * initialize module with request datas * * @param object request * @return void */ function init(&$request, $o_tpl = null, $o_archive = null) { if (!is_a($o_tpl, "TemplateEngine")) { $o_tpl = null; } parent::init($request, $o_tpl); $date = $this->request->getDate(); if (is_null($this->data)) { if (is_null($o_archive)) { $o_archive = DataModel::getArchive($this->site, $date, $this->request->getPeriod()); } $this->data = new DataModel($o_archive, $this->request); } $d = new Date(getDateFromTimestamp(time())); if (($this->data->archive->date->get() == $d->get() || isset($this->disableCache)) && is_a($this->tpl, "TemplateEngine")) { printDebug("Current date asked is today's date, cache not activated<br>"); $this->tpl->caching = 0; } }
/** * @param Piwik_Event_Notification $notification notification object */ function checkHeader($notification) { if (isset($_SERVER['HTTP_X_DO_NOT_TRACK']) && $_SERVER['HTTP_X_DO_NOT_TRACK'] === '1' || isset($_SERVER['HTTP_DNT']) && substr($_SERVER['HTTP_DNT'], 0, 1) === '1') { $ua = Piwik_Tracker_Visit::getUserAgent($_REQUEST); if (strpos($ua, 'MSIE 10') !== false) { printDebug("INTERNET EXPLORER 10 Enables DNT by default, so Piwik ignores DNT for all IE10 browsers..."); return; } $exclude =& $notification->getNotificationObject(); $exclude = true; printDebug("DoNotTrack found."); $trackingCookie = Piwik_Tracker_IgnoreCookie::getTrackingCookie(); $trackingCookie->delete(); // this is an optional supplement to the site's tracking status resource at: // /.well-known/dnt // per Tracking Preference Expression (draft) header('Tk: 1'); } }
function recordFunnelSteps($notification) { $info = $notification->getNotificationInfo(); $idSite = $info['idSite']; printDebug('Looking for funnel steps'); $funnels = Piwik_Funnels_API::getInstance()->getFunnels($idSite); if (count($funnels) > 0) { $idVisit = $info['idVisit']; $idLinkVisitAction = $info['idLinkVisitAction']; $idRefererAction = $info['idRefererAction']; $action = $notification->getNotificationObject(); $actionName = $action->getActionName(); $sanitizedUrl = $action->getActionUrl(); $actionUrl = htmlspecialchars_decode($sanitizedUrl); $idActionUrl = $action->getIdActionUrl(); $url = Piwik_Common::getRequestVar('url', '', 'string', $action->getRequest()); printDebug("idActionUrl" . $idActionUrl . " idSite " . $idSite . " idVisit " . $idVisit . " idRefererAction " . $idRefererAction); # Is this the next action for a recorded funnel step? $previous_step_action = Piwik_Query("UPDATE " . Piwik_Common::prefixTable('log_funnel_step') . "\n\t\t\t\t\t\t\t\t\t\t\t\t\tSET idaction_url_next = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE idsite = ? \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND idvisit = ? \n\t\t\t\t\t\t\t\t\t\t\t\t\tAND idaction_url = ?\n\t\t\t\t\t\t\t\t\t\t\t\t\tAND idaction_url_next is null", array($idActionUrl, $idSite, $idVisit, $idRefererAction)); } foreach ($funnels as &$funnel) { $steps = $funnel['steps']; foreach ($steps as &$step) { if ($step['url'] == $actionUrl or $step['name'] == $actionName) { printDebug("Matched Goal Funnel " . $funnel['idfunnel'] . " Step " . $step['idstep'] . "(name: " . $step['name'] . ", url: " . $step['url'] . "). "); $serverTime = time(); $datetimeServer = Piwik_Tracker::getDatetimeFromTimestamp($serverTime); // Look to see if this step has already been recorded for this visit $exists = Piwik_FetchOne("SELECT idlink_va\n\t\t\t\t\t\t\t\t\t\t\t FROM " . Piwik_Common::prefixTable('log_funnel_step') . " \n\t\t\t\t\t\t\t\t\t\t\t WHERE idsite = ? \n\t\t\t\t\t\t\t\t\t\t\t AND idfunnel = ?\n\t\t\t\t\t\t\t\t\t\t\t AND idstep = ?\n\t\t\t\t\t\t\t\t\t\t\t AND idvisit = ?", array($idSite, $funnel['idfunnel'], $step['idstep'], $idVisit)); // Record it if not if (!$exists) { printDebug("Recording..."); Piwik_Query("INSERT INTO " . Piwik_Common::prefixTable('log_funnel_step') . "\n\t\t\t\t\t\t\t\t\t(idvisit, idsite, idaction_url, url, \n\t\t\t\t\t\t\t\t\t idgoal, idfunnel, idstep, idlink_va, \n\t\t\t\t\t\t\t\t\t idaction_url_ref, server_time)\n\t\t\t\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", array($idVisit, $idSite, $idActionUrl, $url, $funnel['idgoal'], $step['idfunnel'], $step['idstep'], $idLinkVisitAction, $idRefererAction, $datetimeServer)); } } } } }
/** * @param Piwik_Event_Notification $notification notification object */ public function getVisitorLocation($notification) { require_once PIWIK_INCLUDE_PATH . "/plugins/UserCountry/LocationProvider.php"; $location =& $notification->getNotificationObject(); $visitorInfo = $notification->getNotificationInfo(); $id = Piwik_Common::getCurrentLocationProviderId(); $provider = Piwik_UserCountry_LocationProvider::getProviderById($id); if ($provider === false) { $id = Piwik_UserCountry_LocationProvider_Default::ID; $provider = Piwik_UserCountry_LocationProvider::getProviderById($id); printDebug("GEO: no current location provider sent, falling back to default '{$id}' one."); } $location = $provider->getLocation($visitorInfo); // if we can't find a location, use default provider if ($location === false) { $defaultId = Piwik_UserCountry_LocationProvider_Default::ID; $provider = Piwik_UserCountry_LocationProvider::getProviderById($defaultId); $location = $provider->getLocation($visitorInfo); printDebug("GEO: couldn't find a location with Geo Module '{$id}', using Default '{$defaultId}' provider as fallback..."); $id = $defaultId; } printDebug("GEO: Found IP location (provider '" . $id . "'): " . var_export($location, true)); }
/** * Records in the DB the association between the visit and this action. * * @param int idVisit is the ID of the current visit in the DB table log_visit * @param int idRefererActionUrl is the ID of the last action done by the current visit. * @param int timeSpentRefererAction is the number of seconds since the last action was done. * It is directly related to idRefererActionUrl. */ public function record( $idVisit, $visitorIdCookie, $idRefererActionUrl, $idRefererActionName, $timeSpentRefererAction) { $this->loadIdActionNameAndUrl(); $idActionName = in_array($this->getActionType(), array(Piwik_Tracker_Action::TYPE_ACTION_NAME, Piwik_Tracker_Action::TYPE_ACTION_URL)) ? (int)$this->getIdActionName() : null; $insert = array( 'idvisit' => $idVisit, 'idsite' => $this->idSite, 'idvisitor' => $visitorIdCookie, 'server_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->timestamp), 'idaction_url' => (int)$this->getIdActionUrl(), 'idaction_name' => $idActionName, 'idaction_url_ref' => $idRefererActionUrl, 'idaction_name_ref' => $idRefererActionName, 'time_spent_ref_action' => $timeSpentRefererAction ); $customVariables = Piwik_Tracker_Visit::getCustomVariables($scope = 'page', $this->request); $insert = array_merge($insert, $customVariables); // Mysqli apparently does not like NULL inserts? $insertWithoutNulls = array(); foreach($insert as $column => $value) { if(!is_null($value)) { $insertWithoutNulls[$column] = $value; } } $fields = implode(", ", array_keys($insertWithoutNulls)); $bind = array_values($insertWithoutNulls); $values = Piwik_Common::getSqlStringFieldsArray($insertWithoutNulls); $sql = "INSERT INTO ".Piwik_Common::prefixTable('log_link_visit_action'). " ($fields) VALUES ($values)"; Piwik_Tracker::getDatabase()->query( $sql, $bind ); $this->idLinkVisitAction = Piwik_Tracker::getDatabase()->lastInsertId(); $info = array( 'idSite' => $this->idSite, 'idLinkVisitAction' => $this->idLinkVisitAction, 'idVisit' => $idVisit, 'idRefererActionUrl' => $idRefererActionUrl, 'idRefererActionName' => $idRefererActionName, 'timeSpentRefererAction' => $timeSpentRefererAction, ); printDebug($insertWithoutNulls); /* * send the Action object ($this) and the list of ids ($info) as arguments to the event */ Piwik_PostEvent('Tracker.Action.record', $this, $info); }
protected function endProcess() { switch ($this->getState()) { case self::STATE_LOGGING_DISABLE: printDebug("Logging disabled, display transparent logo"); $this->outputTransparentGif(); break; case self::STATE_NO_GET_VARIABLE: printDebug("No get variables => piwik page"); echo "<a href='index.php'>Piwik</a> is a free open source <a href='http://piwik.org'>web analytics</a> alternative to Google analytics."; break; case self::STATE_TO_REDIRECT_URL: $this->sendHeader('Location: ' . $this->getUrlToRedirect()); break; case self::STATE_NOTHING_TO_NOTICE: default: printDebug("Nothing to notice => default behaviour"); $this->outputTransparentGif(); break; } printDebug("End of the page."); if ($GLOBALS['DEBUGPIWIK'] === true) { Piwik::printSqlProfilingReportLogStats(self::$db); } self::disconnectDb(); }
/** * This method allows to set custom IP + server time when using Tracking API. * These two attributes can be only set by the Super User (passing token_auth). */ protected function handleTrackingApi($request) { $shouldAuthenticate = Piwik_Config::getInstance()->Tracker['tracking_requests_require_authentication']; if ($shouldAuthenticate) { if (!$this->authenticateSuperUserOrAdmin($request)) { return; } printDebug("token_auth is authenticated!"); } else { printDebug("token_auth authentication not required"); } // Custom IP to use for this visitor $customIp = Piwik_Common::getRequestVar('cip', false, 'string', $request); if (!empty($customIp)) { $this->setForceIp($customIp); } // Custom server date time to use $customDatetime = Piwik_Common::getRequestVar('cdt', false, 'string', $request); if (!empty($customDatetime)) { $this->setForceDateTime($customDatetime); } // Forced Visitor ID to record the visit / action $customVisitorId = Piwik_Common::getRequestVar('cid', false, 'string', $request); if (!empty($customVisitorId)) { $this->setForceVisitorId($customVisitorId); } }
protected function loadTrackerPlugins() { try { $pluginsTracker = Piwik_Tracker_Config::getInstance()->Plugins_Tracker; if (is_array($pluginsTracker) && count($pluginsTracker) != 0) { Piwik_PluginsManager::getInstance()->doNotLoadAlwaysActivatedPlugins(); Piwik_PluginsManager::getInstance()->setPluginsToLoad($pluginsTracker['Plugins_Tracker']); printDebug("Loading plugins: { " . implode(",", $pluginsTracker['Plugins_Tracker']) . "}"); } } catch (Exception $e) { printDebug("ERROR: " . $e->getMessage()); } }
function showDebug($var, $trace = false, $exit = true) { return printDebug($var, $trace, $exit); }
@ignore_user_abort(true); if (@(include "Version.php") === false || !class_exists('Piwik_Version')) { set_include_path(PIWIK_INCLUDE_PATH . '/core' . PATH_SEPARATOR . PIWIK_INCLUDE_PATH . '/libs' . PATH_SEPARATOR . PIWIK_INCLUDE_PATH . '/plugins' . PATH_SEPARATOR . get_include_path()); } require_once "Common.php"; require_once "PluginsManager.php"; require_once "Tracker.php"; require_once "Tracker/Config.php"; require_once "Tracker/Action.php"; require_once "Cookie.php"; require_once "Tracker/Db.php"; require_once "Tracker/Visit.php"; require_once "Tracker/GoalManager.php"; session_cache_limiter('nocache'); ob_start(); if ($GLOBALS['PIWIK_TRACKER_DEBUG'] === true) { date_default_timezone_set(date_default_timezone_get()); require_once "core/ErrorHandler.php"; require_once "core/ExceptionHandler.php"; set_error_handler('Piwik_ErrorHandler'); set_exception_handler('Piwik_ExceptionHandler'); printDebug($_GET); Piwik_Tracker_Db::enableProfiling(); Piwik::createConfigObject(); Piwik::createLogObject(); } $process = new Piwik_Tracker(); $process->main(); ob_end_flush(); printDebug($_COOKIE);
if (!$insertTagStmt->execute()) { echo "***** Error : inserting timestamp {$v} for {$id} : " . $insertTagStmt->error . "\n"; } foreach ($curNodeTags as $k => $v) { if (!$insertTagStmt->execute()) { echo "***** Error : inserting tag {$k} => {$v} for {$id} : " . $insertTagStmt->error . "\n"; } } $mysqli->commit(); } } } $curNodeAttrs = null; $curNodeTags = null; } } } $file = "change_file.osc"; $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false); xml_set_element_handler($xml_parser, "startElement", "endElement"); if (!($fp = fopen($file, "r"))) { die("could not open XML input"); } while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } printDebug();
/** * Init the phpmv cookie used in logging. Called when no previous phpmv cookie detected. * * @param string $uniqId Old uniqId if exists * * @return string uniqId assigned */ function put($uniqId = '') { printDebug("<br>=>Cookie is init on visitor (idcookie and last_visit_time)<br>"); if ($uniqId == '') { $uniqId = md5(uniqid(rand())); } $this->setVar('idcookie', $uniqId); $this->setVar('last_visit_time', todayTime()); return $uniqId; }
function recordGoals($idSite, $visitorInformation, $visitCustomVariables, $action, $referrerTimestamp, $referrerUrl, $referrerCampaignName, $referrerCampaignKeyword) { $location_country = isset($visitorInformation['location_country']) ? $visitorInformation['location_country'] : Piwik_Common::getCountry(Piwik_Common::getBrowserLanguage(), $enableLanguageToCountryGuess = Piwik_Tracker_Config::getInstance()->Tracker['enable_language_to_country_guess'], $visitorInformation['location_ip']); $location_continent = isset($visitorInformation['location_continent']) ? $visitorInformation['location_continent'] : Piwik_Common::getContinent($location_country); $goal = array('idvisit' => $visitorInformation['idvisit'], 'idsite' => $idSite, 'idvisitor' => $visitorInformation['idvisitor'], 'server_time' => Piwik_Tracker::getDatetimeFromTimestamp($visitorInformation['visit_last_action_time']), 'location_country' => $location_country, 'location_continent' => $location_continent, 'visitor_returning' => $visitorInformation['visitor_returning'], 'visitor_days_since_first' => $visitorInformation['visitor_days_since_first'], 'visitor_count_visits' => $visitorInformation['visitor_count_visits']); // Attributing the correct Referrer to this conversion. // Priority order is as follows: // 1) Campaign name/kwd parsed in the JS // 2) Referrer URL stored in the _ref cookie // 3) If no info from the cookie, attribute to the current visit referrer // 3) Default values: current referrer $type = $visitorInformation['referer_type']; $name = $visitorInformation['referer_name']; $keyword = $visitorInformation['referer_keyword']; $time = $visitorInformation['visit_first_action_time']; // 1) Campaigns from 1st party cookie if (!empty($referrerCampaignName)) { $type = Piwik_Common::REFERER_TYPE_CAMPAIGN; $name = $referrerCampaignName; $keyword = $referrerCampaignKeyword; $time = $referrerTimestamp; } elseif (!empty($referrerUrl)) { $referrer = new Piwik_Tracker_Visit_Referer(); $referrer = $referrer->getRefererInformation($referrerUrl, $currentUrl = '', $idSite); // if the parsed referer is interesting enough, ie. website or search engine if (in_array($referrer['referer_type'], array(Piwik_Common::REFERER_TYPE_SEARCH_ENGINE, Piwik_Common::REFERER_TYPE_WEBSITE))) { $type = $referrer['referer_type']; $name = $referrer['referer_name']; $keyword = $referrer['referer_keyword']; $time = $referrerTimestamp; } } $goal += array('referer_type' => $type, 'referer_name' => $name, 'referer_keyword' => $keyword, 'referer_visit_server_date' => date("Y-m-d", $time)); $goal += $visitCustomVariables; foreach ($this->convertedGoals as $convertedGoal) { printDebug("- Goal " . $convertedGoal['idgoal'] . " matched. Recording..."); $newGoal = $goal; $newGoal['idgoal'] = $convertedGoal['idgoal']; $newGoal['url'] = $convertedGoal['url']; $newGoal['revenue'] = $convertedGoal['revenue']; if (!is_null($action)) { $newGoal['idaction_url'] = $action->getIdActionUrl(); $newGoal['idlink_va'] = $action->getIdLinkVisitAction(); } // If multiple Goal conversions per visit, set a cache buster $newGoal['buster'] = $convertedGoal['allow_multiple'] == 0 ? '0' : $visitorInformation['visit_last_action_time']; $newGoalDebug = $newGoal; $newGoalDebug['idvisitor'] = bin2hex($newGoalDebug['idvisitor']); printDebug($newGoalDebug); $fields = implode(", ", array_keys($newGoal)); $bindFields = substr(str_repeat("?,", count($newGoal)), 0, -1); $sql = "INSERT IGNORE INTO " . Piwik_Common::prefixTable('log_conversion') . "\t\n\t\t\t\t\t({$fields}) VALUES ({$bindFields}) "; $bind = array_values($newGoal); Piwik_Tracker::getDatabase()->query($sql, $bind); } }
if (is_file($crontabFile)) { include $crontabFile; } if (WEB_CRONTAB && is_writable($crontabFile) && ((!isset($crontab) || $crontab['date_last_success'] != getDateFromTimestamp(time())) && (!is_file($crontabFile) || isset($crontab) && $crontab['time_last_try'] < time() - TIME_TO_WAIT_FOR_PARALLEL_ARCHIVE))) { $crontab['time_last_try'] = time(); $crontab['date_last_success'] = '2000-12-31'; saveConfigFile($crontabFile, $crontab, "crontab"); printDebug('==========================<br> CRONTAB BEGIN/ <br> ==========================<br> '); require_once INCLUDE_PATH . '/core/include/PmvConfig.class.php'; require_once INCLUDE_PATH . '/core/include/ApplicationController.php'; $r =& Request::getInstance(); $r->setModuleName('send_mail'); $r->setCrontabAllowed(); ApplicationController::init(); printDebug('==========================<br> CRONTAB END/ <br> ==========================<br> '); $crontab['date_last_success'] = getDateFromTimestamp(time()); saveConfigFile($crontabFile, $crontab, "crontab"); } $db->close(); redirectToUrlIfNecessary(); loadImage($logo, $idSite); // flush content for display if (DEBUG) { ob_end_flush(); }
/** * Update the cookie information. */ protected function setThirdPartyCookie() { if (!$this->shouldUseThirdPartyCookie()) { return; } printDebug("We manage the cookie..."); // idcookie has been generated in handleNewVisit or we simply propagate the old value $this->cookie->set(0, bin2hex($this->visitorInfo['idvisitor'])); $this->cookie->save(); }
/** * Update the cookie information. */ protected function updateCookie() { printDebug("We manage the cookie..."); if (isset($this->visitorInfo['referer_type']) && $this->visitorInfo['referer_type'] != Piwik_Common::REFERER_TYPE_DIRECT_ENTRY) { // if the setting is set to use only the first referer, // we don't update the cookie referer values if they are already set if (!Piwik_Tracker_Config::getInstance()->Tracker['use_first_referer_to_determine_goal_referer'] || $this->cookie->get(Piwik_Tracker::COOKIE_INDEX_REFERER_TYPE) == false) { $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_REFERER_TYPE, $this->visitorInfo['referer_type']); $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_REFERER_NAME, $this->visitorInfo['referer_name']); $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_REFERER_KEYWORD, $this->visitorInfo['referer_keyword']); $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_REFERER_ID_VISIT, $this->visitorInfo['idvisit']); $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_REFERER_TIMESTAMP, $this->getCurrentTimestamp()); } } // idcookie has been generated in handleNewVisit or we simply propagate the old value $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_IDVISITOR, $this->visitorInfo['visitor_idcookie']); // the last action timestamp is the current timestamp $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_TIMESTAMP_LAST_ACTION, $this->visitorInfo['visit_last_action_time']); // the first action timestamp is the timestamp of the first action of the current visit $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_TIMESTAMP_FIRST_ACTION, $this->visitorInfo['visit_first_action_time']); // the idvisit has been generated by mysql in handleNewVisit or simply propagated here $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_ID_VISIT, $this->visitorInfo['idvisit']); // the last action ID is the current exit idaction if (isset($this->visitorInfo['visit_exit_idaction'])) { $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_ID_LAST_ACTION, $this->visitorInfo['visit_exit_idaction']); } // for a new visit, we flag the visit with visitor_returning if (isset($this->visitorInfo['visitor_returning'])) { $this->cookie->set(Piwik_Tracker::COOKIE_INDEX_VISITOR_RETURNING, $this->visitorInfo['visitor_returning']); } $this->cookie->save(); }
function _ValidateFile($file, $onlythis = 0) { global $LV_done, $LV_links, $LV_no_read, $LV_local_only; global $LV_rec, $LV_rec_max, $LV_num_links; $LV_done[$file] = "OK"; // save we checked this file already $LV_num_links++; // increase total no. of checked links printDebug("BEGIN: {$file} (" . ($LV_rec + 1) . ")", 2); if (!($f = fopen($file, "r"))) { return false; } // if the file doesn't exist $LV_rec++; // increase recursion level if ($LV_rec > $LV_rec_max) { $LV_rec_max = $LV_rec; } ereg('^(.*)/([^/]*)$', $file, $out); $dir = $out[1]; // get path from filename printDebug("CHECKING: {$file} ({$LV_rec})", 1); // test if we want to search in this file if (eregi('\\.(' . $LV_no_read . ')$', $file)) { fclose($f); $LV_rec--; return true; } // if $onlythis --> reset $LV_no_read to skip all files if ($onlythis) { $old_no_read = $LV_no_read; $LV_no_read = ".*"; } $link = '(' . $LV_links . ')=(\'|")([^\'"]*)(\'|")'; while (!feof($f)) { // for each line in file $line = fgets($f, 65000); // get first 6500 bytes of line while (eregi($link, $line, $out)) { // for each link on that line $new_file = eregi_replace('#.*', "", $out[3]); // filename from the link (w/o anchor) if (eregi('^mailto:', $new_file)) { $new_file = ""; } // if it is mailto: URL if ($LV_local_only && eregi('^(http|ftp)://', $new_file)) { $new_file = ""; } // don't check remote links if ($new_file) { // if valid link to check $new = ParseParent($dir, $new_file); // filename with parsed path if (!$LV_done[$new]) { // if it was not checked already if (!_ValidateFile($new)) { // if the file was not found printDebug("<b>ERROR</b>: Not found: '{$new_file}' in '{$file}'!"); } } } // remove that link from line $line = eregi_replace(AddSlashes($out[0]), "", $line); } // end of line } // end of file flush(); // try to flush all data to web-server fclose($f); if ($onlythis) { $LV_no_read = $old_no_read; } // restore normal printDebug("END: {$file}", 2); $LV_rec--; return true; }
/** * Tracker requests will automatically trigger the Scheduled tasks. * This is useful for users who don't setup the cron, * but still want daily/weekly/monthly PDF reports emailed automatically. * * This is similar to calling the API CoreAdminHome.runScheduledTasks (see misc/cron/archive.sh) * * @param int $now Current timestamp */ public static function runScheduledTasks($now) { // Currently, there is no hourly tasks. When there are some, // this could be too agressive minimum interval (some hours would be skipped in case of low traffic) $minimumInterval = Piwik_Config::getInstance()->Tracker['scheduled_tasks_min_interval']; // If the user disabled browser archiving, he has already setup a cron // To avoid parallel requests triggering the Scheduled Tasks, // Get last time tasks started executing $cache = Piwik_Common::getCacheGeneral(); if ($minimumInterval <= 0 || empty($cache['isBrowserTriggerArchivingEnabled'])) { printDebug("-> Scheduled tasks not running in Tracker: Browser archiving is disabled."); return; } $nextRunTime = $cache['lastTrackerCronRun'] + $minimumInterval; if (isset($GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS']) && $GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS'] || $cache['lastTrackerCronRun'] === false || $nextRunTime < $now) { $cache['lastTrackerCronRun'] = $now; Piwik_Common::setCacheGeneral($cache); Piwik_Common::initCorePiwikInTrackerMode(); Piwik_SetOption('lastTrackerCronRun', $cache['lastTrackerCronRun']); printDebug('-> Scheduled Tasks: Starting...'); // save current user privilege and temporarily assume super user privilege $isSuperUser = Piwik::isUserIsSuperUser(); // Scheduled tasks assume Super User is running Piwik::setUserIsSuperUser(); // While each plugins should ensure that necessary languages are loaded, // we ensure English translations at least are loaded Piwik_Translate::getInstance()->loadEnglishTranslation(); $resultTasks = Piwik_TaskScheduler::runTasks(); // restore original user privilege Piwik::setUserIsSuperUser($isSuperUser); printDebug($resultTasks); printDebug('Finished Scheduled Tasks.'); } else { printDebug("-> Scheduled tasks not triggered."); } printDebug("Next run will be from: " . date('Y-m-d H:i:s', $nextRunTime) . ' UTC'); }
<?php /* * This script returns events from my calendar */ require 'setup.php'; my_include('src/utils.php'); # do you want to debug this script $debug = 0; //$p_start=$_GET['start']; //$p_end=$_GET['end']; $p_start = '2009-08-24 01:32:40'; $p_end = '2011-08-24 01:32:40'; # connect to the database my_mysql_connect(); $query = sprintf('SELECT id,title,url,start,end FROM TbEvent where start > \'%s\' and end < \'%s\'', $p_start, $p_end); if ($debug == 1) { printDebug($query); } $result = mysql_query($query); # make sure we really have a result assert($result); if ($debug) { printDebug($result); } result_echo_json($result); my_mysql_disconnect();
/** * This method allows to set custom IP + server time when using Tracking API. * These two attributes can be only set by the Super User (passing token_auth). */ protected function handleTrackingApi() { if (!$this->authenticateSuperUserOrAdmin()) { return; } printDebug("token_auth is authenticated!"); // Custom IP to use for this visitor $customIp = Piwik_Common::getRequestVar('cip', false, 'string', $this->request); if (!empty($customIp)) { $this->setForceIp($customIp); } // Custom server date time to use $customDatetime = Piwik_Common::getRequestVar('cdt', false, 'string', $this->request); if (!empty($customDatetime)) { $this->setForceDateTime($customDatetime); } // Forced Visitor ID to record the visit / action $customVisitorId = Piwik_Common::getRequestVar('cid', false, 'string', $this->request); if (!empty($customVisitorId)) { $this->setForceVisitorId($customVisitorId); } }
/** * Records in the DB the association between the visit and this action. * * @param int idVisit is the ID of the current visit in the DB table log_visit * @param int idRefererActionUrl is the ID of the last action done by the current visit. * @param int timeSpentRefererAction is the number of seconds since the last action was done. * It is directly related to idRefererActionUrl. */ public function record($idVisit, $visitorIdCookie, $idRefererActionUrl, $idRefererActionName, $timeSpentRefererAction) { $this->loadIdActionNameAndUrl(); $idActionName = $this->getIdActionName(); if (is_null($idActionName)) { $idActionName = 0; } Piwik_Tracker::getDatabase()->query("INSERT INTO " . Piwik_Common::prefixTable('log_link_visit_action') . " (idvisit, idsite, idvisitor, server_time, idaction_url, idaction_name, idaction_url_ref, idaction_name_ref, time_spent_ref_action) \n\t\t\t\t\t\t\tVALUES (?,?,?,?,?,?,?,?,?)", array($idVisit, $this->idSite, $visitorIdCookie, Piwik_Tracker::getDatetimeFromTimestamp($this->timestamp), $this->getIdActionUrl(), $idActionName, $idRefererActionUrl, $idRefererActionName, $timeSpentRefererAction)); $this->idLinkVisitAction = Piwik_Tracker::getDatabase()->lastInsertId(); $info = array('idSite' => $this->idSite, 'idLinkVisitAction' => $this->idLinkVisitAction, 'idVisit' => $idVisit, 'idRefererActionUrl' => $idRefererActionUrl, 'idRefererActionName' => $idRefererActionName, 'timeSpentRefererAction' => $timeSpentRefererAction); printDebug($info); /* * send the Action object ($this) and the list of ids ($info) as arguments to the event */ Piwik_PostEvent('Tracker.Action.record', $this, $info); }
/** * Helper function used by other record* methods which will INSERT or UPDATE the conversion in the DB * * @param array $newGoal * @param bool $mustUpdateNotInsert If set to true, the previous conversion will be UPDATEd. This is used for the Cart Update conversion (only one cart per visit) * @param array $updateWhere * @return bool */ protected function recordGoal($newGoal, $mustUpdateNotInsert = false, $updateWhere = array()) { $newGoalDebug = $newGoal; $newGoalDebug['idvisitor'] = bin2hex($newGoalDebug['idvisitor']); printDebug($newGoalDebug); $fields = implode(", ", array_keys($newGoal)); $bindFields = Piwik_Common::getSqlStringFieldsArray($newGoal); if ($mustUpdateNotInsert) { $updateParts = $sqlBind = $updateWhereParts = array(); foreach ($newGoal as $name => $value) { $updateParts[] = $name . " = ?"; $sqlBind[] = $value; } foreach ($updateWhere as $name => $value) { $updateWhereParts[] = $name . " = ?"; $sqlBind[] = $value; } $sql = 'UPDATE ' . Piwik_Common::prefixTable('log_conversion') . "\t\n\t\t\t\t\tSET " . implode($updateParts, ', ') . "\n\t\t\t\t\t\tWHERE " . implode($updateWhereParts, ' AND '); Piwik_Tracker::getDatabase()->query($sql, $sqlBind); return true; } else { $sql = 'INSERT IGNORE INTO ' . Piwik_Common::prefixTable('log_conversion') . "\t\n\t\t\t\t\t({$fields}) VALUES ({$bindFields}) "; $bind = array_values($newGoal); $result = Piwik_Tracker::getDatabase()->query($sql, $bind); // If a record was inserted, we return true return Piwik_Tracker::getDatabase()->rowCount($result) > 0; } }
function debugCookie($cookiedArray) { // gets blank for 0/false and 1 for 1/true printDebug("MTB: debug cookie called."); foreach ($cookiedArray as $line) { printDebug("Value is: " . $line); } }
/** * Logs the provider in the log_visit table */ public function logProviderInfo($notification) { $visitorInfo =& $notification->getNotificationObject(); $ip = Piwik_IP::N2P($visitorInfo['location_ip']); // In case the IP was anonymized, we should not continue since the DNS reverse lookup will fail and this will slow down tracking if (substr($ip, -2, 2) == '.0') { printDebug("IP Was anonymized so we skip the Provider DNS reverse lookup..."); return; } $hostname = $this->getHost($ip); $hostnameExtension = $this->getCleanHostname($hostname); // add the provider value in the table log_visit $visitorInfo['location_provider'] = $hostnameExtension; $visitorInfo['location_provider'] = substr($visitorInfo['location_provider'], 0, 100); // improve the country using the provider extension if valid $hostnameDomain = substr($hostnameExtension, 1 + strrpos($hostnameExtension, '.')); if ($hostnameDomain == 'uk') { $hostnameDomain = 'gb'; } if (array_key_exists($hostnameDomain, Piwik_Common::getCountriesList())) { $visitorInfo['location_country'] = $hostnameDomain; } }
require_once PIWIK_INCLUDE_PATH . '/core/Cookie.php'; session_cache_limiter('nocache'); @date_default_timezone_set('UTC'); if (!defined('PIWIK_ENABLE_TRACKING') || PIWIK_ENABLE_TRACKING) { ob_start(); } if ($GLOBALS['PIWIK_TRACKER_DEBUG'] === true) { require_once PIWIK_INCLUDE_PATH . '/core/Loader.php'; require_once PIWIK_INCLUDE_PATH . '/core/ErrorHandler.php'; require_once PIWIK_INCLUDE_PATH . '/core/ExceptionHandler.php'; $timer = new Piwik_Timer(); set_error_handler('Piwik_ErrorHandler'); set_exception_handler('Piwik_ExceptionHandler'); printDebug("Debug enabled - Input parameters: <br/>" . var_export($_GET, true)); Piwik_Tracker_Db::enableProfiling(); Piwik::createConfigObject(); Piwik::createLogObject(); } if (!defined('PIWIK_ENABLE_TRACKING') || PIWIK_ENABLE_TRACKING) { $process = new Piwik_Tracker(); try { $process->main(); } catch (Exception $e) { echo "Error:" . $e->getMessage(); } ob_end_flush(); if ($GLOBALS['PIWIK_TRACKER_DEBUG'] === true) { printDebug($_COOKIE); printDebug($timer); } }
function recordGoals($visitorInformation, $action) { $location_country = isset($visitorInformation['location_country']) ? $visitorInformation['location_country'] : Piwik_Common::getCountry(Piwik_Common::getBrowserLanguage(), $enableLanguageToCountryGuess = Piwik_Tracker_Config::getInstance()->Tracker['enable_language_to_country_guess']); $location_continent = isset($visitorInformation['location_continent']) ? $visitorInformation['location_continent'] : Piwik_Common::getContinent($location_country); $goal = array('idvisit' => $visitorInformation['idvisit'], 'idsite' => $visitorInformation['idsite'], 'visitor_idcookie' => $visitorInformation['visitor_idcookie'], 'server_time' => Piwik_Tracker::getDatetimeFromTimestamp($visitorInformation['visit_last_action_time']), 'visit_server_date' => $visitorInformation['visit_server_date'], 'location_country' => $location_country, 'location_continent' => $location_continent, 'visitor_returning' => $this->cookie->get(Piwik_Tracker::COOKIE_INDEX_VISITOR_RETURNING)); $referer_idvisit = $this->cookie->get(Piwik_Tracker::COOKIE_INDEX_REFERER_ID_VISIT); if ($referer_idvisit !== false) { $goal += array('referer_idvisit' => $referer_idvisit, 'referer_visit_server_date' => date("Y-m-d", $this->cookie->get(Piwik_Tracker::COOKIE_INDEX_REFERER_TIMESTAMP)), 'referer_type' => htmlspecialchars_decode($this->cookie->get(Piwik_Tracker::COOKIE_INDEX_REFERER_TYPE)), 'referer_name' => htmlspecialchars_decode($this->cookie->get(Piwik_Tracker::COOKIE_INDEX_REFERER_NAME)), 'referer_keyword' => htmlspecialchars_decode($this->cookie->get(Piwik_Tracker::COOKIE_INDEX_REFERER_KEYWORD))); } foreach ($this->convertedGoals as $convertedGoal) { printDebug("- Goal " . $convertedGoal['idgoal'] . " matched. Recording..."); $newGoal = $goal; $newGoal['idgoal'] = $convertedGoal['idgoal']; $newGoal['url'] = $convertedGoal['url']; $newGoal['revenue'] = $convertedGoal['revenue']; if (!is_null($action)) { $newGoal['idaction'] = $action->getIdAction(); $newGoal['idlink_va'] = $action->getIdLinkVisitAction(); } printDebug($newGoal); $fields = implode(", ", array_keys($newGoal)); $bindFields = substr(str_repeat("?,", count($newGoal)), 0, -1); try { Piwik_Tracker::getDatabase()->query("INSERT INTO " . Piwik_Common::prefixTable('log_conversion') . "\t({$fields}) \n\t\t\t\t\tVALUES ({$bindFields}) ", array_values($newGoal)); } catch (Exception $e) { if (strpos($e->getMessage(), '1062') !== false) { // integrity violation when same visit converts to the same goal twice printDebug("--> Goal already recorded for this (idvisit, idgoal)"); } else { throw $e; } } //$idlog_goal = Piwik_Tracker::getDatabase()->lastInsertId(); } }
/** * Records in the DB the association between the visit and this action. * * @param int idVisit is the ID of the current visit in the DB table log_visit * @param int idRefererAction is the ID of the last action done by the current visit. * @param int timeSpentRefererAction is the number of seconds since the last action was done. * It is directly related to idRefererAction. */ public function record($idVisit, $idRefererAction, $timeSpentRefererAction) { $actionId = $this->getIdAction(); if (empty($actionId)) { $actionId = 0; } Piwik_Tracker::getDatabase()->query("/* SHARDING_ID_SITE = " . $this->idSite . " */ INSERT INTO " . Piwik_Common::prefixTable('log_link_visit_action') . " (idvisit, idaction, idaction_ref, time_spent_ref_action) VALUES (?,?,?,?)", array($idVisit, $actionId, $idRefererAction, $timeSpentRefererAction)); $this->idLinkVisitAction = Piwik_Tracker::getDatabase()->lastInsertId(); $info = array('idSite' => $this->idSite, 'idLinkVisitAction' => $this->idLinkVisitAction, 'idVisit' => $idVisit, 'idRefererAction' => $idRefererAction, 'timeSpentRefererAction' => $timeSpentRefererAction); printDebug($info); /* * send the Action object ($this) and the list of ids ($info) as arguments to the event */ Piwik_PostEvent('Tracker.Action.record', $this, $info); }