Esempio n. 1
0
 /**
  * Parse this page
  *
  * @return	void
  */
 protected function parse()
 {
     // call parent parse
     parent::parse();
     // get results
     $results = BackendAnalyticsModel::getLandingPages($this->startTimestamp, $this->endTimestamp);
     // there are some results
     if (!empty($results)) {
         // get the datagrid
         $dataGrid = new BackendDataGridArray($results);
         // hide columns
         $dataGrid->setColumnsHidden('start_date', 'end_date', 'updated_on', 'page_encoded');
         // set headers values
         $headers['page_path'] = ucfirst(BL::lbl('Page'));
         // set headers
         $dataGrid->setHeaderLabels($headers);
         // set url
         $dataGrid->setColumnURL('page_path', BackendModel::createURLForAction('detail_page') . '&page=[page_encoded]');
         // add the multicheckbox column
         $dataGrid->setMassActionCheckboxes('checkbox', '[id]');
         // add mass action dropdown
         $ddmMassAction = new SpoonFormDropdown('action', array('delete_landing_page' => BL::lbl('Delete')), 'delete');
         $dataGrid->setMassAction($ddmMassAction);
         // parse the datagrid
         $this->tpl->assign('dgPages', $dataGrid->getContent());
     }
 }
 /**
  * Parse into template
  */
 private function parseReferrers()
 {
     $results = BackendAnalyticsModel::getRecentReferrers();
     if (!empty($results)) {
         $dataGrid = new BackendDataGridArray($results);
         $dataGrid->setPaging();
         $dataGrid->setColumnsHidden('id', 'date', 'url');
         $dataGrid->setColumnURL('referrer', '[url]');
     }
     // parse the datagrid
     return !empty($results) ? $dataGrid->getContent() : '<table class="dataGrid"><tr><td>' . BL::msg('NoReferrers') . '</td></tr></table>';
 }
Esempio n. 3
0
 /**
  * Parse into template
  *
  * @return	void
  */
 private function parse()
 {
     // init vars
     $maxYAxis = 2;
     $metrics = array('visitors', 'pageviews');
     $graphData = array();
     $startTimestamp = strtotime('-1 week -1 days', mktime(0, 0, 0));
     $endTimestamp = mktime(0, 0, 0);
     // get dashboard data
     $dashboardData = BackendAnalyticsModel::getDashboardData($metrics, $startTimestamp, $endTimestamp, true);
     // there are some metrics
     if ($dashboardData !== false) {
         // loop metrics
         foreach ($metrics as $i => $metric) {
             // build graph data array
             $graphData[$i] = array();
             $graphData[$i]['title'] = $metric;
             $graphData[$i]['label'] = ucfirst(BL::lbl(SpoonFilter::toCamelCase($metric)));
             $graphData[$i]['i'] = $i + 1;
             $graphData[$i]['data'] = array();
             // loop metrics per day
             foreach ($dashboardData as $j => $data) {
                 // cast SimpleXMLElement to array
                 $data = (array) $data;
                 // build array
                 $graphData[$i]['data'][$j]['date'] = (int) $data['timestamp'];
                 $graphData[$i]['data'][$j]['value'] = (string) $data[$metric];
             }
         }
     }
     // loop the metrics
     foreach ($graphData as $metric) {
         // loop the data
         foreach ($metric['data'] as $data) {
             // get the maximum value
             if ((int) $data['value'] > $maxYAxis) {
                 $maxYAxis = (int) $data['value'];
             }
         }
     }
     // parse
     $this->tpl->assign('analyticsRecentVisitsStartDate', $startTimestamp);
     $this->tpl->assign('analyticsRecentVisitsEndDate', $endTimestamp);
     $this->tpl->assign('analyticsMaxYAxis', $maxYAxis);
     $this->tpl->assign('analyticsMaxYAxis', $maxYAxis);
     $this->tpl->assign('analyticsTickInterval', $maxYAxis == 2 ? '1' : '');
     $this->tpl->assign('analyticsGraphData', $graphData);
 }
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     $action = SpoonFilter::getGetValue('action', array('delete'), 'delete');
     // no id's provided
     if (!isset($_GET['id'])) {
         $this->redirect(BackendModel::createURLForAction('landing_pages') . '&error=no-items-selected');
     } else {
         // delete items
         if ($action == 'delete') {
             BackendAnalyticsModel::deleteLandingPage((array) $_GET['id']);
         }
     }
     // redirect
     $this->redirect(BackendModel::createURLForAction('landing_pages') . '&report=' . $action);
 }
 /**
  * Execute the action
  */
 public function execute()
 {
     parent::execute();
     // fork is no longer authorized to collect analytics data
     if (BackendAnalyticsHelper::getStatus() == 'UNAUTHORIZED') {
         // remove all parameters from the module settings
         BackendModel::setModuleSetting('analytics', 'session_token', null);
         BackendModel::setModuleSetting('analytics', 'account_name', null);
         BackendModel::setModuleSetting('analytics', 'table_id', null);
         BackendModel::setModuleSetting('analytics', 'profile_title', null);
         BackendAnalyticsModel::removeCacheFiles();
         BackendAnalyticsModel::clearTables();
         return;
     }
     $this->getData();
 }
 /**
  * Execute the action
  */
 public function execute()
 {
     $this->id = $this->getParameter('id', 'int');
     // does the item exist
     if ($this->id !== null && BackendAnalyticsModel::existsLandingPage($this->id)) {
         parent::execute();
         $this->record = (array) BackendAnalyticsModel::getLandingPage($this->id);
         // delete item
         BackendAnalyticsModel::deleteLandingPage($this->id);
         // trigger event
         BackendModel::triggerEvent($this->getModule(), 'after_delete_landing_page', array('id' => $this->id));
         // item was deleted, so redirect
         $this->redirect(BackendModel::createURLForAction('index') . '&report=deleted&var=' . urlencode($this->record['page_path']));
     } else {
         $this->redirect(BackendModel::createURLForAction('index') . '&error=non-existing');
     }
 }
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // action to execute
     $action = SpoonFilter::getGetValue('action', array('delete'), 'delete');
     // no id's provided
     if (!isset($_GET['id'])) {
         $this->redirect(BackendModel::createURLForAction('landing_pages') . '&error=no-items-selected');
     } else {
         // redefine id's
         $ids = (array) $_GET['id'];
         // delete items
         if ($action == 'delete') {
             BackendAnalyticsModel::deleteLandingPage($ids);
         }
     }
     // redirect
     $this->redirect(BackendModel::createURLForAction('landing_pages') . '&report=' . $action);
 }
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // fork is no longer authorized to collect analytics data
     if (BackendAnalyticsHelper::getStatus() == 'UNAUTHORIZED') {
         // remove all parameters from the module settings
         BackendModel::setModuleSetting('analytics', 'session_token', null);
         BackendModel::setModuleSetting('analytics', 'account_name', null);
         BackendModel::setModuleSetting('analytics', 'table_id', null);
         BackendModel::setModuleSetting('analytics', 'profile_title', null);
         // remove cache files
         BackendAnalyticsModel::removeCacheFiles();
         // clear tables
         BackendAnalyticsModel::clearTables();
         // stop here
         return;
     }
     // get data
     $this->getData();
 }
