示例#1
0
	protected function removeHoursInFuture($table, $idSite, $period, $date)
	{
		$site = new Piwik_Site($idSite);
		
		if(	$period == 'day'
			&& ($date == 'today'
				||  $date == Piwik_Date::factory('now', $site->getTimezone())->toString()))
		{
			$currentHour = Piwik_Date::factory('now', $site->getTimezone())->toString('G');
			// If no data for today, this is an exception to the API output rule, as we normally return nothing:
			// we shall return all hours of the day, with nb_visits = 0
			if($table->getRowsCount() == 0)
			{
				for($hour = 0; $hour <= $currentHour; $hour++)
				{
					$table->addRowFromSimpleArray( array('label' => $hour, 'nb_visits' => 0));
				}
				return $table;
			}
			
			$idsToDelete = array();
			foreach($table->getRows() as $id => $row)
			{
				$hour = $row->getColumn('label');
				if($hour > $currentHour)
				{
					$idsToDelete[] = $id;
				}
			}
			$table->deleteRows($idsToDelete);
		}
		return $table;
	}
示例#2
0
	protected function setDateTodayIfWebsiteCreatedToday()
	{
		$date = Piwik_Common::getRequestVar('date', false);
		if($date == 'today'
			|| Piwik_Common::getRequestVar('period', false) == 'range') 
		{
			return;
		} 
		$websiteId = Piwik_Common::getRequestVar('idSite', false, 'int');
		if ($websiteId) 
		{
			$website = new Piwik_Site($websiteId);
			$datetimeCreationDate = $this->site->getCreationDate()->getDatetime();
			$creationDateLocalTimezone = Piwik_Date::factory($datetimeCreationDate, $website->getTimezone())->toString('Y-m-d');
			$todayLocalTimezone = Piwik_Date::factory('now', $website->getTimezone())->toString('Y-m-d');
			if( $creationDateLocalTimezone == $todayLocalTimezone ) 
			{
				Piwik::redirectToModule( 'CoreHome', 'index', 
										array(	'date' => 'today', 
												'idSite' => $websiteId, 
												'period' => Piwik_Common::getRequestVar('period')) 
				);
			}
		}
	}
示例#3
0
 /**
  * Builds an array of Piwik_Archive of a given date range
  *
  * @param Piwik_Site $oSite 
  * @param string $strPeriod eg. 'day' 'week' etc.
  * @param string $strDate A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
  */
 function __construct(Piwik_Site $oSite, $strPeriod, $strDate, Piwik_Segment $segment)
 {
     $rangePeriod = new Piwik_Period_Range($strPeriod, $strDate, $oSite->getTimezone());
     foreach ($rangePeriod->getSubperiods() as $subPeriod) {
         $startDate = $subPeriod->getDateStart();
         $archive = Piwik_Archive::build($oSite->getId(), $strPeriod, $startDate, $segment->getString());
         $archive->setSegment($segment);
         $this->archives[] = $archive;
     }
 }
 /**
  * Builds an array of Piwik_Archive of a given date range
  *
  * @param Piwik_Site $oSite 
  * @param string $strPeriod eg. 'day' 'week' etc.
  * @param string $strDate A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
  */
 function __construct(Piwik_Site $oSite, $strPeriod, $strDate)
 {
     $rangePeriod = new Piwik_Period_Range($strPeriod, $strDate);
     foreach ($rangePeriod->getSubperiods() as $subPeriod) {
         $startDate = $subPeriod->getDateStart();
         $archive = Piwik_Archive::build($oSite->getId(), $strPeriod, $startDate);
         $archive->prepareArchive();
         $timestamp = $archive->getTimestampStartDate();
         $this->archives[$timestamp] = $archive;
     }
     ksort($this->archives);
 }
示例#5
0
 protected function getDefaultIndexView()
 {
     $view = new Piwik_View('Home/templates/index.tpl');
     $this->setGeneralVariablesView($view);
     $site = new Piwik_Site($view->idSite);
     $minDate = $site->getCreationDate();
     $view->minDateYear = $minDate->toString('Y');
     $view->minDateMonth = $minDate->toString('m');
     $view->minDateDay = $minDate->toString('d');
     $view->basicHtmlView = false;
     $view->content = '';
     return $view;
 }
示例#6
0
 function displayJavascriptCode()
 {
     $idSite = Piwik_Common::getRequestVar('idsite', 1);
     Piwik::checkUserHasViewAccess($idSite);
     $jsTag = Piwik::getJavascriptCode($idSite, Piwik_Url::getCurrentUrlWithoutFileName());
     $view = Piwik_View::factory('DisplayJavascriptCode');
     $this->setGeneralVariablesView($view);
     $view->menu = Piwik_GetAdminMenu();
     $site = new Piwik_Site($idSite);
     $view->displaySiteName = $site->getName();
     $view->jsTag = $jsTag;
     echo $view->render();
 }
示例#7
0
	public function generate() 
	{
		Piwik::checkUserIsSuperUser();
		$nonce = Piwik_Common::getRequestVar('form_nonce', '', 'string', $_POST);
		if(Piwik_Common::getRequestVar('choice', 'no') != 'yes' ||
				!Piwik_Nonce::verifyNonce('Piwik_VisitorGenerator.generate', $nonce))
		{
			Piwik::redirectToModule('VisitorGenerator', 'index');
		}
		Piwik_Nonce::discardNonce('Piwik_VisitorGenerator.generate');

		$daysToCompute = Piwik_Common::getRequestVar('daysToCompute', 1, 'int');

		// get idSite from POST with fallback to GET
		$idSite = Piwik_Common::getRequestVar('idSite', false, 'int', $_GET);
		$idSite = Piwik_Common::getRequestVar('idSite', $idSite, 'int', $_POST);

		Piwik::setMaxExecutionTime(0);

		$timer = new Piwik_Timer;
		$time = time() - ($daysToCompute-1)*86400;
		
		// Update site.ts_created if we generate visits on days before the website was created
		$site = new Piwik_Site($idSite);
		$minGeneratedDate = Piwik_Date::factory($time);
		if($minGeneratedDate->isEarlier($site->getCreationDate()))
		{
			// direct access to the website table (bad practise but this is a debug / dev plugin)
    		Zend_Registry::get('db')->update(Piwik_Common::prefixTable("site"), 
    							array('ts_created' =>  $minGeneratedDate->getDatetime()),
    							"idsite = $idSite");
		}
		
		$nbActionsTotal = 0;
		while($time <= time()) 
		{
			$nbActionsTotalThisDay = $this->generateVisits($time, $idSite);
			$time += 86400;
			$nbActionsTotal += $nbActionsTotalThisDay;
		}

		// Init view
		$view = Piwik_View::factory('generate');
		$this->setBasicVariablesView($view);
		$view->menu = Piwik_GetAdminMenu();
		$view->assign('timer', $timer);
		$view->assign('days', $daysToCompute);
		$view->assign('nbActionsTotal', $nbActionsTotal);
		$view->assign('nbRequestsPerSec', round($nbActionsTotal / $timer->getTime(),0));
		echo $view->render();
	}
