Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 1
<?php
2
 
3
/***************************************************************************
4
 *   Copyright (C) 2009-2011 by Geo Varghese(www.seopanel.in)  	   *
5
 *   sendtogeo@gmail.com   												   *
6
 *                                                                         *
7
 *   This program is free software; you can redistribute it and/or modify  *
8
 *   it under the terms of the GNU General Public License as published by  *
9
 *   the Free Software Foundation; either version 2 of the License, or     *
10
 *   (at your option) any later version.                                   *
11
 *                                                                         *
12
 *   This program is distributed in the hope that it will be useful,       *
13
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
14
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
15
 *   GNU General Public License for more details.                          *
16
 *                                                                         *
17
 *   You should have received a copy of the GNU General Public License     *
18
 *   along with this program; if not, write to the                         *
19
 *   Free Software Foundation, Inc.,                                       *
20
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
21
 ***************************************************************************/
22
 
23
// include google api module
24
include_once(SP_CTRLPATH . "/googleapi.ctrl.php");
25
 
26
// class defines all google analytics api controller functions
27
class AnalyticsController extends GoogleAPIController {
28
 
29
    var $spTextGA;
30
    var $metrics;
31
	var $metricList;
32
	var $defaultMetricName = "users";
33
	var $dimensionName = "source";
34
 
35
	function __construct() {
36
		parent::__construct();
37
		$this->spTextGA = $this->getLanguageTexts('analytics', $_SESSION['lang_code']);
38
		$this->set('spTextGA', $this->spTextGA);
39
		$this->metrics = array(
40
		    'users' => $this->spTextGA['Users'],
41
		    'newUsers' => $this->spTextGA['New Users'],
42
		    'sessions' => $this->spTextGA['Sessions'],
43
		    'bounceRate' => $this->spTextGA['Bounce Rate'],
44
		    'avgSessionDuration' => $this->spTextGA['Avg. Session Duration'],
45
		    'goalCompletionsAll' => $this->spTextGA['Goal Completions'],
46
		);
47
 
48
 
49
		$this->set('metricColList', $this->metrics);
50
		$this->metricList = array_keys($this->metrics);
51
	}
52
 
53
	/*
54
	 * function to get analytics query result
55
	 */
56
	function getAnalyticsResults($userId, $VIEW_ID, $startDate, $endDate) {
57
		$result = array('status' => false);
58
 
59
		if (empty($VIEW_ID)) {
60
		    $result['msg'] = $this->spTextGA['view_id_not_found_error'];
61
		    $alertCtler = new AlertController();
62
		    $alertInfo = array(
63
	    		'alert_subject' => $this->spTextGA['view_id_not_found_error'],
64
	    		'alert_message' => "",
65
	    		'alert_url' => SP_WEBPATH ."/admin-panel.php",
66
	    		'alert_type' => "danger",
67
	    		'alert_category' => "reports",
68
		    );
69
		    $alertCtler->createAlert($alertInfo, $userId);
70
		    return $result;
71
		}
72
 
73
		try {
74
 
75
    		$client = $this->getAuthClient($userId);
76
 
77
    		// check whether client created successfully
78
    		if (!is_object($client)) {
79
    		    $result['msg'] = $client;
80
    		    return $result;
81
    		}
82
 
83
    		$analytics = new Google_Service_AnalyticsReporting($client);
84
 
85
    		// Create the DateRange object.
86
    		$dateRange = new Google_Service_AnalyticsReporting_DateRange();
87
    		$dateRange->setStartDate($startDate);
88
    		$dateRange->setEndDate($endDate);
89
 
90
    		// Create the Metrics object list
91
    		$metricObjList = [];
92
    		foreach ($this->metricList as $metricName) {
93
	    		$sessions = new Google_Service_AnalyticsReporting_Metric();
94
	    		$sessions->setExpression("ga:$metricName");
95
	    		$sessions->setAlias($metricName);
96
	    		$metricObjList[] = $sessions;
97
    		}
98
 
99
    		// Create the dimension.
100
    		$dimension = new Google_Service_AnalyticsReporting_Dimension();
101
    		$dimension->setName("ga:$this->dimensionName");
102
 
103
    		// Create the Ordering.
104
    		$ordering = new Google_Service_AnalyticsReporting_OrderBy();
105
    		$ordering->setFieldName("ga:$this->defaultMetricName");
106
    		$ordering->setOrderType("VALUE");
107
    		$ordering->setSortOrder("DESCENDING");
108
 
109
    		// Create the ReportRequest object.
110
    		$request = new Google_Service_AnalyticsReporting_ReportRequest();
111
    		$request->setViewId($VIEW_ID);
112
    		$request->setDateRanges($dateRange);
113
    		$request->setMetrics($metricObjList);
114
    		$request->setDimensions(array($dimension));
115
    		$request->setOrderBys($ordering);
116
 
117
    		$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
118
    		$body->setReportRequests( array( $request) );
119
    		$res = $analytics->reports->batchGet( $body );
120
    		$resultList = $this->formatResult($res);
121
 
122
    		$result['status'] = true;
123
    		$result['resultList'] = $resultList;
124
		} catch (Exception $e) {
125
		    $err = $e->getMessage();
126
		    $result['msg'] = "Error: search query analytics - $err";
127
		}
128
 
129
		return $result;
130
 
131
	}
132
 
133
	function formatMetricValue($value, $metricName) {
134
 
135
		if ($metricName == "bounceRate") {
136
			$value = round($value, 2);
137
		}
138
 
139
		if ($metricName == "avgSessionDuration") {
140
			$value = round(($value/60), 2);
141
		}
142
 
143
		return $value;
144
	}
145
 
146
	function formatResult($reports) {
147
		$resultList = array();
148
 
149
		// loop through the reports
150
		for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
151
			$report = $reports[ $reportIndex ];
152
 
153
			// get total value
154
			$totals = $report->getData()->getTotals();
155
			$values = $totals[0]->getValues();
156
			$resultList['total'] = [];
157
			foreach ($this->metricList as $i => $metricName) {
158
				$resultList['total'][$metricName] = $this->formatMetricValue($values[$i], $metricName);
159
			}
160
 
161
			// get dimension type value
162
			$rows = $report->getData()->getRows();
163
			for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
164
				$row = $rows[$rowIndex];
165
				$dimensions = $row->getDimensions();
166
				$metrics = $row->getMetrics();
167
				$values = $metrics[0]->getValues();
168
 
169
				// find metric values
170
				$resultList[$dimensions[0]] = [];
171
				foreach ($this->metricList as $i => $metricName) {
172
					$resultList[$dimensions[0]][$metricName] = $this->formatMetricValue($values[$i], $metricName);
173
				}
174
			}
175
		}
