Returns the visitor ID of the most recent visit.

@param int $idSite
@param bool|string $segment
@return string
550424
public function getMostRecentVisitorId($idSite, $segment = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        // for faster performance search for a visitor within the last 7 days first
        $minTimestamp = Date::now()->subDay(7)->getTimestamp();

        $dataTable = $this->loadLastVisitsDetailsFromDatabase(
            $idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp
        );

        if (0 >= $dataTable->getRowsCount()) {
            $minTimestamp = Date::now()->subYear(1)->getTimestamp();
            // no visitor found in last 7 days, look further back for up to 1 year. This query will be slower
            $dataTable = $this->loadLastVisitsDetailsFromDatabase(
                $idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1, $minTimestamp
            );
        }

        if (0 >= $dataTable->getRowsCount()) {
            // no visitor found in last year, look over all logs. This query might be quite slow
            $dataTable = $this->loadLastVisitsDetailsFromDatabase(
                $idSite, $period = false, $date = false, $segment, $offset = 0, $limit = 1
            );
        }

        if (0 >= $dataTable->getRowsCount()) {
            return false;
        }

        $visitorFactory = new VisitorFactory();
        $visitDetails   = $dataTable->getFirstRow()->getColumns();
        $visitor        = $visitorFactory->create($visitDetails);

        return $visitor->getVisitorId();
    }
158
public static function isHostKnownAliasHost($urlHost, $idSite)
    {
        $websiteData = Cache::getCacheWebsiteAttributes($idSite);

        if (isset($websiteData['hosts'])) {
            $canonicalHosts = array();
            foreach ($websiteData['hosts'] as $host) {
                $canonicalHosts[] = self::toCanonicalHost($host);
            }

            $canonicalHost = self::toCanonicalHost($urlHost);
            if (in_array($canonicalHost, $canonicalHosts)) {
                return true;
            }
        }

        return false;
    }
1197275
public function get($idSite, $period, $date, $segment = false, $columns = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        $columns = Piwik::getArrayFromApiParameter($columns);

        // build columns map for faster checks later on
        $columnsMap = array();
        foreach ($columns as $column) {
            $columnsMap[$column] = true;
        }

        // find out which columns belong to which plugin
        $columnsByPlugin = array();
        $meta = \Piwik\Plugins\API\API::getInstance()->getReportMetadata($idSite, $period, $date);
        foreach ($meta as $reportMeta) {
            // scan all *.get reports
            if ($reportMeta['action'] == 'get'
                && !isset($reportMeta['parameters'])
                && $reportMeta['module'] != 'API'
                && !empty($reportMeta['metrics'])
            ) {
                $plugin = $reportMeta['module'];
                $allMetrics = array_merge($reportMeta['metrics'], @$reportMeta['processedMetrics'] ?: array());
                foreach ($allMetrics as $column => $columnTranslation) {
                    // a metric from this report has been requested
                    if (isset($columnsMap[$column])
                        // or by default, return all metrics
                        || empty($columnsMap)
                    ) {
                        $columnsByPlugin[$plugin][] = $column;
                    }
                }
            }
        }
        krsort($columnsByPlugin);

        $mergedDataTable = false;
        $params = compact('idSite', 'period', 'date', 'segment');
        foreach ($columnsByPlugin as $plugin => $columns) {
            // load the data
            $className = Request::getClassNameAPI($plugin);
            $params['columns'] = implode(',', $columns);
            $dataTable = Proxy::getInstance()->call($className, 'get', $params);

            $dataTable->filter(function (DataTable $table) {
                $table->clearQueuedFilters();
            });

            // merge reports
            if ($mergedDataTable === false) {
                $mergedDataTable = $dataTable;
            } else {
                $merger = new MergeDataTables();
                $merger->mergeDataTables($mergedDataTable, $dataTable);
            }
        }

        if (!empty($columnsMap)
            && !empty($mergedDataTable)
        ) {
            $mergedDataTable->queueFilter('ColumnDelete', array(false, array_keys($columnsMap)));
        }

        return $mergedDataTable;
    }