示例#8
0
 protected function setDateTodayIfWebsiteCreatedToday()
 {
     $date = Piwik_Common::getRequestVar('date', false);
     $date = Piwik_Date::factory($date);
     if ($date->isToday()) {
         return;
     }
     $websiteId = Piwik_Common::getRequestVar('idSite', false);
     if ($websiteId) {
         $website = new Piwik_Site($websiteId);
         if ($website->getCreationDate()->isToday()) {
             Piwik::redirectToModule('CoreHome', 'index', array('date' => 'today', 'idSite' => $websiteId, 'period' => Piwik_Common::getRequestVar('period')));
         }
     }
 }
示例#9
0
 /**
  * Builds an array of Piwik_Archive of a given date range
  *
  * @param Piwik_Site $oSite 
  * @param string $strPeriod eg. 'day' 'week' etc.
  * @param string $strDate A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
  */
 function __construct(Piwik_Site $oSite, $strPeriod, $strDate)
 {
     $rangePeriod = new Piwik_Period_Range($strPeriod, $strDate);
     // TODO fix this when aggregating data from multiple websites
     // CAREFUL this class wouldnt work as is if handling archives from multiple websites
     // works only when managing archives from multiples dates/periods
     foreach ($rangePeriod->getSubperiods() as $subPeriod) {
         $startDate = $subPeriod->getDateStart();
         $archive = Piwik_Archive::build($oSite->getId(), $strPeriod, $startDate);
         $archive->prepareArchive();
         $timestamp = $archive->getTimestampStartDate();
         $this->archives[$timestamp] = $archive;
     }
     ksort($this->archives);
 }
示例#10
0
 protected function removeHoursInFuture($table, $idSite, $period, $date)
 {
     $site = new Piwik_Site($idSite);
     if ($period == 'day' && ($date == 'today' || $date == Piwik_Date::factory('now', $site->getTimezone())->toString())) {
         $currentHour = Piwik_Date::factory('now', $site->getTimezone())->toString('G');
         $idsToDelete = array();
         foreach ($table->getRows() as $id => $row) {
             $hour = $row->getColumn('label');
             if ($hour > $currentHour) {
                 $idsToDelete[] = $id;
             }
         }
         $table->deleteRows($idsToDelete);
     }
     return $table;
 }
示例#11
0
 public function setColumnsToDisplay($columnsNames)
 {
     $newColumnsNames = array();
     $goals = array();
     $idSite = $this->getIdSite();
     if ($idSite) {
         $goals = Piwik_Goals_API::getInstance()->getGoals($idSite);
         $ecommerceGoal = array('idgoal' => Piwik_Archive::LABEL_ECOMMERCE_ORDER, 'name' => Piwik_Translate('Goals_EcommerceOrder'));
         $site = new Piwik_Site($idSite);
         //Case Ecommerce report table
         if ($this->isEcommerce) {
             $goals = array($ecommerceGoal);
         } elseif ($site->isEcommerceEnabled()) {
             $goals = array_merge(array($ecommerceGoal), $goals);
         }
     }
     foreach ($columnsNames as $columnName) {
         if (in_array($columnName, array('goal_%s_conversion_rate', 'goal_%s_nb_conversions', 'goal_%s_revenue_per_visit', 'goal_%s_revenue', 'goal_%s_avg_order_revenue', 'goal_%s_items'))) {
             foreach ($goals as $goal) {
                 $idgoal = $goal['idgoal'];
                 // Columns names are escaped in smarty via | escape:'html'
                 $goal['name'] = Piwik_Common::unsanitizeInputValue($goal['name']);
                 if ($this->processOnlyIdGoal > Piwik_DataTable_Filter_AddColumnsProcessedMetricsGoal::GOALS_FULL_TABLE && $this->processOnlyIdGoal != $idgoal && !$this->isEcommerce) {
                     continue;
                 }
                 $name = Piwik_Translate($this->getColumnTranslation($columnName), $goal['name']);
                 $columnNameGoal = str_replace('%s', $idgoal, $columnName);
                 $this->setColumnTranslation($columnNameGoal, $name);
                 $this->setDynamicMetricDocumentation($columnName, $columnNameGoal, $goal['name'], $goal['idgoal']);
                 if (strpos($columnNameGoal, '_rate') === false && $this->processOnlyIdGoal == Piwik_DataTable_Filter_AddColumnsProcessedMetricsGoal::GOALS_OVERVIEW) {
                     continue;
                 }
                 if (strstr($columnNameGoal, '_revenue') !== false) {
                     $this->columnsToRevenueFilter[] = $columnNameGoal;
                 } else {
                     $this->columnsToConversionFilter[] = $columnNameGoal;
                 }
                 $newColumnsNames[] = $columnNameGoal;
             }
         } else {
             $newColumnsNames[] = $columnName;
         }
     }
     parent::setColumnsToDisplay($newColumnsNames);
 }