176
 
177
		return $resultList;
178
	}
179
 
180
	function getAnalyticsSourceList() {
181
	    $sourceList = [];
182
	    $list = $this->dbHelper->getAllRows("analytic_sources");
183
	    foreach ($list as $listInfo) {
184
	        $sourceList[$listInfo['source_name']] = $listInfo['id'];
185
	    }
186
 
187
	    return $sourceList;
188
	}
189
 
190
	function generateSource($sourceName) {
191
	    $sourceId = false;
192
	    if ($this->dbHelper->insertRow("analytic_sources", array("source_name" => $sourceName))) {
193
	        $sourceId = $this->db->getMaxId("analytic_sources");
194
	    }
195
 
196
	    return $sourceId;
197
	}
198
 
199
	/*
200
	 * function to store website results
201
	 */
202
	function storeWebsiteAnalytics($websiteId, $reportDate) {
203
		$websiteId = intval($websiteId);
204
		$websiteCtrler = new WebsiteController();
205
		$websiteInfo = $websiteCtrler->__getWebsiteInfo($websiteId);
206
 
207
		// query results from api and verify no error occured
208
		$result = $this->getAnalyticsResults($websiteInfo['user_id'], $websiteInfo['analytics_view_id'], $reportDate, $reportDate);
209
		if ($result['status']) {
210
		    $sourceList = $this->getAnalyticsSourceList();
211
 
212
			// loop through the result list
213
			foreach ($result['resultList'] as $sourceName => $reportInfo) {
214
 
215
			    // generate source list, if not set it yet
216
			    if (!isset($sourceList[$sourceName])) {
217
			        $sourceId = $this->generateSource($sourceName);
218
			    } else {
219
			        $sourceId = $sourceList[$sourceName];
220
			    }
221
 
222
			    if (!empty($sourceId)) {
223
			        $this->insertWebsiteAnalytics($websiteId, $sourceId, $reportInfo, $reportDate);
224
			    } else {
225
			        $result['msg'] .= "Error: Analytics source id not found";
226
			    }
227
			}
228
		}
229
 
230
		return $result;
231
 
232
	}
