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 webmaster tool api controller functions
27
class WebMasterController extends GoogleAPIController {
28
 
29
	var $rowLimit = 5000;
30
	var $sourceList = array('google');
31
	var $colList = array();
32
 
33
	function __construct() {
34
		parent::__construct();
35
 
36
		$this->spTextWB = $this->getLanguageTexts('webmaster', $_SESSION['lang_code']);
37
		$this->set('spTextWB', $this->spTextWB);
38
		$this->tokenCtrler = new UserTokenController();
39
 
40
		$this->colList = array(
41
			'name' => $_SESSION['text']['common']['Keyword'],
42
			'clicks' => $_SESSION['text']['label']['Clicks'],
43
			'impressions' => $_SESSION['text']['label']['Impressions'],
44
			'ctr' => "CTR",
45
			'average_position' => $this->spTextWB['Average Position'],
46
		);
47
 
48
	}
49
 
50
	/*
51
	 * function to get webmaster tool query search result
52
	 */
53
	function getQueryResults($userId, $siteUrl, $paramList, $limit = false) {
54
		$result = array('status' => false);
55
 
56
		try {
57
 
58
			$client = $this->getAuthClient($userId);
59
 
60
			// check whether client created successfully
61
			if (!is_object($client)) {
62
				$result['msg'] = $client;
63
				return $result;
64
			}
65
 
66
			$service = new Google_Service_Webmasters($client);
67
			$serviceRquest = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
68
			$serviceRquest->startDate = $paramList['startDate'];
69
			$serviceRquest->endDate = $paramList['endDate'];
70
 
71
			if (!empty($paramList['dimensions'])) {
72
				$serviceRquest->dimensions = $paramList['dimensions'];
73
			}
74
 
75
			if (!empty($paramList['dimensionFilterGroups'])) {
76
				$serviceRquest->dimensionFilterGroups = $paramList['dimensionFilterGroups'];
77
			}
78
 
79
			$resultList = array();
80
			$startRow = 0;
81
			$limit = $limit ? $limit : $this->rowLimit;
82
 
83
			while (count($resultList) < $limit) {
84
				$serviceRquest->startRow = $startRow;
85
				$serviceRquest->rowLimit = $this->rowLimit;
86
				$statRes = $service->searchanalytics->query($siteUrl, $serviceRquest);
87
				$rowList = $statRes->getRows();
88
				$resultList = array_merge($resultList, $rowList);
89
 
90
				// if the result count is less than expected in a call
91
				if (count($rowList) < $this->rowLimit) {
92
					break;
93
				}
94
 
95
				$startRow += $this->rowLimit;
96
			}
97
 
98
			$result['status'] = true;
99
			$result['resultList'] = $resultList;
100
 
101
		}  catch (Exception $e) {
102
			$err = $e->getMessage();
103
			$result['msg'] = "Error: search query analytics - $err";
104
		}
105
 
106
		return $result;
107
 
108
	}
109
 
110
	/*
111
	 * function to get all sites added in webmaster tools
112
	 */
113
	function getAllSites($userId) {
114
		$result = array('status' => false);
115
 
116
		try {
117
 
118
			$client = $this->getAuthClient($userId);
119
 
120
			// check whether client created successfully
121
			if (!is_object($client)) {
122
				$result['msg'] = $client;
123
				return $result;
124
			}
125
 
126
			$service = new Google_Service_Webmasters($client);
127
			$resultList = $service->sites->listSites();
128
			$result['status'] = true;
129
			$result['resultList'] = $resultList['siteEntry'];
130
 
131
		}  catch (Exception $e) {
132
			$err = $e->getMessage();
133
			$result['msg'] = "Error: get all sites - $err";
134
		}
135
 
136
		return $result;
137
 
138
	}
139
 
140
	/*
141
	 * function to submit website to webmaster tools
142
	 */
143
	function addWebsite($siteUrl, $userId) {
144
		$result = array('status' => false);
145
 
146
		try {
147
 
148
			$client = $this->getAuthClient($userId);
149
 
150
			// check whether client created successfully
151
			if (!is_object($client)) {
152
				$result['msg'] = $client;
153
				return $result;
154
			}
155
 
156
			$service = new Google_Service_Webmasters($client);
157
			$resultList = $service->sites->add($siteUrl);
158
			$result['status'] = true;
159
		}  catch (Exception $e) {
160
			$err = $e->getMessage();
161
			$result['msg'] = "Error: add website - $err";
162
		}
163
 
164
		return $result;
165
 
166
	}
167
 
168
	/*
169
	 * function to submit sitemap to webmaster tools
170
	 */
171
	function submitSitemap($siteUrl, $sitemapUrl, $userId) {
172
		$result = array('status' => false);
173
 
174
		try {
175
 
176
			$client = $this->getAuthClient($userId);
177
 
178
			// check whether client created successfully
179
			if (!is_object($client)) {
180
				$result['msg'] = $client;
181
				return $result;
182
			}
183
 
184
			$service = new Google_Service_Webmasters($client);
185
			$resultList = $service->sitemaps->submit($siteUrl, $sitemapUrl);
186
			$result['status'] = true;
187
		}  catch (Exception $e) {
188
			$err = $e->getMessage();
189
			$result['msg'] = "Error: submit sitemap - $err";
190
		}
191
 
192
		return $result;
193
 
194
	}
195
 
196
	/*
197
	 * function to get all sitemaps submitted in webmaster tools
198
	 */
199
	function getAllSitemap($siteUrl, $userId) {
200
		$result = array('status' => false);
201
 
202
		try {
203
 
204
			$client = $this->getAuthClient($userId);
205
 
206
			// check whether client created successfully
207
			if (!is_object($client)) {
208
				$result['msg'] = $client;
209
				return $result;
210
			}
211
 
212
			$service = new Google_Service_Webmasters($client);
213
			$resultList = $service->sitemaps->listSitemaps($siteUrl);
214
			$result['resultList'] = $resultList['sitemap'];
215
			$result['status'] = true;
216
		}  catch (Exception $e) {
217
			$err = $e->getMessage();
218
			$result['msg'] = "Error: get all sitemaps - $err";
219
		}
220
 
221
		return $result;
222
 
223
	}
224
	/*
225
	 * function to submit sitemap to webmaster tools
226
	 */
227
	function deleteWebsiteSitemap($siteUrl, $sitemapUrl, $userId) {
228
		$result = array('status' => false);
229
 
230
		try {
231
 
232
			// check whether client created successfully
233
			$client = $this->getAuthClient($userId);
234
			if (!is_object($client)) {
235
				$result['msg'] = $client;
236
				return $result;
237
			}
238
 
239
			$service = new Google_Service_Webmasters($client);
240
			$resultList = $service->sitemaps->delete($siteUrl, $sitemapUrl);
241
			$result['status'] = true;
242
		}  catch (Exception $e) {
243
			$err = $e->getMessage();
244
			$result['msg'] = "Error: delete sitemap - $err";
245
		}
246
 
247
		return $result;
248
 
249
	}
250
 
251
 
252
	function __generateKeywordId($websiteId, $keywordName) {
253
		$keywordId = 0;
254
		$dataList = array(
255
			'website_id|int' => $websiteId,
256
			'name' => $keywordName,
257
			'status' => 1,
258
		);
259
 
260
		if ($this->dbHelper->insertRow("webmaster_keywords", $dataList) ) {
261
			$keywordId = $this->db->getMaxId("webmaster_keywords");
262
		}
263
 
264
		return $keywordId;
265
	}
266
 
267
	function __getWebmasterKeywordInfo($keywordId){
268
		$keywordId = intval($keywordId);
269
		$listInfo = $this->dbHelper->getRow("webmaster_keywords", " id=$keywordId");
270
		return !empty($listInfo['id']) ? $listInfo : false;
271
	}
272
 
273
	function __getWebmasterKeywords($whereCond = false) {
274
		$keywordList = $this->dbHelper->getAllRows("webmaster_keywords", $whereCond);
275
		return !empty($keywordList) ? $keywordList : false;
276
	}
277
 
278
	/*
279
	 * function to store website results
280
	 */
281
	function storeWebsiteAnalytics($websiteId, $reportDate, $source = "google") {
282
		$websiteId = intval($websiteId);
283
		$websiteCtrler = new WebsiteController();
284
		$websiteInfo = $websiteCtrler->__getWebsiteInfo($websiteId);
285
		$list = $this->__getWebmasterKeywords("website_id=$websiteId and status=1");
286
		$keywordList = array();
287
		if (!empty($list)) {foreach ($list as $info) $keywordList[$info['name']] = $info;}
288
		$result['status'] = true;
289
 
290
		$paramList = array(
291
			'startDate' => $reportDate,
292
			'endDate' => $reportDate,
293
			'dimensions' => ['query'],
294
		);
295
 
296
		// query results from api and verify no error occured
297
		$result = $this->getQueryResults($websiteInfo['user_id'], $websiteInfo['url'], $paramList);
298
		if ($result['status']) {
299
 
300
			// loop through the result list
301
			foreach ($result['resultList'] as $reportInfo) {
302
				$keywordName = $reportInfo['keys'][0];
303
 
304
				// check if keyword is already existing in the db table, else insert it
305
				$keywordId = isset($keywordList[$keywordName]) ? intval($keywordList[$keywordName]['id']) : 0;
306
				if ($keywordId == 0) {$keywordId = $this->__generateKeywordId($websiteInfo['id'], $keywordName);}
307
 
308
				$info = array(
309
					'clicks' => $reportInfo['clicks'],
310
					'impressions' => $reportInfo['impressions'],
311
					'ctr' => round($reportInfo['ctr'] * 100, 2),
312
					'average_position' => $reportInfo['position'],
313
					'report_date' => $reportDate,
314
					'source' => $source,
315
				);
316
 
317
				$this->insertKeywordAnalytics($keywordId, $info);
318
 
319
			}
320
 
321
		}
322
 
323
		// if keyword report generated successfully
324
		if ($result['status']) {
325
 
326
			// store website analytics
327
			$paramList = array(
328
				'startDate' => $reportDate,
329
				'endDate' => $reportDate,
330
			);
331
 
332
			// query results from api and verify no error occured
333
			$result = $this->getQueryResults($websiteInfo['user_id'], $websiteInfo['url'], $paramList);
334
 
335
			// if status is success
336
			if ($result['status']) {
337
				$reportInfo = !empty($result['resultList'][0]) ? $result['resultList'][0] : array();
338
				$info = array(
339
					'clicks' => !empty($reportInfo->clicks) ? $reportInfo->clicks : 0,
340
					'impressions' => !empty($reportInfo->impressions) ? $reportInfo->impressions : 0,
341
					'ctr' => !empty($reportInfo->ctr) ? $reportInfo->ctr * 100 : 0,
342
					'average_position' => !empty($reportInfo->position) ? $reportInfo->position : 0,
343
					'report_date' => $reportDate,
344
					'source' => $source,
345
				);
346
 
347
				$this->insertWebsiteAnalytics($websiteId, $info);
348
			}
349
 
350
		}
351
 
352
		return $result;
353
 
354
	}
355
 
356
	/*
357
	 * function to insert keyword analytics
358
	 */
359
	function insertKeywordAnalytics($keywordId, $reportInfo, $clearExisting = true) {
360
		$keywordId = intval($keywordId);
361
		$source = addslashes($reportInfo['source']);
362
		$resultDate = addslashes($reportInfo['report_date']);
363
 
364
		if ($clearExisting) {
365
			$whereCond = "keyword_id=$keywordId and report_date='$resultDate' and source='$source'";
366
			$this->dbHelper->deleteRows('keyword_analytics', $whereCond);
367
		}
368
 
369
		$dataList = array(
370
			'keyword_id' => $keywordId,
371
			'clicks|int' => $reportInfo['clicks'],
372
			'impressions|int' => $reportInfo['impressions'],
373
			'ctr|float' => round($reportInfo['ctr'], 2),
374
			'average_position|float' => round($reportInfo['average_position'], 2),
375
			'report_date' => $resultDate,
376
			'source' => $source,
377
		);
378
 
379
		$this->dbHelper->insertRow('keyword_analytics', $dataList);
380
 
381
	}
382
 
383
	/*
384
	 * function to insert website analytics
385
	 */
386
	function insertWebsiteAnalytics($websiteId, $reportInfo, $clearExisting = true) {
387
		$websiteId = intval($websiteId);
388
		$source = addslashes($reportInfo['source']);
389
		$resultDate = addslashes($reportInfo['report_date']);
390
 
391
		if ($clearExisting) {
392
			$whereCond = "website_id=$websiteId and report_date='$resultDate' and source='$source'";
393
			$this->dbHelper->deleteRows('website_search_analytics', $whereCond);
394
		}
395
 
396
		$dataList = array(
397
			'website_id' => $websiteId,
398
			'clicks|int' => $reportInfo['clicks'],
399
			'impressions|int' => $reportInfo['impressions'],
400
			'ctr|float' => round($reportInfo['ctr'], 2),
401
			'average_position|float' => round($reportInfo['average_position'], 2),
402
			'report_date' => $resultDate,
403
			'source' => $source,
404
		);
405
 
406
		$this->dbHelper->insertRow('website_search_analytics', $dataList);
407
 
408
	}
409
 
410
	# function check whether webmaster reports already saved
411
	function isReportsExists($websiteId, $resultDate, $source = "google") {
412
		$websiteId = intval($websiteId);
413
		$source = addslashes($source);
414
		$resultDate = addslashes($resultDate);
415
		$whereCond = "website_id=$websiteId and report_date='$resultDate' and source='$source'";
416
		$info = $this->dbHelper->getRow("website_search_analytics", $whereCond, "website_id");
417
		return !empty($info['website_id']) ? true : false;
418
	}
419
 
420
	# func to show webmasterkeyword report summary
421
	function viewKeywordSearchSummary($searchInfo = '', $summaryPage = false, $cronUserId=false) {
422
 
423
		$userId = !empty($cronUserId) ? $cronUserId : isLoggedIn();
424
		$source = $this->sourceList[0];
425
		$this->set('summaryPage', $summaryPage);
426
		$this->set('searchInfo', $searchInfo);
427
		$this->set('cronUserId', $cronUserId);
428
 
429
		$exportVersion = false;
430
		switch($searchInfo['doc_type']){
431
 
432
			case "export":
433
				$exportVersion = true;
434
				$exportContent = "";
435
				break;
436
 
437
			case "pdf":
438
				$this->set('pdfVersion', true);
439
				break;
440
 
441
			case "print":
442
				$this->set('printVersion', true);
443
				break;
444
		}
445
 
446
		$fromTime = !empty($searchInfo['from_time']) ? addslashes($searchInfo['from_time']) : date('Y-m-d', strtotime('-3 days'));
447
		$toTime = !empty($searchInfo['to_time']) ? addslashes($searchInfo['to_time']) : date('Y-m-d', strtotime('-2 days'));
448
		$this->set('fromTime', $fromTime);
449
		$this->set('toTime', $toTime);
450
 
451
		$websiteController = New WebsiteController();
452
		$wList = $websiteController->__getAllWebsites($userId, true);
453
		$websiteList = [];
454
		foreach ($wList as $wInfo) $websiteList[$wInfo['id']] = $wInfo;
455
		$websiteList = count($websiteList) ? $websiteList : array(0);
456
		$this->set('websiteList', $websiteList);
457
		$websiteId = intval($searchInfo['website_id']);
458
		$this->set('websiteId', $websiteId);
459
 
460
		// to find order col
461
		if (!empty($searchInfo['order_col'])) {
462
			$orderCol = $searchInfo['order_col'];
463
			$orderVal = getOrderByVal($searchInfo['order_val']);
464
		} else {
465
			$orderCol = "clicks";
466
			$orderVal = 'DESC';
467
		}
468
 
469
		$this->set('orderCol', $orderCol);
470
		$this->set('orderVal', $orderVal);
471
		$scriptName = $summaryPage ? "archive.php" : "webmaster-tools.php";
472
		$scriptPath = SP_WEBPATH . "/$scriptName?sec=viewKeywordReports&website_id=$websiteId";
473
		$scriptPath .= "&from_time=$fromTime&to_time=$toTime&search_name=" . $searchInfo['search_name'];
474
		$scriptPath .= "&order_col=$orderCol&order_val=$orderVal&report_type=keyword-search-reports";
475
 
476
		// set website id to get exact keywords of a user
477
		if (!empty($websiteId)) {
478
			$conditions = " and k.website_id=$websiteId";
479
		} else {
480
			$conditions = " and k.website_id in (".implode(',', array_keys($websiteList)).")";
481
		}
482
 
483
		$conditions .= !empty($searchInfo['search_name']) ? " and k.name like '%".addslashes($searchInfo['search_name'])."%'" : "";
484
 
485
		$subSql = "select [cols] from webmaster_keywords k, keyword_analytics r where k.id=r.keyword_id
486
		and k.status=1 $conditions and r.source='$source' and r.report_date='$toTime'";
487
 
488
		$sql = "
489
		(" . str_replace("[cols]", "k.id,k.name,k.website_id,r.clicks,r.impressions,r.ctr,r.average_position", $subSql) . ")
490
		UNION
491
		(select k.id,k.name,k.website_id,0,0,0,0 from webmaster_keywords k where k.status=1 $conditions
492
		and k.id not in (". str_replace("[cols]", "distinct(k.id)", $subSql) ."))
493
		order by " . addslashes($orderCol) . " " . addslashes($orderVal);
494
 
495
		if ($orderCol != 'name') $sql .= ", name";
496
 
497
		// pagination setup, if not from cron job email send function, pdf and export action
498
		if (!in_array($searchInfo['doc_type'], array("pdf", "export"))) {
499
			$this->db->query($sql, true);
500
			$this->paging->setDivClass('pagingdiv');
501
			$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
502
			$pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
503
			$this->set('pagingDiv', $pagingDiv);
504
			$this->set('pageNo', $searchInfo['pageno']);
505
			$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
506
		}
507
 
508
		# set report list
509
		$baseReportList = $this->db->select($sql);
510
		$this->set('baseReportList', $baseReportList);
511
		$this->set('colList', $this->colList);
512
 
513
		// if keywords existing
514
		if (!empty($baseReportList)) {
515
 
516
			$keywordIdList = array();
517
			foreach ($baseReportList as $info) {
518
				$keywordIdList[] = $info['id'];
519
			}
520
 
521
			$sql = "select k.id,k.name,k.website_id,r.clicks,r.impressions,r.ctr,r.average_position
522
			from webmaster_keywords k, keyword_analytics r where k.id=r.keyword_id
523
			and k.status=1 $conditions and r.source='$source' and r.report_date='$fromTime'";
524
			$sql .= " and k.id in(" . implode(",", $keywordIdList) . ")";
525
			$reportList = $this->db->select($sql);
526
			$compareReportList = array();
527
 
528
			foreach ($reportList as $info) {
529
				$compareReportList[$info['id']] = $info;
530
			}
531
 
532
			$this->set('compareReportList', $compareReportList);
533
 
534
		}
535
 
536
		if ($exportVersion) {
537
			$spText = $_SESSION['text'];
538
			$reportHeading =  $this->spTextTools['Keyword Search Summary']."($fromTime - $toTime)";
539
			$exportContent .= createExportContent( array('', $reportHeading, ''));
540
			$exportContent .= createExportContent( array());
541
			$headList = array($spText['common']['Website'], $spText['common']['Keyword']);
542
 
543
			$pTxt = str_replace("-", "/", substr($fromTime, -5));
544
			$cTxt = str_replace("-", "/", substr($toTime, -5));
545
			foreach ($this->colList as $colKey => $colLabel) {
546
				if ($colKey == 'name') continue;
547
				$headList[] = $colLabel . "($pTxt)";
548
				$headList[] = $colLabel . "($cTxt)";
549
				$headList[] = $colLabel . "(+/-)";
550
			}
551
 
552
			$exportContent .= createExportContent($headList);
553
			foreach($baseReportList as $listInfo){
554
 
555
				$valueList = array($websiteList[$listInfo['website_id']]['url'], $listInfo['name']);
556
				foreach ($this->colList as $colName => $colVal) {
557
					if ($colName == 'name') continue;
558
 
559
					$currRank = isset($listInfo[$colName]) ? $listInfo[$colName] : 0;
560
					$prevRank = isset($compareReportList[$listInfo['id']][$colName]) ? $compareReportList[$listInfo['id']][$colName] : 0;
561
					$rankDiff = "";
562
 
563
					// if both ranks are existing
564
					if ($prevRank != '' && $currRank != '') {
565
						$rankDiff = $currRank - $prevRank;
566
						if ($colName == 'average_position') $rankDiff = $rankDiff * -1;
567
					}
568
 
569
					$valueList[] = $prevRank;
570
					$valueList[] = $currRank;
571
					$valueList[] = $rankDiff;
572
				}
573
 
574
				$exportContent .= createExportContent( $valueList);
575
			}
576
 
577
			if ($summaryPage) {
578
				return $exportContent;
579
			} else {
580
				exportToCsv('keyword_search_summary', $exportContent);
581
			}
582
 
583
		} else {
584
 
585
			// if pdf export
586
			if ($summaryPage) {
587
				return $this->getViewContent('webmaster/keyword_search_analytics_summary');
588
			} else {
589
				// if pdf export
590
				if ($searchInfo['doc_type'] == "pdf") {
591
					exportToPdf($this->getViewContent('webmaster/keyword_search_analytics_summary'), "keyword_search_summary_$fromTime-$toTime.pdf");
592
				} else {
593
					$this->set('searchInfo', $searchInfo);
594
					$this->render('webmaster/keyword_search_analytics_summary');
595
				}
596
			}
597
 
598
		}
599
	}
600
 
601
	# func to show website search report summary
602
	function viewWebsiteSearchSummary($searchInfo = '', $summaryPage = false, $cronUserId=false) {
603
 
604
		$userId = !empty($cronUserId) ? $cronUserId : isLoggedIn();
605
		$websiteController = New WebsiteController();
606
		$exportVersion = false;
607
		$source = $this->sourceList[0];
608
		$this->set('summaryPage', $summaryPage);
609
		$this->set('searchInfo', $searchInfo);
610
 
611
		switch($searchInfo['doc_type']){
612
 
613
			case "export":
614
				$exportVersion = true;
615
				$exportContent = "";
616
				break;
617
 
618
			case "pdf":
619
				$this->set('pdfVersion', true);
620
				break;
621
 
622
			case "print":
623
				$this->set('printVersion', true);
624
				break;
625
		}
626
 
627
		$fromTime = !empty($searchInfo['from_time']) ? addslashes($searchInfo['from_time']) : date('Y-m-d', strtotime('-3 days'));
628
		$toTime = !empty($searchInfo['to_time']) ? addslashes($searchInfo['to_time']) : date('Y-m-d', strtotime('-2 days'));
629
		$this->set('fromTime', $fromTime);
630
		$this->set('toTime', $toTime);
631
 
632
		// to find order col
633
		if (!empty($searchInfo['order_col'])) {
634
			$orderCol = $searchInfo['order_col'];
635
			$orderVal = getOrderByVal($searchInfo['order_val']);
636
		} else {
637
			$orderCol = "clicks";
638
			$orderVal = 'DESC';
639
		}
640
 
641
		$this->set('orderCol', $orderCol);
642
		$this->set('orderVal', $orderVal);
643
		$scriptName = $summaryPage ? "archive.php" : "webmaster-tools.php";
644
		$scriptPath = SP_WEBPATH . "/$scriptName?sec=viewWebsiteSearchSummary&website_id=$websiteId";
645
		$scriptPath .= "&from_time=$fromTime&to_time=$toTime&search_name=" . $searchInfo['search_name'];
646
		$scriptPath .= "&order_col=$orderCol&order_val=$orderVal&report_type=website-search-reports";
647
 
648
		$websiteId = intval($searchInfo['website_id']);
649
		$conditions = !empty($websiteId) ? " and w.id=$websiteId" : "";
650
		$conditions .= isAdmin() ? "" : $websiteController->getWebsiteUserAccessCondition($userId);
651
		$conditions .= !empty($searchInfo['search_name']) ? " and w.url like '%".addslashes($searchInfo['search_name'])."%'" : "";
652
		$this->set('websiteId', $websiteId);
653
 
654
		$subSql = "select [cols] from websites w, website_search_analytics r where w.id=r.website_id
655
		and w.status=1 $conditions and r.source='$source' and r.report_date='$fromTime'";
656
 
657
		$unionOrderCol = ($orderCol == 'name') ? "url" : $orderCol;
658
		$sql = "
659
		(" . str_replace("[cols]", "w.id,w.url,w.name,r.clicks,r.impressions,r.ctr,r.average_position", $subSql) . ")
660
		UNION
661
		(select w.id,w.url,w.name,0,0,0,0 from websites w where w.status=1 $conditions
662
		and w.id not in (". str_replace("[cols]", "distinct(w.id)", $subSql) ."))
663
		order by " . addslashes($unionOrderCol) . " " . addslashes($orderVal);
664
 
665
		if ($orderCol != 'name') $sql .= ", url";
666
 
667
		// pagination setup, if not from cron job email send function, pdf and export action
668
		if (!in_array($searchInfo['doc_type'], array("pdf", "export")) && !$cronUserId) {
669
 
670
			$this->db->query($sql, true);
671
			$this->paging->setDivClass('pagingdiv');
672
			$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
673
			$pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
674
			$this->set('pagingDiv', $pagingDiv);
675
			$this->set('pageNo', $searchInfo['pageno']);
676
 
677
			$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
678
		}
679
 
680
		# set report list
681
		$baseReportList = $this->db->select($sql);
682
		$this->set('baseReportList', $baseReportList);
683
		$this->set('colList', $this->colList);
684
 
685
		// if keywords existing
686
		if (!empty($baseReportList)) {
687
 
688
			$websiteIdList = array();
689
			foreach ($baseReportList as $info) {
690
				$websiteIdList[] = $info['id'];
691
			}
692
 
693
			$sql = "select w.id,w.name,w.url,r.clicks,r.impressions,r.ctr,r.average_position
694
			from websites w, website_search_analytics r where w.id=r.website_id
695
			and w.status=1 $conditions and r.source='$source' and r.report_date='$toTime'";
696
			$sql .= " and w.id in(" . implode(",", $websiteIdList) . ")";
697
			$reportList = $this->db->select($sql);
698
			$compareReportList = array();
699
 
700
			foreach ($reportList as $info) {
701
				$compareReportList[$info['id']] = $info;
702
			}
703
 
704
			$this->set('compareReportList', $compareReportList);
705
 
706
		}
707
 
708
		if ($exportVersion) {
709
			$spText = $_SESSION['text'];
710
			$reportHeading =  $this->spTextTools['Website Search Summary']."($fromTime - $toTime)";
711
			$exportContent .= createExportContent( array());
712
			$exportContent .= createExportContent( array());
713
			$exportContent .= createExportContent( array('', $reportHeading, ''));
714
			$exportContent .= createExportContent( array());
715
			$headList = array($spText['common']['Website']);
716
 
717
			$pTxt = str_replace("-", "/", substr($fromTime, -5));
718
			$cTxt = str_replace("-", "/", substr($toTime, -5));
719
			foreach ($this->colList as $colKey => $colLabel) {
720
				if ($colKey == 'name') continue;
721
				$headList[] = $colLabel . "($pTxt)";
722
				$headList[] = $colLabel . "($cTxt)";
723
				$headList[] = $colLabel . "(+/-)";
724
			}
725
 
726
			$exportContent .= createExportContent($headList);
727
			foreach($baseReportList as $listInfo){
728
 
729
				$valueList = array($listInfo['url']);
730
				foreach ($this->colList as $colName => $colVal) {
731
					if ($colName == 'name') continue;
732
 
733
					$prevRank = isset($listInfo[$colName]) ? $listInfo[$colName] : 0;
734
					$currRank = isset($compareReportList[$listInfo['id']][$colName]) ? $compareReportList[$listInfo['id']][$colName] : 0;
735
					$rankDiff = "";
736
 
737
					// if both ranks are existing
738
					if ($prevRank != '' && $currRank != '') {
739
						$rankDiff = $currRank - $prevRank;
740
						if ($colName == 'average_position') $rankDiff = $rankDiff * -1;
741
					}
742
 
743
					$valueList[] = $prevRank;
744
					$valueList[] = $currRank;
745
					$valueList[] = $rankDiff;
746
				}
747
 
748
				$exportContent .= createExportContent( $valueList);
749
			}
750
 
751
			if ($summaryPage) {
752
				return $exportContent;
753
			} else {
754
				exportToCsv('website_search_summary', $exportContent);
755
			}
756
 
757
		} else {
758
 
759
			// if pdf export
760
			if ($summaryPage) {
761
				return $this->getViewContent('webmaster/website_search_analytics_summary');
762
			} else {
763
 
764
			    $websiteList = $websiteController->__getAllWebsites($userId, true);
765
				$this->set('websiteList', $websiteList);
766
 
767
				if ($searchInfo['doc_type'] == "pdf") {
768
					exportToPdf($this->getViewContent('webmaster/website_search_analytics_summary'), "website_search_summary_$fromTime-$toTime.pdf");
769
				} else {
770
					$this->set('searchInfo', $searchInfo);
771
					$this->render('webmaster/website_search_analytics_summary');
772
				}
773
			}
774
 
775
		}
776
	}
777
 
778
	# func to show website search reports
779
	function viewWebsiteSearchReports($searchInfo = '') {
780
 
781
		$userId = isLoggedIn();
782
		if (!empty ($searchInfo['from_time'])) {
783
			$fromTime = addslashes($searchInfo['from_time']);
784
		} else {
785
			$fromTime = date('Y-m-d', strtotime('-17 days'));
786
		}
787
 
788
		if (!empty ($searchInfo['to_time'])) {
789
			$toTime = addslashes($searchInfo['to_time']);
790
		} else {
791
			$toTime = date('Y-m-d', strtotime('-2 days'));
792
		}
793
 
794
		$this->set('fromTime', $fromTime);
795
		$this->set('toTime', $toTime);
796
 
797
		$source = $this->sourceList[0];
798
		$this->set('source', $source);
799
 
800
		$websiteController = New WebsiteController();
801
		$websiteList = $websiteController->__getAllWebsites($userId, true);
802
		$this->set('websiteList', $websiteList);
803
		$websiteId = empty($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
804
		$this->set('websiteId', $websiteId);
805
 
806
		$conditions = empty($websiteId) ? "" : " and s.website_id=$websiteId";
807
		$sql = "select s.* ,w.name from website_search_analytics s,websites w  where s.website_id=w.id
808
		and report_date >= '$fromTime' and report_date <= '$toTime' and source='$source' $conditions order by report_date";
809
		$reportList = $this->db->select($sql);
810
 
811
		$colList = array_keys($this->colList);
812
		array_shift($colList);
813
		foreach ($colList as $col) $prevRank[$col] = 0;
814
 
815
		# loop through rank
816
		foreach ($reportList as $key => $repInfo) {
817
 
818
			// if not the first row, find differences in rank
819
			if ($key)  {
820
 
821
				foreach ($colList as $col) $rankDiff[$col] = '';
822
 
823
				foreach ($colList as $col) {
824
					$rankDiff[$col] = round($repInfo[$col] - $prevRank[$col], 2);
825
 
826
					if (empty($rankDiff[$col])) continue;
827
 
828
					if ($col == "average_position" ) $rankDiff[$col] = $rankDiff[$col] * -1;
829
					$rankClass = ($rankDiff[$col] > 0) ? 'green' : 'red';
830
 
831
					$rankDiff[$col] = "<font class='$rankClass'>($rankDiff[$col])</font>";
832
					$reportList[$key]['rank_diff_'.$col] = empty($rankDiff[$col]) ? '' : $rankDiff[$col];
833
 
834
				}
835
 
836
			}
837
 
838
			foreach ($colList as $col) $prevRank[$col] = $repInfo[$col];
839
 
840
		}
841
 
842
		$this->set('list', array_reverse($reportList, true));
843
		$this->render('webmaster/website_search_reports');
844
	}
845
 
846
	# func to show keyword search reports
847
	function viewKeywordSearchReports($searchInfo = '') {
848
 
849
		$userId = isLoggedIn();
850
 
851
		if (!empty ($searchInfo['from_time'])) {
852
			$fromTimeDate = addslashes($searchInfo['from_time']);
853
		} else {
854
			$fromTimeDate = date('Y-m-d', strtotime('-17 days'));
855
		}
856
 
857
		if (!empty ($searchInfo['to_time'])) {
858
			$toTimeDate = addslashes($searchInfo['to_time']);
859
		} else {
860
			$toTimeDate = date('Y-m-d', strtotime('-2 days'));
861
		}
862
 
863
		$this->set('fromTime', $fromTimeDate);
864
		$this->set('toTime', $toTimeDate);
865
 
866
		if(!empty($searchInfo['keyword_id']) && !empty($searchInfo['rep'])){
867
			$searchInfo['keyword_id'] = intval($searchInfo['keyword_id']);
868
			$keywordInfo = $this->__getWebmasterKeywordInfo($searchInfo['keyword_id']);
869
			$searchInfo['website_id'] = $keywordInfo['website_id'];
870
		}
871
 
872
		$websiteController = New WebsiteController();
873
		$websiteList = $websiteController->__getAllWebsites($userId, true);
874
		$this->set('websiteList', $websiteList);
875
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
876
		$this->set('websiteId', $websiteId);
877
 
878
		$keywordList = $this->__getWebmasterKeywords("website_id=$websiteId  and status=1 order by name");
879
		$this->set('keywordList', $keywordList);
880
		$keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : $searchInfo['keyword_id'];
881
		$this->set('keywordId', $keywordId);
882
 
883
		$conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId";
884
		$sql = "select s.* from keyword_analytics s
885
		where report_date>='$fromTimeDate' and report_date<='$toTimeDate' $conditions
886
		order by s.report_date";
887
		$reportList = $this->db->select($sql);
888
 
889
		$colList = array_keys($this->colList);
890
		array_shift($colList);
891
		foreach ($colList as $col) $prevRank[$col] = 0;
892
 
893
		# loop through rank
894
		foreach ($reportList as $key => $repInfo) {
895
 
896
			// if not the first row, find differences in rank
897
			if ($key)  {
898
 
899
				foreach ($colList as $col) $rankDiff[$col] = '';
900
 
901
				foreach ($colList as $col) {
902
					$rankDiff[$col] = round($repInfo[$col] - $prevRank[$col], 2);
903
					if (empty($rankDiff[$col])) continue;
904
 
905
					if ($col == "average_position" ) $rankDiff[$col] = $rankDiff[$col] * -1;
906
					$rankClass = ($rankDiff[$col] > 0) ? 'green' : 'red';
907
 
908
					$rankDiff[$col] = "<font class='$rankClass'>($rankDiff[$col])</font>";
909
					$reportList[$key]['rank_diff_'.$col] = empty($rankDiff[$col]) ? '' : $rankDiff[$col];
910
				}
911
 
912
			}
913
 
914
			foreach ($colList as $col) $prevRank[$col] = $repInfo[$col];
915
 
916
		}
917
 
918
		$this->set('list', array_reverse($reportList, true));
919
		$this->render('webmaster/keyword_search_reports');
920
 
921
	}
922
 
923
	# func to show keyword search reports in graph
924
	function viewKeywordSearchGraphReports($searchInfo = '') {
925
 
926
		$userId = isLoggedIn();
927
 
928
		if (!empty ($searchInfo['from_time'])) {
929
			$fromTimeDate = addslashes($searchInfo['from_time']);
930
		} else {
931
			$fromTimeDate = date('Y-m-d', strtotime('-17 days'));
932
		}
933
 
934
		if (!empty ($searchInfo['to_time'])) {
935
			$toTimeDate = addslashes($searchInfo['to_time']);
936
		} else {
937
			$toTimeDate = date('Y-m-d', strtotime('-2 days'));
938
		}
939
 
940
		$this->set('fromTime', $fromTimeDate);
941
		$this->set('toTime', $toTimeDate);
942
 
943
		if(!empty($searchInfo['keyword_id']) && !empty($searchInfo['rep'])){
944
			$searchInfo['keyword_id'] = intval($searchInfo['keyword_id']);
945
			$keywordInfo = $this->__getWebmasterKeywordInfo($searchInfo['keyword_id']);
946
			$searchInfo['website_id'] = $keywordInfo['website_id'];
947
		}
948
 
949
		$websiteController = New WebsiteController();
950
		$websiteList = $websiteController->__getAllWebsites($userId, true);
951
		$this->set('websiteList', $websiteList);
952
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
953
		$this->set('websiteId', $websiteId);
954
 
955
		$keywordList = $this->__getWebmasterKeywords("website_id=$websiteId  and status=1 order by name");
956
		$this->set('keywordList', $keywordList);
957
		$keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : $searchInfo['keyword_id'];
958
		$this->set('keywordId', $keywordId);
959
 
960
		$conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId";
961
		$sql = "select s.* from keyword_analytics s
962
		where report_date>='$fromTimeDate' and report_date<='$toTimeDate' $conditions
963
		order by s.report_date";
964
		$reportList = $this->db->select($sql);
965
 
966
		// if reports not empty
967
		$colList = $this->colList;
968
		array_shift($colList);
969
		$this->set('colList', $colList);
970
		$this->set('searchInfo', $searchInfo);
971
 
972
		$graphColList = array();
973
		if (!empty($searchInfo['attr_type'])) {
974
			$graphColList[$searchInfo['attr_type']] = $colList[$searchInfo['attr_type']];
975
			if ($searchInfo['attr_type'] == 'average_position') { $this->set('reverseDir', true);}
976
		} else {
977
			array_pop($colList);
978
			$graphColList = $colList;
979
		}
980
 
981
		if (!empty($reportList)) {
982
 
983
			$dataArr = "['Date', '" . implode("', '", array_values($graphColList)) . "']";
984
 
985
			// loop through data list
986
			foreach ($reportList as $dataInfo) {
987
 
988
				$valStr = "";
989
				foreach ($graphColList as $seId => $seVal) {
990
					$valStr .= ", ";
991
					$valStr .= !empty($dataInfo[$seId]) ? $dataInfo[$seId] : 0;
992
				}
993
 
994
				$dataArr .= ", ['{$dataInfo['report_date']}' $valStr]";
995
			}
996
 
997
			$this->set('dataArr', $dataArr);
998
			$this->set('graphTitle', $this->spTextTools['Keyword Search Reports']);
999
			$graphContent = $this->getViewContent('report/graph');
1000
		} else {
1001
			$graphContent = showErrorMsg($_SESSION['text']['common']['No Records Found'], false, true);
1002
		}
1003
 
1004
		// get graph content
1005
		$this->set('graphContent', $graphContent);
1006
		$this->render('webmaster/graphicalreport');
1007
 
1008
	}
1009
 
1010
	# func to show website search reports in graph
1011
	function viewWebsiteSearchGraphReports($searchInfo = '') {
1012
 
1013
		$userId = isLoggedIn();
1014
 
1015
		if (!empty ($searchInfo['from_time'])) {
1016
			$fromTimeDate = addslashes($searchInfo['from_time']);
1017
		} else {
1018
			$fromTimeDate = date('Y-m-d', strtotime('-17 days'));
1019
		}
1020
 
1021
		if (!empty ($searchInfo['to_time'])) {
1022
			$toTimeDate = addslashes($searchInfo['to_time']);
1023
		} else {
1024
			$toTimeDate = date('Y-m-d', strtotime('-2 days'));
1025
		}
1026
 
1027
		$this->set('fromTime', $fromTimeDate);
1028
		$this->set('toTime', $toTimeDate);
1029
 
1030
		$websiteController = New WebsiteController();
1031
		$websiteList = $websiteController->__getAllWebsites($userId, true);
1032
		$this->set('websiteList', $websiteList);
1033
		$websiteId = empty($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
1034
		$this->set('websiteId', $websiteId);
1035
 
1036
		$conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId";
1037
		$sql = "select s.* from website_search_analytics s
1038
		where report_date>='$fromTimeDate' and report_date<='$toTimeDate' $conditions
1039
		order by s.report_date";
1040
		$reportList = $this->db->select($sql);
1041
 
1042
		// if reports not empty
1043
		$colList = $this->colList;
1044
		array_shift($colList);
1045
		$this->set('colList', $colList);
1046
		$this->set('searchInfo', $searchInfo);
1047
 
1048
		$graphColList = array();
1049
		if (!empty($searchInfo['attr_type'])) {
1050
			$graphColList[$searchInfo['attr_type']] = $colList[$searchInfo['attr_type']];
1051
			if ($searchInfo['attr_type'] == 'average_position') { $this->set('reverseDir', true);}
1052
		} else {
1053
			array_pop($colList);
1054
			$graphColList = $colList;
1055
		}
1056
 
1057
		// format report list
1058
		if (!empty($reportList)) {
1059
 
1060
			$dataArr = "['Date', '" . implode("', '", array_values($graphColList)) . "']";
1061
 
1062
			// loop through data list
1063
			foreach ($reportList as $dataInfo) {
1064
 
1065
				$valStr = "";
1066
				foreach ($graphColList as $seId => $seVal) {
1067
					$valStr .= ", ";
1068
					$valStr .= !empty($dataInfo[$seId]) ? $dataInfo[$seId] : 0;
1069
				}
1070
 
1071
				$dataArr .= ", ['{$dataInfo['report_date']}' $valStr]";
1072
			}
1073
 
1074
			$this->set('dataArr', $dataArr);
1075
			$this->set('graphTitle', $this->spTextTools['Website Search Reports']);
1076
			$graphContent = $this->getViewContent('report/graph');
1077
		} else {
1078
			$graphContent = showErrorMsg($_SESSION['text']['common']['No Records Found'], false, true);
1079
		}
1080
 
1081
		// get graph content
1082
		$this->set('graphContent', $graphContent);
1083
		$this->render('webmaster/website_graphical_report');
1084
 
1085
	}
1086
 
1087
	# func to show quick checker
1088
	function viewQuickChecker($keywordInfo='') {
1089
		$userId = isLoggedIn();
1090
		$websiteController = New WebsiteController();
1091
		$websiteList = $websiteController->__getAllWebsites($userId, true);
1092
		$this->set('websiteList', $websiteList);
1093
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
1094
		$this->set('websiteId', $websiteId);
1095
		$this->set('fromTime', date('Y-m-d', strtotime('-3 days')));
1096
		$this->set('toTime', date('Y-m-d', strtotime('-2 days')));
1097
		$this->render('webmaster/quick_checker');
1098
	}
1099
 
1100
	# func to do quick report
1101
	function doQuickChecker($searchInfo = '') {
1102
 
1103
		if (!empty($searchInfo['website_id'])) {
1104
			$websiteId = intval($searchInfo['website_id']);
1105
			$websiteController = New WebsiteController();
1106
			$websiteInfo = $websiteController->__getWebsiteInfo($websiteId);
1107
			$this->set('websiteInfo', $websiteInfo);
1108
 
1109
			if (!empty($websiteInfo['url'])) {
1110
				$reportStartDate = !empty($searchInfo['from_time']) ? $searchInfo['from_time'] : date('Y-m-d', strtotime('-10 days'));
1111
				$reportEndDate = !empty($searchInfo['to_time']) ? $searchInfo['to_time'] : date('Y-m-d', strtotime('-2 days'));
1112
 
1113
				// store website analytics
1114
				$paramList = array(
1115
					'startDate' => $reportStartDate,
1116
					'endDate' => $reportEndDate,
1117
				);
1118
 
1119
				// query results from api and verify no error occured
1120
				$result = $this->getQueryResults($websiteInfo['user_id'], $websiteInfo['url'], $paramList);
1121
 
1122
				// if status is success
1123
				if ($result['status']) {
1124
					$reportInfo = !empty($result['resultList'][0]) ? $result['resultList'][0] : array();
1125
					$websiteReport = array(
1126
						'clicks' => !empty($reportInfo->clicks) ? $reportInfo->clicks : 0,
1127
						'impressions' => !empty($reportInfo->impressions) ? $reportInfo->impressions : 0,
1128
						'ctr' => !empty($reportInfo->ctr) ? $reportInfo->ctr * 100 : 0,
1129
						'average_position' => !empty($reportInfo->position) ? $reportInfo->position : 0,
1130
						'source' => $source,
1131
					);
1132
 
1133
					$this->set('websiteReport', $websiteReport);
1134
 
1135
					// find keyword reports
1136
					$paramList = array(
1137
						'startDate' => $reportStartDate,
1138
						'endDate' => $reportEndDate,
1139
						'dimensions' => ['query'],
1140
					);
1141
 
1142
					// query results from api and verify no error occured
1143
					$result = $this->getQueryResults($websiteInfo['user_id'], $websiteInfo['url'], $paramList);
1144
					if ($result['status']) {
1145
 
1146
						$keywordAnalytics = array();
1147
						foreach ($result['resultList'] as $resInfo) {
1148
							$keywordAnalytics[$resInfo['keys'][0]] = $resInfo;
1149
						}
1150
 
1151
						$this->set('keywordAnalytics', $keywordAnalytics);
1152
					}
1153
 
1154
					$this->set('searchInfo', $searchInfo);
1155
					$this->render('webmaster/quick_checker_results');
1156
					return true;
1157
 
1158
				}
1159
			}
1160
		}
1161
 
1162
		$errorMsg = !empty($result['msg']) ? $result['msg'] : "Internal error occured while accessing webmaster tools.";
1163
		showErrorMsg($errorMsg);
1164
 
1165
	}
1166
 
1167
	# func to show keyword select box
1168
	function showKeywordSelectBox($websiteId, $keywordId = ""){
1169
		$websiteId = intval($websiteId);
1170
		$this->set('keywordList', $this->__getWebmasterKeywords("website_id=$websiteId and status=1 order by name"));
1171
		$this->set('keywordId', $keywordId);
1172
		$this->render('keyword/keywordselectbox');
1173
	}
1174
 
1175
}
1176
?>