示例#12
0
 function getRank()
 {
     $idSite = Piwik_Common::getRequestVar('idSite');
     $site = new Piwik_Site($idSite);
     $url = urldecode(Piwik_Common::getRequestVar('url', '', 'string'));
     if (!empty($url) && strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) {
         $url = 'http://' . $url;
     }
     if (empty($url) || !Piwik_Common::isLookLikeUrl($url)) {
         $url = $site->getMainUrl();
     }
     $dataTable = Piwik_SEO_API::getInstance()->getRank($url);
     $view = Piwik_View::factory('index');
     $view->urlToRank = Piwik_SEO_RankChecker::extractDomainFromUrl($url);
     $renderer = Piwik_DataTable_Renderer::factory('php');
     $renderer->setSerialize(false);
     $view->ranks = $renderer->render($dataTable);
     echo $view->render();
 }
示例#13
0
 /**
  * Returns a report displaying the total visits, actions and revenue, as
  * well as the evolution of these values, of all existing sites over a
  * specified period of time.
  * 
  * If the specified period is not a 'range', this function will calculcate
  * evolution metrics. Evolution metrics are metrics that display the
  * percent increase/decrease of another metric since the last period.
  * 
  * This function will merge the result of the archive query so each
  * row in the result DataTable will correspond to the metrics of a single
  * site. If a date range is specified, the result will be a
  * DataTable_Array, but it will still be merged.
  * 
  * @param string $period The period type to get data for.
  * @param string $date The date(s) to get data for.
  * @param string $segment The segments to get data for.
  */
 public function getAll($period, $date, $segment = false)
 {
     Piwik::checkUserHasSomeViewAccess();
     $isGoalPluginEnabled = Piwik_Common::isGoalPluginEnabled();
     // get site data for every viewable site and cache them
     if (Piwik::isUserIsSuperUser()) {
         $sites = Piwik_SitesManager_API::getInstance()->getAllSites();
         Piwik_Site::setSites($sites);
     } else {
         $sites = Piwik_SitesManager_API::getInstance()->getSitesWithAtLeastViewAccess();
         Piwik_Site::setSitesFromArray($sites);
     }
     // build the archive type used to query archive data
     $archive = Piwik_Archive::build('all', $period, $date, $segment);
     // determine what data will be displayed
     $fieldsToGet = array('nb_visits', 'nb_actions');
     if ($isGoalPluginEnabled) {
         $revenueMetric = Piwik_Goals::getRecordName('revenue');
         $fieldsToGet[] = $revenueMetric;
     }
     // get the data
     $dataTable = $archive->getDataTableFromNumeric($fieldsToGet);
     // get rid of the DataTable_Array that is created by the IndexedBySite archive type
     $dataTable = $dataTable->mergeChildren();
     // if the period isn't a range & a lastN/previousN date isn't used, we get the same
     // data for the last period to show the evolution of visits/actions/revenue
     if ($period != 'range' && !preg_match('/(last|previous)([0-9]*)/', $date, $regs)) {
         if (strpos($date, ',')) {
             $rangePeriod = new Piwik_Period_Range($period, $date);
             $lastStartDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateStart(), $n = 1);
             $lastEndDate = Piwik_Period_Range::removePeriod($period, $rangePeriod->getDateEnd(), $n = 1);
             $strLastDate = "{$lastStartDate},{$lastEndDate}";
         } else {
             $strLastDate = Piwik_Period_Range::removePeriod($period, Piwik_Date::factory($date), $n = 1)->toString();
         }
         $pastArchive = Piwik_Archive::build('all', $period, $strLastDate, $segment);
         $pastData = $pastArchive->getDataTableFromNumeric($fieldsToGet);
         $pastData = $pastData->mergeChildren();
         // use past data to calculate evolution percentages
         $this->calculateEvolutionPercentages($dataTable, $pastData, $fieldsToGet);
     }
     // move the site id to a metadata column
     $dataTable->filter('ColumnCallbackAddMetadata', array('label', 'idsite'));
     // set the label of each row to the site name
     $getNameFor = array('Piwik_Site', 'getNameFor');
     $dataTable->filter('ColumnCallbackReplace', array('label', $getNameFor));
     // rename the revenue column from the metric name to 'revenue'
     if ($isGoalPluginEnabled) {
         $mapping = array($revenueMetric => 'revenue');
         $dataTable->filter('ReplaceColumnNames', array($mapping));
     }
     // Ensures data set sorted, for Metadata output
     $dataTable->filter('Sort', array('nb_visits', 'desc', $naturalSort = false));
     return $dataTable;
 }
示例#14
0
 public function tearDown()
 {
     parent::tearDown();
     Piwik_DataTable_Manager::getInstance()->deleteAll();
     Piwik_Option::getInstance()->clearCache();
     Piwik_Site::clearCache();
     Piwik_Common::deleteTrackerCache();
     Piwik_TablePartitioning::$tablesAlreadyInstalled = null;
     $tempTableName = Piwik_Common::prefixTable(Piwik_PrivacyManager_LogDataPurger::TEMP_TABLE_NAME);
     Piwik_Query("DROP TABLE IF EXISTS " . $tempTableName);
 }
示例#15
0
 public function addTopMenu()
 {
     $tooltip = false;
     try {
         $idSite = Piwik_Common::getRequestVar('idSite');
         $tooltip = Piwik_Translate('Dashboard_TopLinkTooltip', Piwik_Site::getNameFor($idSite));
     } catch (Exception $ex) {
         // if no idSite parameter, show no tooltip
     }
     $urlParams = array('module' => 'CoreHome', 'action' => 'index');
     Piwik_AddTopMenu('General_Dashboard', $urlParams, true, 1, $isHTML = false, $tooltip);
 }
示例#16
0
	function getRank()
	{
		$idSite = Piwik_Common::getRequestVar('idSite'); 
		$site = new Piwik_Site($idSite);

		$url = urldecode(Piwik_Common::getRequestVar('url', '', 'string'));

		if(empty($url) || @parse_url($url) === false)
		{
			$url = $site->getMainUrl();
		}

		$dataTable = Piwik_SEO_API::getInstance()->getRank($url);
		
		$view = Piwik_View::factory('index');
		$view->urlToRank = $url;
		
		$renderer = Piwik_DataTable_Renderer::factory('php');
		$renderer->setSerialize(false);
		$view->ranks = $renderer->render($dataTable);
		echo $view->render();
	}