233
 
234
	/*
235
	 * function to insert website analytics
236
	 */
237
	function insertWebsiteAnalytics($websiteId, $sourceId, $reportInfo, $resultDate, $clearExisting = true) {
238
		$websiteId = intval($websiteId);
239
		$sourceId = intval($sourceId);
240
		$resultDate = addslashes($resultDate);
241
 
242
		if ($clearExisting) {
243
			$whereCond = "website_id=$websiteId and report_date='$resultDate' and source_id='$sourceId'";
244
			$this->dbHelper->deleteRows('website_analytics', $whereCond);
245
		}
246
 
247
		$reportInfo['website_id'] = $websiteId;
248
		$reportInfo['source_id'] = $sourceId;
249
		$reportInfo['report_date'] = $resultDate;
250
		$this->dbHelper->insertRow('website_analytics', $reportInfo);
251
	}
252
 
253
	// func to show quick checker
254
	function viewQuickChecker($searchInfo='') {
255
		$userId = isLoggedIn();
256
		$websiteController = New WebsiteController();
257
		$websiteList = $websiteController->__getAllWebsites($userId, true);
258
		$this->set('websiteList', $websiteList);
259
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
260
		$this->set('websiteId', $websiteId);
261
		$this->set('fromTime', date('Y-m-d', strtotime('-1 days')));
262
		$this->set('toTime', date('Y-m-d'));
263
		$this->render('analytics/quick_checker');
264
	}
265
 
266
	// func to do quick report
267
	function doQuickChecker($searchInfo = '') {
268
 
269
		if (!empty($searchInfo['website_id'])) {
270
			$websiteId = intval($searchInfo['website_id']);
271
			$websiteController = New WebsiteController();
272
			$websiteInfo = $websiteController->__getWebsiteInfo($websiteId);
273
			$this->set('websiteInfo', $websiteInfo);
274
 
275
			if (!empty($websiteInfo['url'])) {
276
				$reportStartDate = !empty($searchInfo['from_time']) ? $searchInfo['from_time'] : date('Y-m-d', strtotime('-1 days'));
277
				$reportEndDate = !empty($searchInfo['to_time']) ? $searchInfo['to_time'] : date('Y-m-d');
278
 
279
				// query results from api and verify no error occured
280
				$result = $this->getAnalyticsResults($websiteInfo['user_id'], $websiteInfo['analytics_view_id'], $reportStartDate, $reportEndDate);
281
 
282
				// if status is success
283
				if ($result['status']) {
284
					$websiteReport = array_shift($result['resultList']);
285
					$sourceReport = $result['resultList'];
286
					$this->set('websiteReport', $websiteReport);
287
					$this->set('sourceReport', $sourceReport);
288
 
289
					$this->set('searchInfo', $searchInfo);
290
					$this->render('analytics/quick_checker_results');
291
					return true;
292
 
293
				}
294
			}
295
		}
296
 
297
		$errorMsg = !empty($result['msg']) ? $result['msg'] : "Internal error occured while accessing webmaster tools.";
298
		showErrorMsg($errorMsg);
299
	}
300
 
301
	// function check whether analytics reports already saved