Esempio n. 9
0
 /**
  * Parse this page
  */
 protected function parse()
 {
     parent::parse();
     $results = BackendAnalyticsModel::getLandingPages($this->startTimestamp, $this->endTimestamp);
     if (!empty($results)) {
         $dataGrid = new BackendDataGridArray($results);
         $dataGrid->setColumnsHidden('start_date', 'end_date', 'updated_on', 'page_encoded');
         $dataGrid->setMassActionCheckboxes('checkbox', '[id]');
         // check if this action is allowed
         if (BackendAuthentication::isAllowedAction('detail_page', $this->getModule())) {
             $dataGrid->setColumnURL('page_path', BackendModel::createURLForAction('detail_page') . '&amp;page=[page_encoded]');
         }
         // set headers
         $dataGrid->setHeaderLabels(array('page_path' => SpoonFilter::ucfirst(BL::lbl('Page'))));
         // add mass action dropdown
         $ddmMassAction = new SpoonFormDropdown('action', array('delete_landing_page' => BL::lbl('Delete')), 'delete');
         $dataGrid->setMassAction($ddmMassAction);
         // parse the datagrid
         $this->tpl->assign('dgPages', $dataGrid->getContent());
     }
 }
Esempio n. 10
0
 /**
  * Parse the referrers datagrid
  */
 private function parseReferrers()
 {
     $results = BackendAnalyticsModel::getRecentReferrers();
     if (!empty($results)) {
         $dataGrid = new BackendDataGridArray($results);
         $dataGrid->setPaging(false);
         $dataGrid->setColumnsHidden('id', 'date', 'url');
         $dataGrid->setColumnURL('referrer', '[url]');
         // parse the datagrid
         $this->tpl->assign('dgAnalyticsReferrers', $dataGrid->getContent());
     }
 }
Esempio n. 11
0
 /**
  * Execute the action
  *
  * @return	void
  */
 public function execute()
 {
     // call parent, this will probably add some general CSS/JS or other required files
     parent::execute();
     // get parameters
     $page = trim(SpoonFilter::getPostValue('page', null, ''));
     $identifier = trim(SpoonFilter::getPostValue('identifier', null, ''));
     // validate
     if ($page == '' || $identifier == '') {
         $this->output(self::BAD_REQUEST, null, 'No page provided.');
     }
     // init vars
     $filename = BACKEND_CACHE_PATH . '/analytics/' . $page . '_' . $identifier . '.txt';
     // does the temporary file still exits?
     $status = SpoonFile::getContent($filename);
     // no file - create one
     if ($status === false) {
         // create file with initial counter
         SpoonFile::setContent($filename, 'missing1');
         // return status
         $this->output(self::OK, array('status' => false), 'Temporary file was missing. We created one.');
     }
     // busy status
     if (strpos($status, 'busy') !== false) {
         // get counter
         $counter = (int) substr($status, 4) + 1;
         // file's been busy for more than hundred cycles - just stop here
         if ($counter > 100) {
             // remove file
             SpoonFile::delete($filename);
             // return status
             $this->output(self::ERROR, array('status' => 'timeout'), 'Error while retrieving data - the script took too long to retrieve data.');
         }
         // change file content to increase counter
         SpoonFile::setContent($filename, 'busy' . $counter);
         // return status
         $this->output(self::OK, array('status' => 'busy'), 'Data is being retrieved. (' . $counter . ')');
     }
     // unauthorized status
     if ($status == 'unauthorized') {
         // remove file
         SpoonFile::delete($filename);
         // remove all parameters from the module settings
         BackendModel::setModuleSetting($this->getModule(), 'session_token', null);
         BackendModel::setModuleSetting($this->getModule(), 'account_name', null);
         BackendModel::setModuleSetting($this->getModule(), 'table_id', null);
         BackendModel::setModuleSetting($this->getModule(), 'profile_title', null);
         // remove cache files
         BackendAnalyticsModel::removeCacheFiles();
         // clear tables
         BackendAnalyticsModel::clearTables();
         // return status
         $this->output(self::OK, array('status' => 'unauthorized'), 'No longer authorized.');
     }
     // done status
     if ($status == 'done') {
         // remove file
         SpoonFile::delete($filename);
         // return status
         $this->output(self::OK, array('status' => 'done'), 'Data retrieved.');
     }
     // missing status
     if (strpos($status, 'missing') !== false) {
         // get counter
         $counter = (int) substr($status, 7) + 1;
         // file's been missing for more than ten cycles - just stop here
         if ($counter > 10) {
             // remove file
             SpoonFile::delete($filename);
             // return status
             $this->output(self::ERROR, array('status' => 'missing'), 'Error while retrieving data - file was never created.');
         }
         // change file content to increase counter
         SpoonFile::setContent($filename, 'missing' . $counter);
         // return status
         $this->output(self::OK, array('status' => 'busy'), 'Temporary file was still in status missing. (' . $counter . ')');
     }
     /* FALLBACK - SOMETHING WENT WRONG */
     // remove file
     SpoonFile::delete($filename);
     // return status
     $this->output(self::ERROR, array('status' => 'error'), 'Error while retrieving data.');
 }