示例#17
0
 public static function checkUserHasAdminAccess($idSites)
 {
     if (!self::$superUser) {
         $websitesAccess = self::$idSitesAdmin;
     } else {
         $websitesAccess = Piwik_SitesManager_API::getInstance()->getAllSitesId();
     }
     $idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites);
     foreach ($idSites as $idsite) {
         if (!in_array($idsite, $websitesAccess)) {
             throw new Exception("checkUserHasAdminAccess Fake exception // string not to be tested");
         }
     }
 }
示例#18
0
	/**
	 * Sets general variables to the view that are used by various templates and Javascript.
	 * If any error happens, displays the login screen
	 * @param Piwik_View $view
	 * @return void
	 */
	protected function setGeneralVariablesView($view)
	{
		$view->date = $this->strDate;
		
		try {
			$view->idSite = $this->idSite;
			if(empty($this->site) || empty($this->idSite))
			{
				throw new Exception("The requested website idSite is not found in the request, or is invalid.
				Please check that you are logged in Piwik and have permission to access the specified website.");
			}
			$this->setPeriodVariablesView($view);
			
			$rawDate = Piwik_Common::getRequestVar('date');
			$periodStr = Piwik_Common::getRequestVar('period');
			if($periodStr != 'range')
			{
				$date = Piwik_Date::factory($this->strDate);
				$period = Piwik_Period::factory($periodStr, $date);
			}
			else
			{
				$period = new Piwik_Period_Range($periodStr, $rawDate, $this->site->getTimezone());
			}
			$view->rawDate = $rawDate;
			$view->prettyDate = $period->getPrettyString();
			$view->siteName = $this->site->getName();
			$view->siteMainUrl = $this->site->getMainUrl();
			
			$datetimeMinDate = $this->site->getCreationDate()->getDatetime();
			$minDate = Piwik_Date::factory($datetimeMinDate, $this->site->getTimezone());
			$this->setMinDateView($minDate, $view);

			$maxDate = Piwik_Date::factory('now', $this->site->getTimezone());
			$this->setMaxDateView($maxDate, $view);
			
			// Setting current period start & end dates, for pre-setting the calendar when "Date Range" is selected 
			$dateStart = $period->getDateStart();
			if($dateStart->isEarlier($minDate)) { $dateStart = $minDate; } 
			$dateEnd = $period->getDateEnd();
			if($dateEnd->isLater($maxDate)) { $dateEnd = $maxDate; }
			
			$view->startDate = $dateStart;
			$view->endDate = $dateEnd;
			
			$this->setBasicVariablesView($view);
		} catch(Exception $e) {
			Piwik_ExitWithMessage($e->getMessage());
		}
	}
 /**
  * Returns the difference between the column in the specific row and its
  * sister column in the past DataTable.
  * 
  * @param Piwik_DataTable_Row $row
  * @return int|float
  */
 protected function getDividend($row)
 {
     $currentValue = $row->getColumn($this->columnValueToRead);
     // if the site this is for doesn't support ecommerce & this is for the revenue_evolution column,
     // we don't add the new column
     if ($currentValue === false && $this->isRevenueEvolution && !Piwik_Site::isEcommerceEnabledFor($row->getColumn('label'))) {
         return false;
     }
     $pastRow = $this->getPastRowFromCurrent($row);
     if ($pastRow) {
         $pastValue = $pastRow->getColumn($this->columnValueToRead);
     } else {
         $pastValue = 0;
     }
     return $currentValue - $pastValue;
 }
示例#20
0
 protected function setSparklinesAndNumbers($view)
 {
     $view->urlSparklineNbVisits = $this->getUrlSparkline('getEvolutionGraph', array('columns' => $view->displayUniqueVisitors ? array('nb_visits', 'nb_uniq_visitors') : array('nb_visits')));
     $view->urlSparklineNbPageviews = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_pageviews', 'nb_uniq_pageviews')));
     $view->urlSparklineNbDownloads = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_downloads', 'nb_uniq_downloads')));
     $view->urlSparklineNbOutlinks = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_outlinks', 'nb_uniq_outlinks')));
     $view->urlSparklineAvgVisitDuration = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('avg_time_on_site')));
     $view->urlSparklineMaxActions = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('max_actions')));
     $view->urlSparklineActionsPerVisit = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_actions_per_visit')));
     $view->urlSparklineBounceRate = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('bounce_rate')));
     $idSite = Piwik_Common::getRequestVar('idSite');
     $displaySiteSearch = Piwik_Site::isSiteSearchEnabledFor($idSite);
     if ($displaySiteSearch) {
         $view->urlSparklineNbSearches = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_searches', 'nb_keywords')));
     }
     $view->displaySiteSearch = $displaySiteSearch;
     $dataTableVisit = self::getVisitsSummary();
     $dataRow = $dataTableVisit->getRowsCount() == 0 ? new Piwik_DataTable_Row() : $dataTableVisit->getFirstRow();
     $dataTableActions = Piwik_Actions_API::getInstance()->get($idSite, Piwik_Common::getRequestVar('period'), Piwik_Common::getRequestVar('date'), Piwik_Common::getRequestVar('segment', false));
     $dataActionsRow = $dataTableActions->getRowsCount() == 0 ? new Piwik_DataTable_Row() : $dataTableActions->getFirstRow();
     $view->nbUniqVisitors = (int) $dataRow->getColumn('nb_uniq_visitors');
     $nbVisits = (int) $dataRow->getColumn('nb_visits');
     $view->nbVisits = $nbVisits;
     $view->nbPageviews = (int) $dataActionsRow->getColumn('nb_pageviews');
     $view->nbUniquePageviews = (int) $dataActionsRow->getColumn('nb_uniq_pageviews');
     $view->nbDownloads = (int) $dataActionsRow->getColumn('nb_downloads');
     $view->nbUniqueDownloads = (int) $dataActionsRow->getColumn('nb_uniq_downloads');
     $view->nbOutlinks = (int) $dataActionsRow->getColumn('nb_outlinks');
     $view->nbUniqueOutlinks = (int) $dataActionsRow->getColumn('nb_uniq_outlinks');
     $view->averageVisitDuration = $dataRow->getColumn('avg_time_on_site');
     $nbBouncedVisits = $dataRow->getColumn('bounce_count');
     $view->bounceRate = Piwik::getPercentageSafe($nbBouncedVisits, $nbVisits);
     $view->maxActions = (int) $dataRow->getColumn('max_actions');
     $view->nbActionsPerVisit = $dataRow->getColumn('nb_actions_per_visit');
     if ($displaySiteSearch) {
         $view->nbSearches = (int) $dataActionsRow->getColumn('nb_searches');
         $view->nbKeywords = (int) $dataActionsRow->getColumn('nb_keywords');
     }
     // backward compatibility:
     // show actions if the finer metrics are not archived
     $view->showOnlyActions = false;
     if ($dataActionsRow->getColumn('nb_pageviews') + $dataActionsRow->getColumn('nb_downloads') + $dataActionsRow->getColumn('nb_outlinks') == 0 && $dataRow->getColumn('nb_actions') > 0) {
         $view->showOnlyActions = true;
         $view->nbActions = $dataRow->getColumn('nb_actions');
         $view->urlSparklineNbActions = $this->getUrlSparkline('getEvolutionGraph', array('columns' => array('nb_actions')));
     }
 }