302
	function isReportsExists($websiteId, $resultDate) {
303
		$websiteId = intval($websiteId);
304
		$resultDate = addslashes($resultDate);
305
		$whereCond = "website_id=$websiteId and report_date='$resultDate'";
306
		$info = $this->dbHelper->getRow("website_analytics", $whereCond, "website_id");
307
		return !empty($info['website_id']) ? true : false;
308
	}
309
 
310
	# func to show analytics report summary
311
	function viewAnalyticsSummary($searchInfo = '', $summaryPage = false, $cronUserId=false) {
312
 
313
	    $userId = !empty($cronUserId) ? $cronUserId : isLoggedIn();
314
	    $this->set('summaryPage', $summaryPage);
315
	    $this->set('searchInfo', $searchInfo);
316
	    $this->set('cronUserId', $cronUserId);
317
 
318
	    $exportVersion = false;
319
	    switch($searchInfo['doc_type']){
320
 
321
	        case "export":
322
	            $exportVersion = true;
323
	            $exportContent = "";
324
	            break;
325
 
326
	        case "pdf":
327
	            $this->set('pdfVersion', true);
328
	            break;
329
 
330
	        case "print":
331
	            $this->set('printVersion', true);
332
	            break;
333
	    }
334
 
335
	    $fromTime = !empty($searchInfo['from_time']) ? addslashes($searchInfo['from_time']) : date('Y-m-d', strtotime('-2 days'));
336
	    $toTime = !empty($searchInfo['to_time']) ? addslashes($searchInfo['to_time']) : date('Y-m-d', strtotime('-1 days'));
337
	    $this->set('fromTime', $fromTime);
338
	    $this->set('toTime', $toTime);
339
 
340
	    $websiteController = New WebsiteController();
341
	    $wList = $websiteController->__getAllWebsites($userId, true);
342
	    $websiteList = [];
343
	    foreach ($wList as $wInfo) {
344
	        $websiteList[$wInfo['id']] = $wInfo;
345
	    }
346
 
347
	    $websiteList = count($websiteList) ? $websiteList : array(0);
348
	    $this->set('websiteList', $websiteList);
349
	    $websiteId = intval($searchInfo['website_id']);
350
	    $this->set('websiteId', $websiteId);
351
 
352
	    // to find order col
353
	    if (!empty($searchInfo['order_col'])) {
354
	        $orderCol = $searchInfo['order_col'];
355
	        $orderVal = getOrderByVal($searchInfo['order_val']);
356
	    } else {
357
	        $orderCol = "users";
358
	        $orderVal = 'DESC';
359
	    }
360
 
361
	    $this->set('orderCol', $orderCol);
362
	    $this->set('orderVal', $orderVal);
363
	    $scriptName = $summaryPage ? "archive.php" : "analytics.php";
364
	    $scriptPath = SP_WEBPATH . "/$scriptName?sec=viewAnalyticsSummary&website_id=$websiteId";
365
	    $scriptPath .= "&from_time=$fromTime&to_time=$toTime&search_name=" . $searchInfo['search_name'];
366
	    $scriptPath .= "&order_col=$orderCol&order_val=$orderVal&report_type=analytics-reports";
367
 
368
	    $conditions = !empty($searchInfo['search_name']) ? " and k.source_name like '%".addslashes($searchInfo['search_name'])."%'" : "";
369
 
370
	    // set website id to get exact keywords of a user
371
	    if (!empty($websiteId)) {
372
	        $conditions .= " and r.website_id=$websiteId";
373
	    } else {
374
	        $conditions .= " and r.website_id in (".implode(',', array_keys($websiteList)).")";
375
	    }
376
 
377
	    $analyticsCols = implode(",", array_keys($this->metrics));
378
	    $sql = "select k.id,k.source_name,r.website_id,$analyticsCols
379
            from analytic_sources k, website_analytics r
380
            where k.id=r.source_id $conditions and r.report_date='$toTime'
381
            order by " . addslashes($orderCol) . " " . addslashes($orderVal);
382
 
383
	    if ($orderCol != 'users') $sql .= ", users";
384
 
385
	    // pagination setup, if not from cron job email send function, pdf and export action
386
	    if (!in_array($searchInfo['doc_type'], array("pdf", "export"))) {
387
	        $this->db->query($sql, true);
388
	        $this->paging->setDivClass('pagingdiv');
389
	        $this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
390
	        $pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
391
	        $this->set('pagingDiv', $pagingDiv);
392
	        $this->set('pageNo', $searchInfo['pageno']);
393
	        $sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
394
	    }
395
 
396
	    # set report list
397
	    $baseReportList = $this->db->select($sql);
398
	    $this->set('baseReportList', $baseReportList);
399
	    $this->set('colList', $this->colList);
400
 
401
	    // if keywords existing
402
	    if (!empty($baseReportList)) {
403
 
404
	        $sourceIdList = array();
405
	        foreach ($baseReportList as $info) {
406
	            $sourceIdList[] = $info['id'];
407
	        }
408
 
409
	        $sql = "select k.id,k.source_name,r.website_id, $analyticsCols
410
			from analytic_sources k, website_analytics r where k.id=r.source_id
411
			$conditions and r.report_date='$fromTime'";
412
	        $sql .= " and k.id in(" . implode(",", $sourceIdList) . ")";
413
	        $reportList = $this->db->select($sql);
414
	        $compareReportList = array();
415
 
416
	        foreach ($reportList as $info) {
417
	            $compareReportList[$info['website_id']][$info['id']] = $info;
418
	        }
419
 
420
	        $this->set('compareReportList', $compareReportList);
421
	    }
422
 
423
	    if ($exportVersion) {
424
	        $spText = $_SESSION['text'];
425
	        $reportHeading =  $this->spTextTools['Website Analytics Summary']."($fromTime - $toTime)";
426
	        $exportContent .= createExportContent( array('', $reportHeading, ''));
427
	        $exportContent .= createExportContent( array());
428
	        $headList = array($spText['common']['Website'], $spText['common']['Source']);
429
 
430
	        $pTxt = str_replace("-", "/", substr($fromTime, -5));
431
	        $cTxt = str_replace("-", "/", substr($toTime, -5));
432
	        foreach ($this->metrics as $colKey => $colLabel) {
433
	            if ($colKey == 'name') continue;
434
	            $headList[] = $colLabel . "($pTxt)";
435
	            $headList[] = $colLabel . "($cTxt)";
436
	            $headList[] = $colLabel . "(+/-)";
437
	        }
438
 
439
	        $exportContent .= createExportContent($headList);
440
	        foreach($baseReportList as $listInfo){
441
 
442
	            $valueList = array($websiteList[$listInfo['website_id']]['url'], $listInfo['source_name']);
443
	            foreach ($this->metrics as $colName => $colVal) {
444
	                if ($colName == 'name') continue;
445
 
446
	                $currRank = isset($listInfo[$colName]) ? $listInfo[$colName] : 0;
447
	                $prevRank = isset($compareReportList[$listInfo['website_id']][$listInfo['id']][$colName]) ? $compareReportList[$listInfo['website_id']][$listInfo['id']][$colName] : 0;
448
	                $rankDiff = "";
449
 
450
	                // if both ranks are existing
451
	                if ($prevRank != '' && $currRank != '') {
452
	                    $rankDiff = $currRank - $prevRank;
453
	                    if ($colName == 'bounceRate') $rankDiff = $rankDiff * -1;
454
	                }
455
 
456
	                $valueList[] = $prevRank;
457
	                $valueList[] = $currRank;
458
	                $valueList[] = $rankDiff;
459
	            }
460
 
461
	            $exportContent .= createExportContent( $valueList);
462
	        }
463
 
464
	        if ($summaryPage) {
465
	            return $exportContent;
466
	        } else {
467
	            exportToCsv('analytics_summary', $exportContent);
468
	        }
469
 
470
	    } else {
471
 
472
	        // if pdf export
473
	        if ($summaryPage) {
474
	            return $this->getViewContent('analytics/analytics_summary');
475
	        } else {
476
	            // if pdf export
477
	            if ($searchInfo['doc_type'] == "pdf") {
478
	                exportToPdf($this->getViewContent('analytics/analytics_summary'), "analytics_summary_$fromTime-$toTime.pdf");
479
	            } else {
480
	                $this->set('searchInfo', $searchInfo);
481
	                $this->render('analytics/analytics_summary');
482
	            }
483
	        }
484
 
485
	    }
486
	}