768062
public function getAll($idSite = false)
    {
        if (!empty($idSite)) {
            Piwik::checkUserHasViewAccess($idSite);
        } else {
            Piwik::checkUserHasSomeViewAccess();
        }

        $userLogin = Piwik::getCurrentUserLogin();

        $model = $this->getModel();
        if(Piwik::hasUserSuperUserAccess()) {
            $segments = $model->getAllSegmentsForAllUsers($idSite);
        } else {
            if (empty($idSite)) {
                $segments = $model->getAllSegments($userLogin);
            } else {
                $segments = $model->getAllSegmentsForSite($idSite, $userLogin);
            }
        }

        $segments = $this->sortSegmentsCreatedByUserFirst($segments);

        return $segments;
    }
26185
public function getIdAdresse($idEvenement)
    {
        if (!isset($idEvenement)) {
                        return false;
        }
        $idEvenementGroup = $this->getIdGroupeEvenement($idEvenement);
        $requete ="
				SELECT idAdresse
				FROM _adresseEvenement
				WHERE  idEvenement = $idEvenementGroup
				";
        $result = $this->connexionBdd->requete($requete);
        $res = mysql_fetch_assoc($result);
        return $res['idAdresse'];
    }
877252
public function setSiteAliasUrls($idSite, $urls = array())
    {
        Piwik::checkUserHasAdminAccess($idSite);

        $mainUrl = Site::getMainUrlFor($idSite);
        array_unshift($urls, $mainUrl);

        $urlsProperty = new Urls($idSite);
        $urlsProperty->setValue($urls);
        $urlsProperty->save();

        $inserted = array_diff($urlsProperty->getValue(), $urls);

        $this->postUpdateWebsite($idSite);

        return count($inserted);
    }
1062799
public function getSiteById($idSite, $env, $includeSite404Table = false)
	{
        // Retrieve cache version if front mode to avoid multiple calls
	    $cacheKey = get_class($this) . '_getSiteById_' . $idSite . '_' . $env . '_' . $includeSite404Table;
        $cacheConfig = 'engine_page_services';
        $melisEngineCacheSystem = $this->getServiceLocator()->get('MelisEngineCacheSystem');
        $results = $melisEngineCacheSystem->getCacheByKey($cacheKey, $cacheConfig);
        if (!empty($results)) return $results;
	    
		$select = $this->tableGateway->getSql()->select();
		
		$select->columns(array('*'));
	
		$siteDomainjoin = new Expression('melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id AND sdom_env =\''.$env.'\'');
		
		if($includeSite404Table) {
		    
		    $site404join = new Expression('melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id');
		    
		    $select->join('melis_cms_site_domain', $siteDomainjoin, array('*'), $select::JOIN_LEFT)
		           ->join('melis_cms_site_404', $site404join, array('*'), $select::JOIN_LEFT);
		}
		else {
		    $select->join('melis_cms_site_domain', $siteDomainjoin, array('*'), $select::JOIN_LEFT);
		}
		
		$select->where('site_id ='.$idSite);
	
		$resultSet = $this->tableGateway->selectWith($select);

		$melisEngineCacheSystem->setCacheByKey($cacheKey, $cacheConfig, $resultSet);
		
		return $resultSet;
	}
777454
public function getPageUrlsFollowingSiteSearch($idSite, $period, $date, $segment = false, $expanded = false, $idSubtable = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable);
        $this->keepPagesFollowingSearch($dataTable);
        return $dataTable;
    }
375218
private function buildRememberArchivedReportIdProcessSafe($idSite, $date)
    {
        $id  = $this->buildRememberArchivedReportIdForSiteAndDate($idSite, $date);
        $id .= '_' . getmypid();
        return $id;
    }
343549
public function detectGoalsMatchingUrl($idSite, $action)
    {
        if (!Common::isGoalPluginEnabled()) {
            return array();
        }

        $goals = $this->getGoalDefinitions($idSite);

        $convertedGoals = array();
        foreach ($goals as $goal) {
            $convertedUrl = $this->detectGoalMatch($goal, $action);
            if (!is_null($convertedUrl)) {
                $convertedGoals[] = array('url' => $convertedUrl) + $goal;
            }
        }
        return $convertedGoals;
    }