示例#21
0
 /**
  * Sets general variables to the view that are used by
  * various templates and Javascript.
  * If any error happens, displays the login screen
  *
  * @param Piwik_View $view
  * @throws Exception
  * @return void
  */
 protected function setGeneralVariablesView($view)
 {
     $view->date = $this->strDate;
     try {
         $view->idSite = $this->idSite;
         if (empty($this->site) || empty($this->idSite)) {
             throw new Exception("The requested website idSite is not found in the request, or is invalid.\n\t\t\t\tPlease check that you are logged in Piwik and have permission to access the specified website.");
         }
         $this->setPeriodVariablesView($view);
         $rawDate = Piwik_Common::getRequestVar('date');
         $periodStr = Piwik_Common::getRequestVar('period');
         if ($periodStr != 'range') {
             $date = Piwik_Date::factory($this->strDate);
             $period = Piwik_Period::factory($periodStr, $date);
         } else {
             $period = new Piwik_Period_Range($periodStr, $rawDate, $this->site->getTimezone());
         }
         $view->rawDate = $rawDate;
         $view->prettyDate = self::getCalendarPrettyDate($period);
         $view->siteName = $this->site->getName();
         $view->siteMainUrl = $this->site->getMainUrl();
         $datetimeMinDate = $this->site->getCreationDate()->getDatetime();
         $minDate = Piwik_Date::factory($datetimeMinDate, $this->site->getTimezone());
         $this->setMinDateView($minDate, $view);
         $maxDate = Piwik_Date::factory('now', $this->site->getTimezone());
         $this->setMaxDateView($maxDate, $view);
         // Setting current period start & end dates, for pre-setting the calendar when "Date Range" is selected
         $dateStart = $period->getDateStart();
         if ($dateStart->isEarlier($minDate)) {
             $dateStart = $minDate;
         }
         $dateEnd = $period->getDateEnd();
         if ($dateEnd->isLater($maxDate)) {
             $dateEnd = $maxDate;
         }
         $view->startDate = $dateStart;
         $view->endDate = $dateEnd;
         $language = Piwik_LanguagesManager::getLanguageForSession();
         $view->language = !empty($language) ? $language : Piwik_LanguagesManager::getLanguageCodeForCurrentUser();
         $view->config_action_url_category_delimiter = Piwik_Config::getInstance()->General['action_url_category_delimiter'];
         $this->setBasicVariablesView($view);
         $view->topMenu = Piwik_GetTopMenu();
     } catch (Exception $e) {
         Piwik_ExitWithMessage($e->getMessage(), '');
     }
 }