487
 
488
	function __getWebsiteSourceList($websiteId) {
489
	    $websiteId = intval($websiteId);
490
	    $sql = "select * from analytic_sources where
491
            id in (select distinct source_id from website_analytics where website_id=$websiteId)
492
            order by source_name";
493
	    $sourceList = $this->db->select($sql);
494
	    return $sourceList;
495
	}
496
 
497
	// func to show analytics reports
498
	function viewAnalyticsReports($searchInfo = '') {
499
 
500
	    $userId = isLoggedIn();
501
 
502
	    if (!empty ($searchInfo['from_time'])) {
503
	        $fromTimeDate = addslashes($searchInfo['from_time']);
504
	    } else {
505
	        $fromTimeDate = date('Y-m-d', strtotime('-17 days'));
506
	    }
507
 
508
	    if (!empty ($searchInfo['to_time'])) {
509
	        $toTimeDate = addslashes($searchInfo['to_time']);
510
	    } else {
511
	        $toTimeDate = date('Y-m-d', strtotime('-1 days'));
512
	    }
513
 
514
	    $this->set('fromTime', $fromTimeDate);
515
	    $this->set('toTime', $toTimeDate);
516
 
517
	    $websiteController = New WebsiteController();
518
	    $websiteList = $websiteController->__getAllWebsites($userId, true);
519
	    $this->set('websiteList', $websiteList);
520
	    $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
521
	    $this->set('websiteId', $websiteId);
522
 
523
	    $sourceList = $this->__getWebsiteSourceList($websiteId);
524
	    $this->set('sourceList', $sourceList);
525
	    $sourceId = empty ($searchInfo['source_id']) ? $sourceList[0]['id'] : $searchInfo['source_id'];
526
	    $this->set('sourceId', $sourceId);
527
 
528
	    $conditions = " and s.website_id=$websiteId";
529
	    $conditions .= empty ($sourceId) ? "" : " and s.source_id=$sourceId";
530
	    $sql = "select s.* from website_analytics s
531
		  where report_date>='$fromTimeDate' and report_date<='$toTimeDate' $conditions
532
		  order by s.report_date";
533
	    $reportList = $this->db->select($sql);
534
 
535
	    $colList = array_keys($this->metrics);
536
	    $prevRank = [];
537
	    $rankDiff = [];
538
	    foreach ($colList as $col) {
539
	        $prevRank[$col] = 0;
540
	    }
541
 
542
	    // loop through rank
543
	    foreach ($reportList as $key => $repInfo) {
544
 
545
	        // exclude first row
546
	        if ($key) {
547
                foreach ($colList as $col) {
548
                    $rankDiff[$col] = '';
549
                }
550
 
551
                foreach ($colList as $col) {
552
                    $rankDiff[$col] = round($repInfo[$col] - $prevRank[$col], 2);
553
                    if (empty($rankDiff[$col])) {
554
                        continue;
555
                    }
556
 
557
                    if ($col == "bounceRate" ) {
558
                        $rankDiff[$col] = $rankDiff[$col] * -1;
559
                    }
560
 
561
                    $rankClass = ($rankDiff[$col] > 0) ? 'green' : 'red';
562
                    $rankDiff[$col] = "<font class='$rankClass'>($rankDiff[$col])</font>";
563
                    $reportList[$key]['rank_diff_'.$col] = empty($rankDiff[$col]) ? '' : $rankDiff[$col];
564
                }
565
            }
566
 
567
	        foreach ($colList as $col) {
568
	            $prevRank[$col] = $repInfo[$col];
569
	        }
570
	    }
571
 
572
	    $this->set('list', array_reverse($reportList, true));
573
	    $this->render('analytics/analytics_reports');
574
 
575
	}