601164
public function getSiteSearchCategories($idSite, $period, $date, $segment = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        Actions::checkCustomVariablesPluginEnabled();
        $customVariables = APICustomVariables::getInstance()->getCustomVariables($idSite, $period, $date, $segment, $expanded = false, $_leavePiwikCoreVariables = true);

        $customVarNameToLookFor = ActionSiteSearch::CVAR_KEY_SEARCH_CATEGORY;

        $dataTable = new DataTable();
        // Handle case where date=last30&period=day
        // FIXMEA: this logic should really be refactored somewhere, this is ugly!
        if ($customVariables instanceof DataTable\Map) {
            $dataTable = $customVariables->getEmptyClone();

            $customVariableDatatables = $customVariables->getDataTables();
            foreach ($customVariableDatatables as $key => $customVariableTableForDate) {
                // we do not enter the IF, in the case idSite=1,3 AND period=day&date=datefrom,dateto,
                if ($customVariableTableForDate instanceof DataTable
                    && $customVariableTableForDate->getMetadata(Archive\DataTableFactory::TABLE_METADATA_PERIOD_INDEX)
                ) {
                    $row = $customVariableTableForDate->getRowFromLabel($customVarNameToLookFor);
                    if ($row) {
                        $dateRewrite = $customVariableTableForDate->getMetadata(Archive\DataTableFactory::TABLE_METADATA_PERIOD_INDEX)->getDateStart()->toString();
                        $idSubtable = $row->getIdSubDataTable();
                        $categories = APICustomVariables::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $dateRewrite, $idSubtable, $segment);
                        $dataTable->addTable($categories, $key);
                    }
                }
            }
        } elseif ($customVariables instanceof DataTable) {
            $row = $customVariables->getRowFromLabel($customVarNameToLookFor);
            if ($row) {
                $idSubtable = $row->getIdSubDataTable();
                $dataTable = APICustomVariables::getInstance()->getCustomVariablesValuesFromNameId($idSite, $period, $date, $idSubtable, $segment);
            }
        }
        $this->filterActionsDataTable($dataTable, $isPageTitleType = false);
        $dataTable->filter('ReplaceColumnNames');
        $this->addPagesPerSearchColumn($dataTable, $columnToRead = 'nb_actions');
        return $dataTable;
    }
153491
public function getSuggestedValuesForSegment($segmentName, $idSite)
    {
        if (empty(Config::getInstance()->General['enable_segment_suggested_values'])) {
            return array();
        }

        Piwik::checkUserHasViewAccess($idSite);

        $maxSuggestionsToReturn = 30;
        $segment = $this->findSegment($segmentName, $idSite);

        // if segment has suggested values callback then return result from it instead
        $suggestedValuesCallbackRequiresTable = false;
        if (isset($segment['suggestedValuesCallback'])) {
            $suggestedValuesCallbackRequiresTable = $this->doesSuggestedValuesCallbackNeedData(
                $segment['suggestedValuesCallback']);

            if (!$suggestedValuesCallbackRequiresTable) {
                return call_user_func($segment['suggestedValuesCallback'], $idSite, $maxSuggestionsToReturn);
            }
        }

        // if period=range is disabled, do not proceed
        if (!Period\Factory::isPeriodEnabledForAPI('range')) {
            return array();
        }

        if (!empty($segment['unionOfSegments'])) {
            $values = array();
            foreach ($segment['unionOfSegments'] as $unionSegmentName) {
                $unionSegment = $this->findSegment($unionSegmentName, $idSite);

                try {
                    $result = $this->getSuggestedValuesForSegmentName($idSite, $unionSegment, $maxSuggestionsToReturn);
                    if (!empty($result)) {
                        $values = array_merge($result, $values);
                    }
                } catch (\Exception $e) {
                    // we ignore if there was no data found for $unionSegmentName
                }
            }

            if (empty($values)) {
                throw new \Exception("There was no data to suggest for $segmentName");
            }

        } else {
            $values = $this->getSuggestedValuesForSegmentName($idSite, $segment, $maxSuggestionsToReturn);
        }

        $values = $this->getMostFrequentValues($values);
        $values = array_slice($values, 0, $maxSuggestionsToReturn);
        $values = array_map(array('Piwik\Common', 'unsanitizeInputValue'), $values);

        return $values;
    }