示例#22
0
文件: Sms.php 项目: nnnnathann/piwik
    public function renderReport($processedReport)
    {
        $isGoalPluginEnabled = Piwik_Common::isGoalPluginEnabled();
        $prettyDate = $processedReport['prettyDate'];
        $reportData = $processedReport['reportData'];
        $evolutionMetrics = array();
        $multiSitesAPIMetrics = Piwik_MultiSites_API::getApiMetrics($enhanced = true);
        foreach ($multiSitesAPIMetrics as $metricSettings) {
            $evolutionMetrics[] = $metricSettings[Piwik_MultiSites_API::METRIC_EVOLUTION_COL_NAME_KEY];
        }
        // no decimal for all metrics to shorten SMS content (keeps the monetary sign for revenue metrics)
        $reportData->filter('ColumnCallbackReplace', array(array_merge(array_keys($multiSitesAPIMetrics), $evolutionMetrics), create_function('$value', '
					return preg_replace_callback (
						FLOAT_REGEXP,
						create_function (
							\'$matches\',
							\'return round($matches[0]);\'
						),
						$value
					);
					')));
        // evolution metrics formatting :
        //  - remove monetary, percentage and white spaces to shorten SMS content
        //    (this is also needed to be able to test $value != 0 and see if there is an evolution at all in SMSReport.tpl)
        //  - adds a plus sign
        $reportData->filter('ColumnCallbackReplace', array($evolutionMetrics, create_function('$value', '
					$matched = preg_match(FLOAT_REGEXP, $value, $matches);
					return $matched ? sprintf("%+d",$matches[0]) : $value;
					')));
        $dataRows = $reportData->getRows();
        $reportMetadata = $processedReport['reportMetadata'];
        $reportRowsMetadata = $reportMetadata->getRows();
        $siteHasECommerce = array();
        foreach ($reportRowsMetadata as $rowMetadata) {
            $idSite = $rowMetadata->getColumn('idsite');
            $siteHasECommerce[$idSite] = Piwik_Site::isEcommerceEnabledFor($idSite);
        }
        $smarty = new Piwik_Smarty();
        $smarty->assign("isGoalPluginEnabled", $isGoalPluginEnabled);
        $smarty->assign("reportRows", $dataRows);
        $smarty->assign("reportRowsMetadata", $reportRowsMetadata);
        $smarty->assign("prettyDate", $prettyDate);
        $smarty->assign("siteHasECommerce", $siteHasECommerce);
        $smarty->assign("displaySiteName", $processedReport['metadata']['action'] == 'getAll');
        $this->rendering .= $smarty->fetch(PIWIK_USER_PATH . '/plugins/MobileMessaging/templates/SMSReport.tpl');
    }
示例#23
0
 /**
  * Returns all Goals for a given website, or list of websites
  * 
  * @param string|array $idSite Array or Comma separated list of website IDs to request the goals for
  * @return array Array of Goal attributes
  */
 public function getGoals($idSite)
 {
     if (!is_array($idSite)) {
         $idSite = Piwik_Site::getIdSitesFromIdSitesString($idSite);
     }
     Piwik::checkUserHasViewAccess($idSite);
     $goals = Piwik_FetchAll("SELECT * \n\t\t\t\t\t\t\t\tFROM " . Piwik_Common::prefixTable('goal') . " \n\t\t\t\t\t\t\t\tWHERE idsite IN (" . implode(", ", $idSite) . ")\n\t\t\t\t\t\t\t\t\tAND deleted = 0");
     $cleanedGoals = array();
     foreach ($goals as &$goal) {
         if ($goal['match_attribute'] == 'manually') {
             unset($goal['pattern']);
             unset($goal['pattern_type']);
             unset($goal['case_sensitive']);
         }
         $cleanedGoals[$goal['idgoal']] = $goal;
     }
     return $cleanedGoals;
 }
示例#24
0
 /**
  * Resets all caches and drops the database
  */
 public function tearDown()
 {
     parent::tearDown();
     try {
         $plugins = Piwik_PluginsManager::getInstance()->getLoadedPlugins();
         foreach ($plugins as $plugin) {
             $plugin->uninstall();
         }
         Piwik_PluginsManager::getInstance()->unloadPlugins();
     } catch (Exception $e) {
     }
     Piwik::dropDatabase();
     Piwik_DataTable_Manager::getInstance()->deleteAll();
     Piwik_Option::getInstance()->clearCache();
     Piwik_Site::clearCache();
     Piwik_Common::deleteTrackerCache();
     Piwik_Config::getInstance()->clear();
     Piwik_TablePartitioning::$tablesAlreadyInstalled = null;
     Zend_Registry::_unsetInstance();
 }
示例#25
0
 /**
  * Returns all Goals for a given website, or list of websites
  * 
  * @param string|array $idSite Array or Comma separated list of website IDs to request the goals for
  * @return array Array of Goal attributes
  */
 public function getGoals($idSite)
 {
     //TODO calls to this function could be cached as static
     // would help UI at least, since some UI requests would call this 2-3 times..
     $idSite = Piwik_Site::getIdSitesFromIdSitesString($idSite);
     if (empty($idSite)) {
         return array();
     }
     Piwik::checkUserHasViewAccess($idSite);
     $goals = Piwik_FetchAll("SELECT * \n\t\t\t\t\t\t\t\tFROM " . Piwik_Common::prefixTable('goal') . " \n\t\t\t\t\t\t\t\tWHERE idsite IN (" . implode(", ", $idSite) . ")\n\t\t\t\t\t\t\t\t\tAND deleted = 0");
     $cleanedGoals = array();
     foreach ($goals as &$goal) {
         if ($goal['match_attribute'] == 'manually') {
             unset($goal['pattern']);
             unset($goal['pattern_type']);
             unset($goal['case_sensitive']);
         }
         $cleanedGoals[$goal['idgoal']] = $goal;
     }
     return $cleanedGoals;
 }
示例#26
0
文件: API.php 项目: nnnnathann/piwik
 /**
  * Generates a report file.
  *
  * @param int $idReport ID of the report to generate.
  * @param string $date YYYY-MM-DD
  * @param bool|false|string $language If not passed, will use default language.
  * @param bool|false|int $outputType 1 = download report, 2 = save report to disk, 3 = output report in browser, 4 = return report content to caller, defaults to download
  * @param bool|false|string $period Defaults to 'day'. If not specified, will default to the report's period set when creating the report
  * @param bool|false|string $reportFormat 'pdf', 'html' or any other format provided via the PDFReports.getReportFormats hook
  * @param bool|false|array $parameters array of parameters
  * @return array|void
  */
 public function generateReport($idReport, $date, $language = false, $outputType = false, $period = false, $reportFormat = false, $parameters = false)
 {
     Piwik::checkUserIsNotAnonymous();
     // load specified language
     if (empty($language)) {
         $language = Piwik_Translate::getInstance()->getLanguageDefault();
     }
     Piwik_Translate::getInstance()->reloadLanguage($language);
     $reports = $this->getReports($idSite = false, $_period = false, $idReport);
     $report = reset($reports);
     $idSite = $report['idsite'];
     $reportType = $report['type'];
     // override report period
     if (empty($period)) {
         $period = $report['period'];
     }
     // override report format
     if (!empty($reportFormat)) {
         self::validateReportFormat($reportType, $reportFormat);
         $report['format'] = $reportFormat;
     } else {
         $reportFormat = $report['format'];
     }
     // override report parameters
     if (!empty($parameters)) {
         $report['parameters'] = Piwik_Common::json_decode(self::validateReportParameters($reportType, $parameters), true);
     } else {
         $parameters = $report['parameters'];
     }
     // decode report list
     $reportUniqueIds = $report['reports'];
     // available reports
     $availableReportMetadata = Piwik_API_API::getInstance()->getReportMetadata($idSite);
     // we need to lookup which reports metadata are registered in this report
     $reportMetadata = array();
     foreach ($availableReportMetadata as $metadata) {
         if (in_array($metadata['uniqueId'], $reportUniqueIds)) {
             $reportMetadata[] = $metadata;
         }
     }
     // the report will be rendered with the first 23 rows and will aggregate other rows in a summary row
     // 23 rows table fits in one portrait page
     $initialFilterTruncate = Piwik_Common::getRequestVar('filter_truncate', false);
     $_GET['filter_truncate'] = self::REPORT_TRUNCATE;
     $prettyDate = null;
     $processedReports = array();
     foreach ($reportMetadata as $action) {
         $apiModule = $action['module'];
         $apiAction = $action['action'];
         $apiParameters = array();
         if (isset($action['parameters'])) {
             $apiParameters = $action['parameters'];
         }
         $mustRestoreGET = false;
         // all Websites dashboard should not be truncated in the report
         if ($apiModule == 'MultiSites') {
             $mustRestoreGET = $_GET;
             $_GET['enhanced'] = true;
             if ($apiAction == 'getAll') {
                 $_GET['filter_truncate'] = false;
                 // when a view/admin user created a report, workaround the fact that "Super User"
                 // is enforced in Scheduled tasks, and ensure Multisites.getAll only return the websites that this user can access
                 if (!empty($userLogin) && $userLogin != Piwik_Config::getInstance()->superuser['login']) {
                     $_GET['_restrictSitesToLogin'] = $userLogin;
                 }
             }
         }
         $processedReport = Piwik_API_API::getInstance()->getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters, $idGoal = false, $language);
         // TODO add static method getPrettyDate($period, $date) in Piwik_Period
         $prettyDate = $processedReport['prettyDate'];
         if ($mustRestoreGET) {
             $_GET = $mustRestoreGET;
         }
         $processedReports[] = $processedReport;
     }
     // restore filter truncate parameter value
     if ($initialFilterTruncate !== false) {
         $_GET['filter_truncate'] = $initialFilterTruncate;
     }
     $notificationInfo = array(self::REPORT_TYPE_INFO_KEY => $reportType, self::REPORT_KEY => $report);
     // allow plugins to alter processed reports
     Piwik_PostEvent(self::PROCESS_REPORTS_EVENT, $processedReports, $notificationInfo);
     // retrieve report renderer instance
     $reportRenderer = null;
     Piwik_PostEvent(self::GET_RENDERER_INSTANCE_EVENT, $reportRenderer, $notificationInfo);
     // init report renderer
     $reportRenderer->setLocale($language);
     $reportRenderer->setRenderImageInline($outputType != self::OUTPUT_SAVE_ON_DISK);
     // render report
     $websiteName = Piwik_Site::getNameFor($idSite);
     $description = str_replace(array("\r", "\n"), ' ', $report['description']);
     $reportRenderer->renderFrontPage($websiteName, $prettyDate, $description, $reportMetadata);
     array_walk($processedReports, array($reportRenderer, 'renderReport'));
     switch ($outputType) {
         case self::OUTPUT_SAVE_ON_DISK:
             $outputFilename = strtoupper($reportFormat) . ' ' . ucfirst($reportType) . ' Report - ' . $idReport . '.' . $date . '.' . $idSite . '.' . $language;
             $outputFilename = $reportRenderer->sendToDisk($outputFilename);
             $additionalFiles = array();
             if ($reportRenderer instanceof Piwik_ReportRenderer_Html) {
                 foreach ($processedReports as &$report) {
                     if ($report['displayGraph']) {
                         $additionalFile = array();
                         $additionalFile['filename'] = $report['metadata']['name'] . '.png';
                         $additionalFile['cid'] = $report['metadata']['uniqueId'];
                         $additionalFile['content'] = Piwik_ReportRenderer::getStaticGraph($report['metadata']['imageGraphUrl'], Piwik_ReportRenderer_Html::IMAGE_GRAPH_WIDTH, Piwik_ReportRenderer_Html::IMAGE_GRAPH_HEIGHT);
                         $additionalFile['mimeType'] = 'image/png';
                         $additionalFile['encoding'] = Zend_Mime::ENCODING_BASE64;
                         $additionalFiles[] = $additionalFile;
                     }
                 }
             }
             return array($outputFilename, $prettyDate, $websiteName, $additionalFiles);
             break;
         case self::OUTPUT_INLINE:
             $reportRenderer->sendToBrowserInline("{$websiteName} - {$prettyDate} - {$description}");
             break;
         case self::OUTPUT_RETURN:
             return $reportRenderer->getRenderedReport();
             break;
         default:
         case self::OUTPUT_DOWNLOAD:
             $reportRenderer->sendToBrowserDownload("{$websiteName} - {$prettyDate} - {$description}");
             break;
     }
 }
示例#27
0
 /**
  * Inits the object
  */
 protected function loadArchiveProperties()
 {
     $this->idsite = $this->site->getId();
     $this->periodId = $this->period->getId();
     $this->dateStart = $this->period->getDateStart();
     $this->dateEnd = $this->period->getDateEnd();
     $this->tableArchiveNumeric = new Piwik_TablePartitioning_Monthly('archive_numeric');
     $this->tableArchiveNumeric->setIdSite($this->idsite);
     $this->tableArchiveNumeric->setTimestamp($this->dateStart->get());
     $this->tableArchiveBlob = new Piwik_TablePartitioning_Monthly('archive_blob');
     $this->tableArchiveBlob->setIdSite($this->idsite);
     $this->tableArchiveBlob->setTimestamp($this->dateStart->get());
     $this->strDateStart = $this->dateStart->toString();
     $this->strDateEnd = $this->dateEnd->toString();
     // if the current archive is a DAY and if it's today,
     // we set this maxTimestampArchive that defines the lifetime value of today's archive
     $this->maxTimestampArchive = 0;
     if ($this->period->getNumberOfSubperiods() == 0 && $this->period->toString() == date("Y-m-d")) {
         $this->maxTimestampArchive = time() - Zend_Registry::get('config')->General->time_before_today_archive_considered_outdated;
         $browserArchivingEnabled = Zend_Registry::get('config')->General->enable_browser_archiving_triggering;
         // see #1150; if new archives are not triggered from the browser,
         // we still want to try and return the latest archive available for today (rather than return nothing)
         if (!$browserArchivingEnabled) {
             $this->maxTimestampArchive = 0;
         }
     } else {
         if ($this->period->isFinished()) {
             $this->maxTimestampArchive = $this->period->getDateEnd()->setTime('00:00:00')->addDay(1)->getTimestamp();
         } else {
             $this->maxTimestampArchive = Piwik_Date::today()->getTimestamp();
         }
     }
     $db = Zend_Registry::get('db');
     $this->compressBlob = $db->hasBlobDataType();
 }
示例#28
0
文件: API.php 项目: nnnnathann/piwik
 /**
  * Set an access level to a given user for a list of websites ID.
  * 
  * If access = 'noaccess' the current access (if any) will be deleted.
  * If access = 'view' or 'admin' the current access level is deleted and updated with the new value.
  *
  * @param string $userLogin The user login
  * @param string $access Access to grant. Must have one of the following value : noaccess, view, admin
  * @param int|array $idSites The array of idSites on which to apply the access level for the user.
  *       If the value is "all" then we apply the access level to all the websites ID for which the current authentificated user has an 'admin' access.
  * 
  * @throws Exception if the user doesn't exist
  * @throws Exception if the access parameter doesn't have a correct value
  * @throws Exception if any of the given website ID doesn't exist
  * 
  * @return bool true on success
  */
 public function setUserAccess($userLogin, $access, $idSites)
 {
     $this->checkAccessType($access);
     $this->checkUserExists($userLogin);
     $this->checkUserIsNotSuperUser($userLogin);
     if ($userLogin == 'anonymous' && $access == 'admin') {
         throw new Exception(Piwik_TranslateException("UsersManager_ExceptionAdminAnonymous"));
     }
     // in case idSites is null we grant access to all the websites on which the current connected user
     // has an 'admin' access
     if ($idSites === 'all') {
         $idSites = Piwik_SitesManager_API::getInstance()->getSitesIdWithAdminAccess();
     } elseif (!is_array($idSites)) {
         $idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites);
     }
     // it is possible to set user access on websites only for the websites admin
     // basically an admin can give the view or the admin access to any user for the websites he manages
     Piwik::checkUserHasAdminAccess($idSites);
     $this->deleteUserAccess($userLogin, $idSites);
     // delete UserAccess
     $db = Zend_Registry::get('db');
     // if the access is noaccess then we don't save it as this is the default value
     // when no access are specified
     if ($access != 'noaccess') {
         foreach ($idSites as $idsite) {
             $db->insert(Piwik_Common::prefixTable("access"), array("idsite" => $idsite, "login" => $userLogin, "access" => $access));
         }
     }
     // we reload the access list which doesn't yet take in consideration this new user access
     Zend_Registry::get('access')->reloadAccess();
     Piwik_Common::deleteTrackerCache();
 }
示例#29
0
	/**
	 * This method checks that the user has VIEW or ADMIN access for the given list of websites.
	 * If the user doesn't have VIEW or ADMIN access for at least one website of the list, we throw an exception.
	 * 
	 * @param int|arrayOfIntegers|string List of ID sites to check (integer, array of integers, string comma separated list of integers)
	 * @throws Exception If for any of the websites the user doesn't have an VIEW or ADMIN access
	 */
	public function checkUserHasViewAccess( $idSites )
	{
		if($idSites === 'all')
		{
			$idSites = $this->getSitesIdWithAtLeastViewAccess();
		}
		
		if(!is_array($idSites))
		{
			$idSites = Piwik_Site::getIdSitesFromIdSitesString($idSites);
		}
		$idSitesAccessible = $this->getSitesIdWithAtLeastViewAccess();

		foreach($idSites as $idsite)
		{
			if(!in_array($idsite, $idSitesAccessible))
			{
				throw new Piwik_Access_NoAccessException("You can't access this resource as it requires a 'view' access for the website id = $idsite.");
			}
		}
	}
示例#30
0
 public function getProcessedReport($idSite, $period, $date, $apiModule, $apiAction, $segment = false, $apiParameters = false, $idGoal = false, $language = false, $showTimer = true)
 {
     $timer = new Piwik_Timer();
     if ($apiParameters === false) {
         $apiParameters = array();
     }
     if (!empty($idGoal) && empty($apiParameters['idGoal'])) {
         $apiParameters['idGoal'] = $idGoal;
     }
     // Is this report found in the Metadata available reports?
     $reportMetadata = $this->getMetadata($idSite, $apiModule, $apiAction, $apiParameters, $language, $period, $date);
     if (empty($reportMetadata)) {
         throw new Exception("Requested report {$apiModule}.{$apiAction} for Website id={$idSite} not found in the list of available reports. \n");
     }
     $reportMetadata = reset($reportMetadata);
     // Generate Api call URL passing custom parameters
     $parameters = array_merge($apiParameters, array('method' => $apiModule . '.' . $apiAction, 'idSite' => $idSite, 'period' => $period, 'date' => $date, 'format' => 'original', 'serialize' => '0', 'language' => $language));
     if (!empty($segment)) {
         $parameters['segment'] = $segment;
     }
     $url = Piwik_Url::getQueryStringFromParameters($parameters);
     $request = new Piwik_API_Request($url);
     try {
         /** @var Piwik_DataTable */
         $dataTable = $request->process();
     } catch (Exception $e) {
         throw new Exception("API returned an error: " . $e->getMessage() . "\n");
     }
     list($newReport, $columns, $rowsMetadata) = $this->handleTableReport($idSite, $dataTable, $reportMetadata, isset($reportMetadata['dimension']));
     foreach ($columns as $columnId => &$name) {
         $name = ucfirst($name);
     }
     $website = new Piwik_Site($idSite);
     //    	$segment = new Piwik_Segment($segment, $idSite);
     if (Piwik_Archive::isMultiplePeriod($date, $period)) {
         $period = new Piwik_Period_Range($period, $date);
     } else {
         if ($period == 'range') {
             $period = new Piwik_Period_Range($period, $date);
         } else {
             $period = Piwik_Period::factory($period, Piwik_Date::factory($date));
         }
     }
     $period = $period->getLocalizedLongString();
     $return = array('website' => $website->getName(), 'prettyDate' => $period, 'metadata' => $reportMetadata, 'columns' => $columns, 'reportData' => $newReport, 'reportMetadata' => $rowsMetadata);
     if ($showTimer) {
         $return['timerMillis'] = $timer->getTimeMs(0);
     }
     return $return;
 }