576
 
577
	// func to show analytics reports in graph
578
	function viewAnalyticsGraphReports($searchInfo = '') {
579
	    $userId = isLoggedIn();
580
 
581
	    if (!empty ($searchInfo['from_time'])) {
582
	        $fromTimeDate = addslashes($searchInfo['from_time']);
583
	    } else {
584
	        $fromTimeDate = date('Y-m-d', strtotime('-17 days'));
585
	    }
586
 
587
	    if (!empty ($searchInfo['to_time'])) {
588
	        $toTimeDate = addslashes($searchInfo['to_time']);
589
	    } else {
590
	        $toTimeDate = date('Y-m-d', strtotime('-1 days'));
591
	    }
592
 
593
	    $this->set('fromTime', $fromTimeDate);
594
	    $this->set('toTime', $toTimeDate);
595
 
596
	    $websiteController = New WebsiteController();
597
	    $websiteList = $websiteController->__getAllWebsites($userId, true);
598
	    $this->set('websiteList', $websiteList);
599
	    $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
600
	    $this->set('websiteId', $websiteId);
601
 
602
	    $sourceList = $this->__getWebsiteSourceList($websiteId);
603
	    $this->set('sourceList', $sourceList);
604
	    $sourceId = empty ($searchInfo['source_id']) ? $sourceList[0]['id'] : $searchInfo['source_id'];
605
	    $this->set('sourceId', $sourceId);
606
 
607
	    $conditions = " and s.website_id=$websiteId";
608
	    $conditions .= empty ($sourceId) ? "" : " and s.source_id=$sourceId";
609
	    $sql = "select s.* from website_analytics s
610
		  where report_date>='$fromTimeDate' and report_date<='$toTimeDate' $conditions
611
		  order by s.report_date";
612
	    $reportList = $this->db->select($sql);
613
 
614
	    // if reports not empty
615
	    $colList = $this->metrics;
616
	    $this->set('colList', $colList);
617
	    $this->set('searchInfo', $searchInfo);
618
 
619
	    $graphColList = array();
620
	    if (!empty($searchInfo['attr_type'])) {
621
	        $graphColList[$searchInfo['attr_type']] = $colList[$searchInfo['attr_type']];
622
	        if ($searchInfo['attr_type'] == 'bounceRate') {
623
	            $this->set('reverseDir', true);
624
	        }
625
	    } else {
626
	        $graphColList = $colList;
627
	        unset($graphColList['bounceRate']);
628
	    }
629
 
630
	    if (!empty($reportList)) {
631
 
632
	        $dataArr = "['Date', '" . implode("', '", array_values($graphColList)) . "']";
633
 
634
	        // loop through data list
635
	        foreach ($reportList as $dataInfo) {
636
 
637
	            $valStr = "";
638
	            foreach ($graphColList as $seId => $seVal) {
639
	                $valStr .= ", ";
640
	                $valStr .= !empty($dataInfo[$seId]) ? $dataInfo[$seId] : 0;
641
	            }
642
 
643
	            $dataArr .= ", ['{$dataInfo['report_date']}' $valStr]";
644
	        }
645
 
646
	        $this->set('dataArr', $dataArr);
647
	        $this->set('graphTitle', $this->spTextTools['Website Analytics Summary']);
648
	        $graphContent = $this->getViewContent('report/graph');
649
	    } else {
650
	        $graphContent = showErrorMsg($_SESSION['text']['common']['No Records Found'], false, true);
651
	    }
652
 
653
	    // get graph content
654
	    $this->set('graphContent', $graphContent);
655
	    $this->render('analytics/graphicalreport');
656
 
657
	}
658
 
659
	// func to show keyword select box
660
	function showSourceSelectBox($websiteId){
661
	    $websiteId = intval($websiteId);
662
	    $this->set('sourceList', $this->__getWebsiteSourceList($websiteId));
663
	    $this->render('analytics/source_select_box', 'ajax');
664
	}
665
 
666
}
667
?>