156615
public function get($idSegment)
    {
        Piwik::checkUserHasSomeViewAccess();

        if (!is_numeric($idSegment)) {
            throw new Exception("idSegment should be numeric.");
        }

        $segment = $this->getModel()->getSegment($idSegment);

        if (empty($segment)) {
            return false;
        }
        try {

            if (!$segment['enable_all_users']) {
                Piwik::checkUserHasSuperUserAccessOrIsTheUser($segment['login']);
            }

        } catch (Exception $e) {
            throw new Exception($this->getMessageCannotEditSegmentCreatedBySuperUser());
        }

        if ($segment['deleted']) {
            throw new Exception("This segment is marked as deleted. ");
        }

        return $segment;
    }
1200913
public function getBrand($idSite, $period, $date, $segment = false)
    {
        $dataTable = $this->getDataTable('DevicesDetection_brands', $idSite, $period, $date, $segment);
        $dataTable->filter('GroupBy', array('label', __NAMESPACE__ . '\getDeviceBrandLabel'));
        $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'logo', __NAMESPACE__ . '\getBrandLogo'));
        $dataTable->filter('AddSegmentByLabel', array('deviceBrand'));
        return $dataTable;
    }
37264
public static function getDoneStringFlagFor(array $idSites, $segment, $periodLabel, $plugin)
    {
        if (!self::shouldProcessReportsAllPlugins($idSites, $segment, $periodLabel)) {
            return self::getDoneFlagArchiveContainsOnePlugin($segment, $plugin);
        }
        return self::getDoneFlagArchiveContainsAllPlugins($segment);
    }
720994
public function getVisitorId()
    {
        $found = false;
        
        // If User ID is set it takes precedence
        $userId = $this->getForcedUserId();
        if ($userId) {
            $userIdHashed = $this->getUserIdHashed($userId);
            $idVisitor = $this->truncateIdAsVisitorId($userIdHashed);
            Common::printDebug("Request will be recorded for this user_id = " . $userId . " (idvisitor = $idVisitor)");
            $found = true;
        }

        // Was a Visitor ID "forced" (@see Tracking API setVisitorId()) for this request?
        if (!$found) {
            $idVisitor = $this->getForcedVisitorId();
            if (!empty($idVisitor)) {
                if (strlen($idVisitor) != Tracker::LENGTH_HEX_ID_STRING) {
                    throw new InvalidRequestParameterException("Visitor ID (cid) $idVisitor must be " . Tracker::LENGTH_HEX_ID_STRING . " characters long");
                }
                Common::printDebug("Request will be recorded for this idvisitor = " . $idVisitor);
                $found = true;
            }
        }

        // - If set to use 3rd party cookies for Visit ID, read the cookie
        if (!$found) {
            $useThirdPartyCookie = $this->shouldUseThirdPartyCookie();
            if ($useThirdPartyCookie) {
                $idVisitor = $this->getThirdPartyCookieVisitorId();
                if(!empty($idVisitor)) {
                    $found = true;
                }
            }
        }

        // If a third party cookie was not found, we default to the first party cookie
        if (!$found) {
            $idVisitor = Common::getRequestVar('_id', '', 'string', $this->params);
            $found = strlen($idVisitor) >= Tracker::LENGTH_HEX_ID_STRING;
        }

        if ($found) {
            return $this->getVisitorIdAsBinary($idVisitor);
        }

        return false;
    }
510944
public function getSegmentHashesByIdSite()
    {
        //Get a list of hashes of all segments that exist now
        $sql = "SELECT DISTINCT definition, enable_only_idsite FROM " . Common::prefixTable('segment')
            . " WHERE deleted = 0";
        $rows = Db::fetchAll($sql);
        $segmentHashes = array();
        foreach ($rows as $row) {
            $idSite = (int)$row['enable_only_idsite'];
            if (! isset($segmentHashes[$idSite])) {
                $segmentHashes[$idSite] = array();
            }
            $segmentHashes[$idSite][] = Segment::getSegmentHash($row['definition']);
        }

        return $segmentHashes;
    }