Esempio n. 12
0
    /**
     * Get all needed metrics for certain dates
     *
     * @return	array
     * @param	int $pageId			The id of the page to collect data from.
     * @param	int $startTimestamp		The start timestamp for the google call.
     * @param	int $endTimestamp		The end timestamp for the google call.
     */
    public static function getDataForPage($pageId, $startTimestamp, $endTimestamp)
    {
        // get page
        $page = BackendModel::getDB(false)->getVar('SELECT page
													FROM analytics_pages
													WHERE id = ?', array((int) $pageId));
        // init vars
        $data = array();
        $data['hostname'] = SITE_URL;
        $data['aggregates'] = array();
        $data['metrics_per_day'] = array();
        $data['sources'] = array();
        $data['sources_grouped'] = array();
        // get metrics and dimensions
        $metrics = 'ga:visits';
        $dimensions = 'ga:hostname';
        // get parameters
        $parameters = array();
        $parameters['max-results'] = 1;
        $parameters['sort'] = '-ga:visits';
        // get results
        $results = self::getGoogleAnalyticsInstance()->getAnalyticsResults($metrics, mktime(0, 0, 0, 1, 1, 2005), $endTimestamp, $dimensions, $parameters);
        // loop page results and add hostname to data array
        foreach ($results['entries'] as $result) {
            $data['hostname'] = $result['hostname'];
        }
        // get metrics
        $metrics = array('bounces', 'entrances', 'exits', 'newVisits', 'pageviews', 'timeOnPage', 'timeOnSite', 'visits');
        $gaMetrics = array();
        foreach ($metrics as $metric) {
            $gaMetrics[] = 'ga:' . $metric;
        }
        // get dimensions
        $dimensions = 'ga:date';
        // get parameters
        $parameters = array();
        $parameters['filters'] = 'ga:pagePath==' . $page;
        // get results
        $results = self::getGoogleAnalyticsInstance()->getAnalyticsResults($gaMetrics, $startTimestamp, $endTimestamp, $dimensions, $parameters);
        // get aggregates
        $data['aggregates'] = $results['aggregates'];
        // loop page results
        foreach ($results['entries'] as $result) {
            // get timestamp
            $timestamp = gmmktime(12, 0, 0, substr($result['date'], 4, 2), substr($result['date'], 6, 2), substr($result['date'], 0, 4));
            // store metrics in correct format
            $entry = array();
            $entry['timestamp'] = $timestamp;
            // loop metrics
            foreach ($metrics as $metric) {
                $entry[$metric] = (int) $result[$metric];
            }
            // add to entries array
            $data['metrics_per_day'][] = $entry;
        }
        // get metrics
        $metrics = array('bounces', 'entrances', 'exits', 'newVisits', 'pageviews', 'timeOnPage', 'timeOnSite', 'visits');
        $gaMetrics = array();
        foreach ($metrics as $metric) {
            $gaMetrics[] = 'ga:' . $metric;
        }
        // get dimensions
        $dimensions = array('ga:source', 'ga:referralPath', 'ga:keyword');
        // get parameters
        $parameters = array();
        $parameters['max-results'] = 50;
        $parameters['filters'] = 'ga:pagePath==' . $page . ';ga:pageviews>0';
        $parameters['sort'] = '-ga:pageviews';
        // get results
        $results = self::getGoogleAnalyticsInstance()->getAnalyticsResults($gaMetrics, $startTimestamp, $endTimestamp, $dimensions, $parameters);
        // loop page results
        foreach ($results['entries'] as $result) {
            // store dimension in correct format
            $entry = array();
            if ($result['keyword'] != '(not set)') {
                $entry['source'] = $result['keyword'];
            } elseif ($result['source'] == '(direct)') {
                $entry['source'] = BL::lbl('DirectTraffic');
            } elseif ($result['referralPath'] != '(not set)') {
                $entry['source'] = $result['source'] . $result['referralPath'];
            } else {
                $entry['source'] = $result['source'];
            }
            // get metrics
            $entry['pageviews'] = (int) $result['pageviews'];
            $entry['pages_per_visit'] = $result['visits'] == 0 ? 0 : number_format((int) $result['pageviews'] / $result['visits'], 2);
            $entry['time_on_site'] = BackendAnalyticsModel::getTimeFromSeconds($result['entrances'] == 0 ? 0 : number_format((int) $result['timeOnSite'] / $result['entrances'], 2));
            $entry['new_visits'] = ($result['visits'] == 0 ? 0 : number_format((int) $result['newVisits'] / $result['visits'] * 100, 2)) . '%';
            $entry['bounce_rate'] = ($result['entrances'] == 0 ? 0 : number_format((int) $result['bounces'] / $result['entrances'] * 100, 2)) . '%';
            // add to entries array
            $data['sources'][] = $entry;
        }
        // set parameters
        $parameters = array();
        $parameters['filters'] = 'ga:pagePath==' . $page;
        $parameters['sort'] = '-ga:pageviews';
        // get results for sources grouped
        $results = self::getGoogleAnalyticsInstance()->getAnalyticsResults('ga:pageviews', $startTimestamp, $endTimestamp, 'ga:medium', $parameters);
        // get total pageviews
        $totalPageviews = isset($results['aggregates']['pageviews']) ? (int) $results['aggregates']['pageviews'] : 0;
        // loop entries
        foreach ($results['entries'] as $i => $result) {
            // add to sources array
            $data['sources_grouped'][$i]['label'] = $result['medium'];
            $data['sources_grouped'][$i]['value'] = $result['pageviews'];
            $data['sources_grouped'][$i]['percentage'] = ($totalPageviews == 0 ? 0 : number_format((int) $result['pageviews'] / $totalPageviews * 100, 2)) . '%';
        }
        // return metrics
        return $data;
    }
Esempio n. 13
0
 /**
  * Parse this page
  */
 protected function parse()
 {
     parent::parse();
     $page = $this->pageId != '' ? BackendAnalyticsModel::getPageForId($this->pageId) : null;
     // update date_viewed for this page
     BackendAnalyticsModel::updatePageDateViewed($this->pageId);
     // parse redirect link
     $this->tpl->assign('redirectGet', isset($page) ? 'page=' . $page : '');
     $this->tpl->assign('page', $this->redirectAction);
     $this->tpl->assign('identifier', ($this->pageId != '' ? $this->pageId . '_' : '') . $this->identifier);
     // check if this action is allowed
     if (BackendAuthentication::isAllowedAction($this->redirectAction, $this->getModule())) {
         $this->tpl->assign('redirect', BackendModel::createURLForAction($this->redirectAction));
     }
     // check if this action is allowed
     if (BackendAuthentication::isAllowedAction('settings', $this->getModule())) {
         $this->tpl->assign('settingsUrl', BackendModel::createURLForAction('settings'));
     }
 }
Esempio n. 14
0
 /**
  * Parses the overview data
  *
  * @param array $results The aggregates for the selected period.
  */
 private function parseOverviewData($results)
 {
     // get total aggregates
     $resultsTotal = BackendAnalyticsModel::getAggregatesTotal($this->startTimestamp, $this->endTimestamp);
     // are there some values?
     $dataAvailable = false;
     foreach ($resultsTotal as $data) {
         if ($data != 0) {
             $dataAvailable = true;
         }
     }
     // show message if there is no data
     $this->tpl->assign('dataAvailable', $dataAvailable);
     if (!empty($results)) {
         // time on page values
         $timeOnPage = $results['pageviews'] - $results['exits'] == 0 ? 0 : $results['timeOnPage'] / ($results['pageviews'] - $results['exits']);
         $timeOnPageTotal = $results['pageviews'] - $results['exits'] == 0 ? 0 : $resultsTotal['timeOnPage'] / ($resultsTotal['pageviews'] - $resultsTotal['exits']);
         $timeOnPageDifference = $timeOnPageTotal == 0 ? 0 : number_format(($timeOnPage - $timeOnPageTotal) / $timeOnPageTotal * 100, 0);
         if ($timeOnPageDifference > 0) {
             $timeOnPageDifference = '+' . $timeOnPageDifference;
         }
         // pages / visit
         $pagesPerVisit = $results['visits'] == 0 ? 0 : number_format($results['pageviews'] / $results['visits'], 2);
         $pagesPerVisitTotal = $resultsTotal['visits'] == 0 ? 0 : number_format($resultsTotal['pageviews'] / $resultsTotal['visits'], 2);
         $pagesPerVisitDifference = $pagesPerVisitTotal == 0 ? 0 : number_format(($pagesPerVisit - $pagesPerVisitTotal) / $pagesPerVisitTotal * 100, 0);
         if ($pagesPerVisitDifference > 0) {
             $pagesPerVisitDifference = '+' . $pagesPerVisitDifference;
         }
         // new visits
         $newVisits = $results['entrances'] == 0 ? 0 : number_format($results['newVisits'] / $results['entrances'] * 100, 0);
         $newVisitsTotal = $resultsTotal['entrances'] == 0 ? 0 : number_format($resultsTotal['newVisits'] / $resultsTotal['entrances'] * 100, 0);
         $newVisitsDifference = $newVisitsTotal == 0 ? 0 : number_format(($newVisits - $newVisitsTotal) / $newVisitsTotal * 100, 0);
         if ($newVisitsDifference > 0) {
             $newVisitsDifference = '+' . $newVisitsDifference;
         }
         // bounces
         $bounces = $results['entrances'] == 0 ? 0 : number_format($results['bounces'] / $results['entrances'] * 100, 0);
         $bouncesTotal = $resultsTotal['entrances'] == 0 ? 0 : number_format($resultsTotal['bounces'] / $resultsTotal['entrances'] * 100, 0);
         $bouncesDifference = $bouncesTotal == 0 ? 0 : number_format(($bounces - $bouncesTotal) / $bouncesTotal * 100, 0);
         if ($bouncesDifference > 0) {
             $bouncesDifference = '+' . $bouncesDifference;
         }
         $this->tpl->assign('pageviews', $results['pageviews']);
         $this->tpl->assign('visits', $results['visits']);
         $this->tpl->assign('pagesPerVisit', $pagesPerVisit);
         $this->tpl->assign('pagesPerVisitDifference', $pagesPerVisitDifference);
         $this->tpl->assign('timeOnPage', BackendAnalyticsModel::getTimeFromSeconds($timeOnPage));
         $this->tpl->assign('timeOnPageTotal', BackendAnalyticsModel::getTimeFromSeconds($timeOnPageTotal));
         $this->tpl->assign('timeOnPageDifference', $timeOnPageDifference);
         $this->tpl->assign('newVisits', $newVisits);
         $this->tpl->assign('newVisitsDifference', $newVisitsDifference);
         $this->tpl->assign('bounces', $bounces);
         $this->tpl->assign('bouncesDifference', $bouncesDifference);
     }
 }
Esempio n. 15
0
 /**
  * Gets all the needed parameters to link a google analytics account to fork
  */
 private function getAnalyticsParameters()
 {
     $remove = SpoonFilter::getGetValue('remove', array('session_token', 'table_id'), null);
     // something has to be removed before proceeding
     if (!empty($remove)) {
         // the session token has te be removed
         if ($remove == 'session_token') {
             // remove all parameters from the module settings
             BackendModel::setModuleSetting($this->getModule(), 'session_token', null);
         }
         // remove all profile parameters from the module settings
         BackendModel::setModuleSetting($this->getModule(), 'account_name', null);
         BackendModel::setModuleSetting($this->getModule(), 'table_id', null);
         BackendModel::setModuleSetting($this->getModule(), 'profile_title', null);
         // remove cache files
         BackendAnalyticsModel::removeCacheFiles();
         // clear tables
         BackendAnalyticsModel::clearTables();
     }
     // get session token, account name, the profile's table id, the profile's title
     $this->sessionToken = BackendModel::getModuleSetting($this->getModule(), 'session_token', null);
     $this->accountName = BackendModel::getModuleSetting($this->getModule(), 'account_name', null);
     $this->tableId = BackendModel::getModuleSetting($this->getModule(), 'table_id', null);
     $this->profileTitle = BackendModel::getModuleSetting($this->getModule(), 'profile_title', null);
     // no session token
     if (!isset($this->sessionToken)) {
         $token = SpoonFilter::getGetValue('token', null, null);
         // a one time token is given in the get parameters
         if (!empty($token) && $token !== 'true') {
             // get google analytics instance
             $ga = BackendAnalyticsHelper::getGoogleAnalyticsInstance();
             // get a session token
             $this->sessionToken = $ga->getSessionToken($token);
             // store the session token in the settings
             BackendModel::setModuleSetting($this->getModule(), 'session_token', $this->sessionToken);
         }
     }
     // session id is present but there is no table_id
     if (isset($this->sessionToken) && !isset($this->tableId)) {
         // get google analytics instance
         $ga = BackendAnalyticsHelper::getGoogleAnalyticsInstance();
         // get all possible profiles in this account
         $this->profiles = $ga->getAnalyticsAccountList($this->sessionToken);
         // not authorized
         if ($this->profiles == 'UNAUTHORIZED') {
             // remove invalid session token
             BackendModel::setModuleSetting($this->getModule(), 'session_token', null);
             // redirect to the settings page without parameters
             $this->redirect(BackendModel::createURLForAction('settings'));
         } elseif (is_array($this->profiles)) {
             $tableId = SpoonFilter::getGetValue('table_id', null, null);
             // a table id is given in the get parameters
             if (!empty($tableId)) {
                 $profiles = array();
                 // set the table ids as keys
                 foreach ($this->profiles as $profile) {
                     $profiles[$profile['tableId']] = $profile;
                 }
                 // correct table id
                 if (isset($profiles[$tableId])) {
                     // save table id and account title
                     $this->tableId = $tableId;
                     $this->accountName = $profiles[$this->tableId]['accountName'];
                     $this->profileTitle = $profiles[$this->tableId]['title'];
                     $webPropertyId = $profiles[$this->tableId]['webPropertyId'];
                     // store the table id and account title in the settings
                     BackendModel::setModuleSetting($this->getModule(), 'account_name', $this->accountName);
                     BackendModel::setModuleSetting($this->getModule(), 'table_id', $this->tableId);
                     BackendModel::setModuleSetting($this->getModule(), 'profile_title', $this->profileTitle);
                     BackendModel::setModuleSetting($this->getModule(), 'web_property_id', $webPropertyId);
                 }
             }
         }
     }
 }
Esempio n. 16
0
 /**
  * Get pages
  *
  * @return	array
  * @param	int $startTimestamp		The start timestamp for the cache file.
  * @param	int $endTimestamp		The end timestamp for the cache file.
  */
 public static function getPages($startTimestamp, $endTimestamp)
 {
     // get data from cache
     $items = self::getDataFromCacheByType('pages', $startTimestamp, $endTimestamp);
     // get current action
     $action = Spoon::get('url')->getAction();
     // nothing in cache
     if ($items === false) {
         self::redirectToLoadingPage($action);
     }
     // reset loop counter for the current action if we got data from cache
     SpoonSession::set($action . 'Loop', null);
     // init vars
     $results = array();
     // build pages array
     foreach ($items as $i => $item) {
         // build array
         $results[$i] = array();
         $results[$i]['page'] = $item['pagePath'];
         $results[$i]['page_encoded'] = urlencode($item['pagePath']);
         $results[$i]['pageviews'] = (int) $item['pageviews'];
         $results[$i]['pages_per_visit'] = $item['visits'] == 0 ? 0 : number_format((int) $item['pageviews'] / $item['visits'], 2);
         $results[$i]['time_on_site'] = BackendAnalyticsModel::getTimeFromSeconds($item['entrances'] == 0 ? 0 : number_format((int) $item['timeOnSite'] / $item['entrances'], 2));
         $results[$i]['new_visits_percentage'] = ($item['visits'] == 0 ? 0 : number_format((int) $item['newVisits'] / $item['visits'] * 100, 2)) . '%';
         $results[$i]['bounce_rate'] = ($item['entrances'] == 0 ? 0 : number_format((int) $item['bounces'] / $item['entrances'] * 100, 2)) . '%';
     }
     // return results
     return $results;
 }
Esempio n. 17
0
 /**
  * Parse pages datagrid
  */
 private function parsePages()
 {
     $results = BackendAnalyticsModel::getPages($this->startTimestamp, $this->endTimestamp);
     if (!empty($results)) {
         $dataGrid = new BackendDataGridArray($results);
         $dataGrid->setPaging(false);
         $dataGrid->setColumnHidden('page_encoded');
         // check if this action is allowed
         if (BackendAuthentication::isAllowedAction('detail_page', $this->getModule())) {
             $dataGrid->setColumnURL('page', BackendModel::createURLForAction('detail_page') . '&amp;page_path=[page_encoded]');
         }
         // parse the datagrid
         $this->tpl->assign('dgPages', $dataGrid->getContent());
     }
 }
Esempio n. 18
0
 /**
  * Parse this page
  *
  * @return	void
  */
 protected function parse()
 {
     // get page
     $page = $this->pageId != '' ? BackendAnalyticsModel::getPageForId($this->pageId) : null;
     // update date_viewed for this page
     BackendAnalyticsModel::updatePageDateViewed($this->pageId);
     // parse redirect link
     $this->tpl->assign('redirect', BackendModel::createURLForAction($this->redirectAction));
     $this->tpl->assign('redirectGet', isset($page) ? 'page=' . $page : '');
     $this->tpl->assign('settingsUrl', BackendModel::createURLForAction('settings'));
     $this->tpl->assign('page', $this->redirectAction);
     $this->tpl->assign('identifier', ($this->pageId != '' ? $this->pageId . '_' : '') . $this->identifier);
 }
Esempio n. 19
0
 /**
  * Get data from analytics
  *
  * @return	void
  * @param	int $startTimestamp			The start timestamp for the data to collect.
  * @param	int $endTimestamp			The end timestamp for the data to collect.
  * @param	bool[optional] $force		Force getting data. Don't rely on cache.
  * @param	string[optional] $page		The page to get data for.
  * @param	string[optional] $pageId	The id of the page to get data for.
  * @param	string[optional] $filename	The name of the cache file.
  */
 private function getData($startTimestamp, $endTimestamp, $force = false, $page = 'all', $pageId = null, $filename = null)
 {
     // try
     try {
         // get data from cache
         $data = BackendAnalyticsModel::getDataFromCache($startTimestamp, $endTimestamp);
         // nothing in cache - fetch from google and set cache
         if (!isset($data['aggregates']) || $force) {
             $data['aggregates'] = BackendAnalyticsHelper::getAggregates($startTimestamp, $endTimestamp);
         }
         // nothing in cache - fetch from google and set cache
         if (!isset($data['aggregates_total']) || $force) {
             $data['aggregates_total'] = BackendAnalyticsHelper::getAggregates(mktime(0, 0, 0, 1, 1, 2005), mktime(0, 0, 0));
         }
         // nothing in cache - fetch from google and set cache
         if (!isset($data['metrics_per_day']) || $force) {
             $data['metrics_per_day']['entries'] = BackendAnalyticsHelper::getMetricsPerDay($startTimestamp, $endTimestamp);
         }
         // traffic sources, top keywords and top referrals on index page
         if ($page == 'all' || $page == 'index') {
             // nothing in cache - fetch from google and set cache
             if (!isset($data['traffic_sources']) || $force) {
                 $data['traffic_sources']['entries'] = BackendAnalyticsHelper::getTrafficSourcesGrouped(array('pageviews'), $startTimestamp, $endTimestamp, 'pageviews');
             }
             // nothing in cache
             if (!isset($data['top_keywords']) || $force) {
                 // fetch from google and use a safe limit
                 $gaResults = BackendAnalyticsHelper::getKeywords('pageviews', $startTimestamp, $endTimestamp, 'pageviews', 50);
                 // set cache
                 $data['top_keywords']['entries'] = $gaResults['entries'];
             }
             // nothing in cache
             if (!isset($data['top_referrals']) || $force) {
                 // fetch from google and use a safe limit
                 $gaResults = BackendAnalyticsHelper::getReferrals('pageviews', $startTimestamp, $endTimestamp, 'pageviews', 50);
                 // init vars
                 $topReferrals = array();
                 // add entries to items
                 foreach ($gaResults['entries'] as $entry) {
                     $topReferrals[] = array('referrer' => $entry['source'] . $entry['referralPath'], 'pageviews' => $entry['pageviews']);
                 }
                 // set cache
                 $data['top_referrals']['entries'] = $topReferrals;
             }
         }
         // top pages on index and content page
         if ($page == 'all' || $page == 'index' || $page == 'content') {
             // nothing in cache
             if (!isset($data['top_pages']) || $force) {
                 // fetch from google and use a safe limit
                 $gaResults = BackendAnalyticsHelper::getPages('pageviews', $startTimestamp, $endTimestamp, 'pageviews', 50);
                 // set cache
                 $data['top_pages']['entries'] = $gaResults['entries'];
             }
         }
         // top exit pages on content page
         if ($page == 'all' || $page == 'content') {
             // nothing in cache
             if (!isset($data['top_exit_pages']) || $force) {
                 // fetch from google
                 $gaResults = BackendAnalyticsHelper::getPages(array('exits', 'pageviews'), $startTimestamp, $endTimestamp, 'exits', 50);
                 // set cache
                 $data['top_exit_pages']['entries'] = $gaResults['entries'];
             }
         }
         // top exit pages on all pages page
         if ($page == 'all' || $page == 'all_pages') {
             // nothing in cache
             if (!isset($data['pages']) || $force) {
                 // fetch from google
                 $gaResults = BackendAnalyticsHelper::getPages(array('bounces', 'entrances', 'exits', 'newVisits', 'pageviews', 'timeOnSite', 'visits'), $startTimestamp, $endTimestamp, 'pageviews', 50);
                 // set cache
                 $data['pages']['entries'] = $gaResults['entries'];
                 $data['pages']['attributes'] = array('totalResults' => $gaResults['totalResults']);
             }
         }
         // exit pages on exit pages page
         if ($page == 'all' || $page == 'exit_pages') {
             // nothing in cache
             if (!isset($data['exit_pages']) || $force) {
                 // fetch from google
                 $gaResults = BackendAnalyticsHelper::getExitPages(array('bounces', 'entrances', 'exits', 'newVisits', 'pageviews', 'timeOnSite', 'visits'), $startTimestamp, $endTimestamp, 'exits', 50);
                 // set cache
                 $data['exit_pages']['entries'] = $gaResults['entries'];
             }
         }
         // detail page
         if ($page == 'detail_page') {
             // nothing in cache
             if (!isset($data['page' . $pageId]) || $force) {
                 // fetch from google
                 $gaResults = BackendAnalyticsHelper::getDataForPage($pageId, $startTimestamp, $endTimestamp);
                 // set cache
                 $data['page_' . $pageId] = $gaResults;
             }
         }
         // update cache file
         BackendAnalyticsModel::writeCacheFile($data, $startTimestamp, $endTimestamp);
     } catch (Exception $e) {
         // set file content to indicate something went wrong if needed
         if (isset($filename)) {
             SpoonFile::setContent($filename, 'error');
         } else {
             throw new SpoonException('Something went wrong while getting data.');
         }
     }
     // remove temporary file if needed
     if (isset($filename)) {
         SpoonFile::setContent($filename, 'done');
     }
 }
Esempio n. 20
0
 /**
  * Parses the overview data
  *
  * @return	void
  */
 private function parseOverviewData()
 {
     // get aggregates
     $results = BackendAnalyticsModel::getAggregates($this->startTimestamp, $this->endTimestamp);
     // get total aggregates
     $resultsTotal = BackendAnalyticsModel::getAggregatesTotal($this->startTimestamp, $this->endTimestamp);
     // are there some values?
     $dataAvailable = false;
     foreach ($resultsTotal as $data) {
         if ($data != 0) {
             $dataAvailable = true;
         }
     }
     // show message if there is no data
     $this->tpl->assign('dataAvailable', $dataAvailable);
     // there are some results
     if (!empty($results)) {
         // exits percentage of total
         $exitsPercentageOfTotal = $results['exits'] == 0 ? 0 : number_format($results['exitPagesExits'] / $results['exits'] * 100, 0);
         // pageviews percentage of total
         $pageviewsPercentageOfTotal = $results['pageviews'] == 0 ? 0 : number_format($results['exitPagesPageviews'] / $results['pageviews'] * 100, 0);
         // exits percentage
         $exitsPercentage = $results['exitPagesPageviews'] == 0 ? 0 : number_format($results['exits'] / $results['exitPagesPageviews'] * 100, 0);
         $exitsPercentageTotal = $resultsTotal['pageviews'] == 0 ? 0 : number_format($resultsTotal['exits'] / $resultsTotal['pageviews'] * 100, 0);
         $exitsPercentageDifference = $exitsPercentageTotal == 0 ? 0 : number_format(($exitsPercentage - $exitsPercentageTotal) / $exitsPercentageTotal * 100, 0);
         if ($exitsPercentageDifference > 0) {
             $exitsPercentageDifference = '+' . $exitsPercentageDifference;
         }
         // parse data
         $this->tpl->assign('exits', $results['exits']);
         $this->tpl->assign('exitsPercentageOfTotal', $exitsPercentageOfTotal);
         $this->tpl->assign('pageviews', $results['exitPagesPageviews']);
         $this->tpl->assign('pageviewsPercentageOfTotal', $pageviewsPercentageOfTotal);
         $this->tpl->assign('exitsPercentage', $exitsPercentage);
         $this->tpl->assign('exitsPercentageTotal', $exitsPercentageTotal);
         $this->tpl->assign('exitsPercentageDifference', $exitsPercentageDifference);
     }
 }
Esempio n. 21
0
 /**
  * Parse pages datagrid
  *
  * @return	void
  */
 private function parsePages()
 {
     // get results
     $results = BackendAnalyticsModel::getPages($this->startTimestamp, $this->endTimestamp);
     // there are some results
     if (!empty($results)) {
         // get the datagrid
         $dataGrid = new BackendDataGridArray($results);
         // no pagination
         $dataGrid->setPaging();
         // hide columns
         $dataGrid->setColumnHidden('page_encoded');
         // set url
         $dataGrid->setColumnURL('page', BackendModel::createURLForAction('detail_page') . '&amp;page_path=[page_encoded]');
         // parse the datagrid
         $this->tpl->assign('dgPages', $dataGrid->getContent());
     }
 }
Esempio n. 22
0
 /**
  * Validate the form
  *
  * @return	void
  */
 private function validateForm()
 {
     // is the form submitted?
     if ($this->frm->isSubmitted()) {
         // cleanup the submitted fields, ignore fields that were added by hackers
         $this->frm->cleanupFields();
         // shorten values
         $pagePath = $this->frm->getField('page_path')->getValue();
         if (count($this->linkList) > 1) {
             $pageList = $this->frm->getField('page_list')->getSelected();
         }
         // get the target
         if ($this->frm->getfield('page_path')->isFilled()) {
             $page = $pagePath;
         } elseif ($pageList == '0') {
             $page = null;
         } else {
             $page = SITE_MULTILANGUAGE ? substr($pageList, strpos($pageList, '/', 1)) : $pageList;
         }
         // validate fields
         if (isset($page) && !SpoonFilter::isURL(SITE_URL . $page)) {
             $this->frm->getField('page_path')->addError(BL::err('InvalidURL'));
         }
         if (!isset($page)) {
             $this->frm->getField('page_path')->addError(BL::err('FieldIsRequired'));
         }
         if (!$this->frm->getField('page_path')->isFilled() && !$this->frm->getfield('page_list')->isFilled()) {
             $this->frm->getField('page_path')->addError(BL::err('FieldIsRequired'));
         }
         // no errors?
         if ($this->frm->isCorrect()) {
             // get metrics
             $metrics = BackendAnalyticsHelper::getMetricsForPage($page, $this->startTimestamp, $this->endTimestamp);
             // build item
             $item['page_path'] = $page;
             $item['entrances'] = isset($metrics['entrances']) ? $metrics['entrances'] : 0;
             $item['bounces'] = isset($metrics['bounces']) ? $metrics['bounces'] : 0;
             $item['bounce_rate'] = ($metrics['entrances'] == 0 ? 0 : number_format((int) $metrics['bounces'] / $metrics['entrances'] * 100, 2)) . '%';
             $item['start_date'] = date('Y-m-d', $this->startTimestamp) . ' 00:00:00';
             $item['end_date'] = date('Y-m-d', $this->endTimestamp) . ' 00:00:00';
             $item['updated_on'] = date('Y-m-d H:i:s');
             // insert the item
             $item['id'] = (int) BackendAnalyticsModel::insertLandingPage($item);
             // trigger event
             BackendModel::triggerEvent($this->getModule(), 'after_add_landing_page', array('item' => $item));
             // everything is saved, so redirect to the overview
             $this->redirect(BackendModel::createURLForAction('landing_pages') . '&report=saved&var=' . urlencode($item['page_path']));
         }
     }
 }
Esempio n. 23
0
 /**
  * Parses the overview data
  *
  * @return	void
  */
 private function parseOverviewData()
 {
     // get aggregates
     $results = BackendAnalyticsModel::getAggregates($this->startTimestamp, $this->endTimestamp);
     // get total aggregates
     $resultsTotal = BackendAnalyticsModel::getAggregatesTotal($this->startTimestamp, $this->endTimestamp);
     // are there some values?
     $dataAvailable = false;
     foreach ($resultsTotal as $data) {
         if ($data != 0) {
             $dataAvailable = true;
         }
     }
     // show message if there is no data
     $this->tpl->assign('dataAvailable', $dataAvailable);
     // there are some results
     if (!empty($results)) {
         // new visitors
         $newVisits = $results['entrances'] == 0 ? 0 : number_format($results['newVisits'] / $results['entrances'] * 100, 0);
         $newVisitsTotal = $resultsTotal['entrances'] == 0 ? 0 : number_format($resultsTotal['newVisits'] / $resultsTotal['entrances'] * 100, 0);
         $newVisitsDifference = $newVisitsTotal == 0 ? 0 : number_format(($newVisits - $newVisitsTotal) / $newVisitsTotal * 100, 0);
         if ($newVisitsDifference > 0) {
             $newVisitsDifference = '+' . $newVisitsDifference;
         }
         // bounces
         $bounces = $results['entrances'] == 0 ? 0 : number_format($results['bounces'] / $results['entrances'] * 100, 0);
         $bouncesTotal = $resultsTotal['entrances'] == 0 ? 0 : number_format($resultsTotal['bounces'] / $resultsTotal['entrances'] * 100, 0);
         $bouncesDifference = $bouncesTotal == 0 ? 0 : number_format(($bounces - $bouncesTotal) / $bouncesTotal * 100, 0);
         if ($bouncesDifference > 0) {
             $bouncesDifference = '+' . $bouncesDifference;
         }
         // parse data
         $this->tpl->assign('pageviews', $results['pageviews']);
         $this->tpl->assign('pageviewsTotal', $resultsTotal['pageviews']);
         $this->tpl->assign('uniquePageviews', $results['uniquePageviews']);
         $this->tpl->assign('uniquePageviewsTotal', $resultsTotal['uniquePageviews']);
         $this->tpl->assign('newVisits', $newVisits);
         $this->tpl->assign('newVisitsTotal', $newVisitsTotal);
         $this->tpl->assign('newVisitsDifference', $newVisitsDifference);
         $this->tpl->assign('bounces', $bounces);
         $this->tpl->assign('bouncesTotal', $bouncesTotal);
         $this->tpl->assign('bouncesDifference', $bouncesDifference);
     }
 }
Esempio n. 24
0
 /**
  * Parses the data to make the pie-chart
  *
  * @return	void
  */
 private function parsePieChartData()
 {
     // get sources
     $sources = BackendAnalyticsModel::getTrafficSourcesGrouped($this->startTimestamp, $this->endTimestamp);
     // init vars
     $graphData = array();
     // loop metrics
     foreach ($sources as $i => $source) {
         // get label
         $label = BL::lbl(SpoonFilter::toCamelCase($source['label']), 'analytics');
         if ($label == '{$lblAnalytics' . SpoonFilter::toCamelCase($source['label']) . '}') {
             $label = $source['label'];
         }
         // build array
         $graphData[$i]['label'] = ucfirst($label);
         $graphData[$i]['value'] = (string) $source['value'];
         $graphData[$i]['percentage'] = (string) $source['percentage'];
     }
     // parse
     $this->tpl->assign('pieGraphData', $graphData);
 }
 /**
  * Parse into template
  *
  * @return	void
  */
 private function parseReferrers()
 {
     // get results
     $results = BackendAnalyticsModel::getRecentReferrers();
     // there are some results
     if (!empty($results)) {
         // get the datagrid
         $dataGrid = new BackendDataGridArray($results);
         // no pagination
         $dataGrid->setPaging();
         // hide columns
         $dataGrid->setColumnsHidden('id', 'date', 'url');
         // set url
         $dataGrid->setColumnURL('referrer', '[url]');
     }
     // parse the datagrid
     return !empty($results) ? $dataGrid->getContent() : '<table border="0" cellspacing="0" cellpadding="0" class="dataGrid"><tr><td>' . BL::msg('NoKeywords') . '</td></tr></table>';
 }