Subversion Repositories cheapmusic

Rev

Rev 103 | Details | Compare with Previous | 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
# class defines all report controller functions
24
class ReportController extends Controller {
25
	var $seLIst;
26
	var $showAll = false;
27
	var $proxyCheckCount = 1;
28
 
29
	# func to get keyword report summary
30
	function __getKeywordSearchReport($keywordId, $fromTime, $toTime, $apiCall = false){
31
		$positionInfo = array();
32
 
33
		if(empty($this->seLIst)){
34
			$seController = New SearchEngineController();
35
			$this->seLIst = $seController->__getAllSearchEngines();
36
		}
37
 
38
		$fromTimeLabel = date('Y-m-d', $fromTime);
39
		$toTimeLabel = date('Y-m-d', $toTime);
40
		foreach($this->seLIst as $seInfo){
155 - 41
			$sql = "select min(`rank`) as `rank`,result_date from searchresults
103 - 42
			where keyword_id=$keywordId and searchengine_id=".$seInfo['id']."
43
			and (result_date='$fromTimeLabel' or result_date='$toTimeLabel')
44
			group by result_date order by result_date DESC limit 0, 2";
45
			$reportList = $this->db->select($sql);
46
			$reportList = array_reverse($reportList);
47
 
48
			$prevRank = 0;
49
			$i = 0;
50
			foreach ($reportList as $key => $repInfo) {
51
				$rankDiff = '';
52
				if ($i > 0) {
53
					$rankDiff = $prevRank - $repInfo['rank'];
54
					if ($rankDiff > 0) {
55
						$rankDiff = $apiCall ? $rankDiff : "<font class='green'>($rankDiff)</font>";
56
					} elseif ($rankDiff < 0) {
57
						$rankDiff = $apiCall ? $rankDiff : "<font class='red'>($rankDiff)</font>";
58
					}
59
				}
60
				$positionInfo[$seInfo['id']]['rank_diff'] = empty ($rankDiff) ? '' : $rankDiff;
61
				$positionInfo[$seInfo['id']]['rank'] = $repInfo['rank'];
62
				$positionInfo[$seInfo['id']][$repInfo['result_date']] = $repInfo['rank'];
63
				$prevRank = $repInfo['rank'];
64
				$i++;
65
			}
66
		}
67
 
68
		return $positionInfo;
69
	}
70
 
71
 
72
	# func to show keyword report summary
73
	function showKeywordReportSummary($searchInfo = '') {
74
 
75
		$userId = isLoggedIn();
76
		$keywordController = New KeywordController();
77
		$exportVersion = false;
78
		switch($searchInfo['doc_type']){
79
 
80
			case "export":
81
				$exportVersion = true;
82
				$exportContent = "";
83
				break;
84
 
85
			case "pdf":
86
				$this->set('pdfVersion', true);
87
				break;
88
 
89
			case "print":
90
				$this->set('printVersion', true);
91
				break;
92
		}
93
 
94
		if (!empty ($searchInfo['from_time'])) {
95
			$fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00');
96
		} else {
97
			$fromTime = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
98
		}
99
 
100
		if (!empty ($searchInfo['to_time'])) {
101
			$toTime = strtotime($searchInfo['to_time'] . ' 00:00:00');
102
		} else {
103
			$toTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
104
		}
105
 
106
		$fromTimeTxt = date('Y-m-d', $fromTime);
107
		$toTimeTxt = date('Y-m-d', $toTime);
108
		$this->set('fromTime', $fromTimeTxt);
109
		$this->set('toTime', $toTimeTxt);
110
 
111
		$websiteController = New WebsiteController();
112
		$websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true);
113
		$this->set('websiteList', $websiteList);
114
		$websiteId = isset($searchInfo['website_id']) ? $searchInfo['website_id'] : $websiteList[0]['id'];
115
		$websiteId = intval($websiteId);
116
		$this->set('websiteId', $websiteId);
117
 
118
		$websiteUrl = "";
119
		foreach ($websiteList as $websiteInfo) {
120
		    if ($websiteInfo['id'] == $websiteId) {
121
		        $websiteUrl = $websiteInfo['url'];
122
		        break;
123
		    }
124
		}
125
		$this->set('websiteUrl', $websiteUrl);
126
 
127
		$seSearchUserId = isAdmin() ? "" : $userId;
128
		$this->seLIst = $keywordController->getUserKeywordSearchEngineList($seSearchUserId);
129
		$this->set('seList', $this->seLIst);
130
 
131
		// to find order col
132
        if (!empty($searchInfo['order_col'])) {
133
		    $orderCol = $searchInfo['order_col'];
134
		    $orderVal = getOrderByVal($searchInfo['order_val']);
135
		} else {
136
		    $orderCol = $this->seLIst[array_keys($this->seLIst)[0]]['id'];
137
		    $orderVal = 'ASC';
138
		}
139
 
140
		$this->set('orderCol', $orderCol);
141
		$this->set('orderVal', $orderVal);
142
		$scriptPath = SP_WEBPATH."/reports.php?sec=reportsum&website_id=$websiteId";
143
		$scriptPath .= "&from_time=$fromTimeTxt&to_time=$toTimeTxt&search_name=" . $searchInfo['search_name'];
144
		$scriptPath .= "&order_col=$orderCol&order_val=$orderVal";
145
 
146
		$conditions = " and w.status=1 and k.status=1";
147
		$conditions .= isAdmin() ? "" : $websiteController->getWebsiteUserAccessCondition($userId);
148
		$conditions .= !empty($websiteId) ? " and w.id=$websiteId" : "";
149
		$conditions .= !empty($searchInfo['search_name']) ? " and k.name like '%".addslashes($searchInfo['search_name'])."%'" : "";
150
 
151
		$subSql = "select [col] from keywords k,searchresults r, websites w
152
		where k.id=r.keyword_id and k.website_id=w.id $conditions
153
		and r.searchengine_id=".intval($orderCol)." and r.result_date='" . addslashes($toTimeTxt) . "'
154
		group by k.id";
155
 
155 - 156
		$unionOrderCol = ($orderCol == "keyword") ? "name" : "`rank`";
157
		$sql = "(". str_replace("[col]", "k.id,k.name,min(`rank`) `rank`,w.name website,w.url weburl", $subSql) .")
103 - 158
		UNION
159
		(select k.id,k.name,1000,w.name website,w.url weburl
160
		from keywords k, websites w
161
		where w.id=k.website_id $conditions and k.id not in
162
		(". str_replace("[col]", "distinct(k.id)", $subSql) ."))
163
		order by $unionOrderCol $orderVal";
164
 
165
		if ($unionOrderCol != 'name') $sql .= ", name";
166
 
167
		# pagination setup
168
		$this->db->query($sql, true);
169
		$this->paging->setDivClass('pagingdiv');
170
		$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
171
		$pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
172
		$this->set('pagingDiv', $pagingDiv);
173
		$this->set('pageNo', $searchInfo['pageno']);
174
 
175
		if (!in_array($searchInfo['doc_type'], array("pdf", "export"))) {
176
			$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
177
		}
178
 
179
		# set keywords list
180
		$list = $this->db->select($sql);
181
 
182
		$indexList = array();
183
		foreach($list as $keywordInfo){
184
			$positionInfo = $this->__getKeywordSearchReport($keywordInfo['id'], $fromTime, $toTime, true);
185
 
186
			// check whether the sorting search engine is there
187
		    $indexList[$keywordInfo['id']] = empty($positionInfo[$orderCol][$toTimeTxt]) ? 10000 : $positionInfo[$orderCol][$toTimeTxt];
188
 
189
			$keywordInfo['position_info'] = $positionInfo;
190
			$keywordList[$keywordInfo['id']] = $keywordInfo;
191
		}
192
 
193
		// sort array according the value
194
		if ($orderCol != 'keyword') {
195
    		if ($orderVal == 'DESC') {
196
    		    arsort($indexList);
197
    		} else {
198
    		    asort($indexList);
199
    		}
200
		}
201
		$this->set('indexList', $indexList);
202
 
203
		if ($exportVersion) {
204
			$spText = $_SESSION['text'];
205
			$reportHeading =  $this->spTextTools['Keyword Position Summary']."(".date('Y-m-d', $fromTime)." - ".date('Y-m-d', $toTime).")";
206
			$exportContent .= createExportContent( array('', $reportHeading, ''));
207
			$exportContent .= createExportContent( array());
208
			$headList = array($spText['common']['Website'], $spText['common']['Keyword']);
209
 
210
			$pTxt = str_replace("-", "/", substr($fromTimeTxt, -5));
211
			$cTxt = str_replace("-", "/", substr($toTimeTxt, -5));
212
			foreach ($this->seLIst as $seInfo) {
213
				$domainTxt = str_replace("www.", "", $seInfo['domain']);
214
				$headList[] = $domainTxt . "($cTxt)";
215
				$headList[] = $domainTxt . "($pTxt)";
216
				$headList[] = $domainTxt . "(+/-)";
217
			}
218
 
219
			$exportContent .= createExportContent( $headList);
220
			foreach($indexList as $keywordId => $rankValue){
221
			    $listInfo = $keywordList[$keywordId];
222
				$positionInfo = $listInfo['position_info'];
223
 
224
				$valueList = array($listInfo['weburl'], $listInfo['name']);
225
				foreach ($this->seLIst as $index => $seInfo){
226
 
227
					$rankInfo = $positionInfo[$seInfo['id']];
228
					$prevRank = isset($rankInfo[$fromTimeTxt]) ? $rankInfo[$fromTimeTxt] : "";
229
					$currRank = isset($rankInfo[$toTimeTxt]) ? $rankInfo[$toTimeTxt] : "";
230
					$rankDiff = "";
231
 
232
					// if both ranks are existing
233
					if ($prevRank != '' && $currRank != '') {
234
						$rankDiff = $prevRank - $currRank;
235
					}
236
 
237
					$valueList[] = $currRank;
238
					$valueList[] = $prevRank;
239
					$valueList[] = $rankDiff;
240
				}
241
 
242
				$exportContent .= createExportContent( $valueList);
243
			}
244
			exportToCsv('keyword_report_summary', $exportContent);
245
		} else {
246
			$this->set('list', $keywordList);
247
 
248
			// if pdf export
249
			if ($searchInfo['doc_type'] == "pdf") {
250
				exportToPdf($this->getViewContent('report/reportsummary'), "keyword_report_summary_$fromTimeTxt-$toTimeTxt.pdf");
251
			} else {
252
				$this->set('searchInfo', $searchInfo);
253
				$this->render('report/reportsummary');
254
			}
255
		}
256
	}
257
 
258
	# func to show reports
259
	function showReports($searchInfo = '') {
260
 
261
		$userId = isLoggedIn();
262
		if (!empty ($searchInfo['from_time'])) {
263
			$fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00');
264
		} else {
265
			$fromTime = @mktime(0, 0, 0, date('m'), date('d') - 30, date('Y'));
266
		}
267
		if (!empty ($searchInfo['to_time'])) {
268
			$toTime = strtotime($searchInfo['to_time'] . ' 23:59:59');
269
		} else {
270
			$toTime = @mktime();
271
		}
272
 
273
		$fromTimeDate = date('Y-m-d', $fromTime);
274
		$toTimeDate = date('Y-m-d', $toTime);
275
		$this->set('fromTime', $fromTimeDate);
276
		$this->set('toTime', $toTimeDate);
277
 
278
		$keywordController = New KeywordController();
279
		if(!empty($searchInfo['keyword_id']) && !empty($searchInfo['rep'])){
280
 
281
			$searchInfo['keyword_id'] = intval($searchInfo['keyword_id']);
282
			$keywordInfo = $keywordController->__getKeywordInfo($searchInfo['keyword_id']);
283
			$searchInfo['website_id'] = $keywordInfo['website_id'];
284
		}
285
 
286
		$websiteController = New WebsiteController();
287
		$websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true);
288
		$this->set('websiteList', $websiteList);
289
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
290
		$this->set('websiteId', $websiteId);
291
 
292
		$keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true);
293
		$this->set('keywordList', $keywordList);
294
		$keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : $searchInfo['keyword_id'];
295
		$this->set('keywordId', $keywordId);
296
 
297
		$seController = New SearchEngineController();
298
		$seList = $seController->__getAllSearchEngines();
299
		$this->set('seList', $seList);
300
		$seId = empty ($searchInfo['se_id']) ? $seList[0]['id'] : intval($searchInfo['se_id']);
301
		$this->set('seId', $seId);
302
		$this->set('seInfo', $seController->__getsearchEngineInfo($seId));
303
 
304
		$conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId";
305
		$conditions .= empty ($seId) ? "" : " and s.searchengine_id=$seId";
306
		$sql = "select s.*,sd.url,sd.title,sd.description from searchresults s,searchresultdetails sd
307
		where s.id=sd.searchresult_id and result_date>='$fromTimeDate' and result_date<='$toTimeDate' $conditions
308
		order by s.result_date";
309
		$repList = $this->db->select($sql);
310
 
311
		$reportList = array ();
312
		foreach ($repList as $repInfo) {
313
			$var = 'se' . $seId . $repInfo['keyword_id'] . $repInfo['result_date'];
314
			if (empty ($reportList[$var])) {
315
				$reportList[$var] = $repInfo;
316
			} else {
317
				if ($repInfo['rank'] < $reportList[$var]['rank']) {
318
					$reportList[$var] = $repInfo;
319
				}
320
			}
321
 
322
		}
323
 
324
		$prevRank = 0;
325
		$i = 0;
326
		foreach ($reportList as $key => $repInfo) {
327
			$rankDiff = '';
328
			if ($i > 0) {
329
				$rankDiff = $prevRank - $repInfo['rank'];
330
				if ($rankDiff > 0) {
331
					$rankDiff = "<font class='green'>($rankDiff)</font>";
332
				}
333
				elseif ($rankDiff < 0) {
334
					$rankDiff = "<font class='red'>($rankDiff)</font>";
335
				}
336
			}
337
			$reportList[$key]['rank_diff'] = empty ($rankDiff) ? '' : $rankDiff;
338
			$prevRank = $repInfo['rank'];
339
			$i++;
340
		}
341
 
342
		$this->set('list', array_reverse($reportList, true));
343
		$this->render('report/report');
344
	}
345
 
346
	# func to show reports in a time
347
	function showTimeReport($searchInfo = '') {
348
 
349
		$fromTime = addslashes($searchInfo['time']);
350
		$toTime = $fromTime + (3600 * 24);
351
		$keywordId = intval($searchInfo['keyId']);
352
		$seId = intval($searchInfo['seId']);
353
		$seController = New SearchEngineController();
354
		$this->set('seInfo', $seController->__getsearchEngineInfo($seId));
355
 
356
		$conditions = empty ($keywordId) ? "" : " and s.keyword_id=$keywordId";
357
		$conditions .= empty ($seId) ? "" : " and s.searchengine_id=$seId";
358
 
359
		$fromTimeDate = date('Y-m-d', $fromTime);
360
		$toTimeDate = date('Y-m-d', $toTime);
361
		$sql = "select s.*,sd.url,sd.title,sd.description from searchresults s,searchresultdetails sd
362
		where s.id=sd.searchresult_id and result_date>='$fromTimeDate' and result_date<'$toTimeDate' $conditions
363
		order by s.rank";
364
		$reportList = $this->db->select($sql);
365
		$this->set('list', $reportList);
366
		$this->render('report/timereport');
367
	}
368
 
369
	# func to show graphical reports
370
	function showGraphicalReports($searchInfo = '') {
371
 
372
		$userId = isLoggedIn();
373
		$fromTime = !empty($searchInfo['from_time']) ? $searchInfo['from_time'] : date('Y-m-d', strtotime('-30 days'));
374
		$toTime = !empty ($searchInfo['to_time']) ? $searchInfo['to_time'] : date("Y-m-d");
375
		$this->set('fromTime', $fromTime);
376
		$this->set('toTime', $toTime);
377
 
378
		$websiteController = New WebsiteController();
379
		$websiteList = $websiteController->__getAllWebsitesWithActiveKeywords($userId, true);
380
		$this->set('websiteList', $websiteList);
381
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
382
		$this->set('websiteId', $websiteId);
383
 
384
		$keywordController = New KeywordController();
385
		$keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true);
386
		$this->set('keywordList', $keywordList);
387
		$keywordId = empty ($searchInfo['keyword_id']) ? $keywordList[0]['id'] : intval($searchInfo['keyword_id']);
388
		$this->set('keywordId', $keywordId);
389
 
390
		$seController = New SearchEngineController();
391
		$seList = $seController->__getAllSearchEngines();
392
		$this->set('seList', $seList);
393
		$seId = empty ($searchInfo['se_id']) ? '' : intval($searchInfo['se_id']);
394
		$this->set('seId', $seId);
395
		$this->set('seNull', true);
396
 
397
		// get graph content
398
		$graphCtrler = new GraphController();
399
		$graphCtrler->spTextKeyword = $this->spTextKeyword;
400
		$graphContent = $graphCtrler->showKeywordPostionGraph($keywordId, $fromTime, $toTime, $seId);
401
		$this->set('graphContent', $graphContent);
402
 
403
		$this->render('report/graphicalreport');
404
	}
405
 
406
	# function to show an message in graph when no records exist
407
	function showMessageAsImage($msg='', $width=700, $height=30, $red=233, $green=14, $blue=91) {
408
 
409
		$im = imagecreate($width, $height);
410
        $bgColor = imagecolorallocate($im, 245, 248, 250);
411
        $textColor = imagecolorallocate($im, 233, 14, 91);
412
	    $fontFile = ($_SESSION['lang_code'] == 'ja') ? "fonts/M+1P+IPAG.ttf" : "fonts/tahoma.ttf";
413
	    imagettftext($im, 10, 0, 260, 20, $textColor, $fontFile, $msg);
414
        imagepng($im);
415
        imagedestroy($im);
416
        exit;
417
	}
418
 
419
	# function to show graph
420
	function showGraph($searchInfo = '') {
421
 
422
		$fromTimeDate = date('Y-m-d', $searchInfo['fromTime']);
423
		$toTimeDate = date('Y-m-d', $searchInfo['toTime']);
424
		$conditions = empty ($searchInfo['keywordId']) ? "" : " and s.keyword_id=".intval($searchInfo['keywordId']);
425
		$conditions .= empty ($searchInfo['seId']) ? "" : " and s.searchengine_id=".intval($searchInfo['seId']);
426
		$sql = "select s.*,se.domain from searchresults s,searchengines se
427
		where s.searchengine_id=se.id and result_date>='$fromTimeDate' and result_date<='$toTimeDate'
428
		$conditions order by s.result_date";
429
		$repList = $this->db->select($sql);
430
		$reportList = array ();
431
		$seList = array();
432
		foreach ($repList as $repInfo) {
433
			$var = $repInfo['searchengine_id'] . $repInfo['keyword_id'] . $repInfo['result_date'];
434
			if (empty ($reportList[$var])) {
435
				$reportList[$var] = $repInfo;
436
			} else {
437
				if ($repInfo['rank'] < $reportList[$var]['rank']) {
438
					$reportList[$var] = $repInfo;
439
				}
440
			}
441
 
442
			if(empty($seList[$repInfo['searchengine_id']])){
443
				$seList[$repInfo['searchengine_id']] = $repInfo['domain'];
444
			}
445
		}
446
		asort($seList);
447
 
448
		$dataList = array();
449
		$maxValue = 0;
450
		foreach($reportList as $repInfo){
451
			$seId = $repInfo['searchengine_id'];
452
			$dataList[$repInfo['result_date']][$seId] = $repInfo['rank'];
453
			$maxValue = ($repInfo['rank'] > $maxValue) ? $repInfo['rank'] : $maxValue;
454
		}
455
 
456
		// check whether the records are available for drawing graph
457
		if(empty($dataList) || empty($maxValue)) {
458
		    $kpText = ($_SESSION['lang_code'] == 'ja') ? $_SESSION['text']['common']['No Records Found']."!" : "No Records Found!";
459
		    $this->showMessageAsImage($kpText);
460
		}
461
 
462
		# Dataset definition
463
		$dataSet = new pData;
464
		foreach($dataList as $dataInfo){
465
			$i = 1;
466
			foreach($seList as $seId => $seVal){
467
				$val = empty($dataInfo[$seId]) ? 0 : $dataInfo[$seId];
468
				$dataSet->AddPoint($val, "Serie".$i++);
469
			}
470
		}
471
 
472
		$i = 1;
473
		foreach($seList as $seDomain){
474
			$dataSet->AddSerie("Serie$i");
475
			$dataSet->SetSerieName($seDomain, "Serie$i");
476
			$i++;
477
		}
478
 
479
		$serieCount = count($seList) + 1;
480
		$dataSet->AddPoint(array_keys($dataList), "Serie$serieCount");
481
		$dataSet->SetAbsciseLabelSerie("Serie$serieCount");
482
 
483
		# if language is japanese
484
		if ($_SESSION['lang_code'] == 'ja') {
485
		    $fontFile = "fonts/M+1P+IPAG.ttf";
486
		    $dataSet->SetXAxisName($_SESSION['text']['common']["Date"]);
487
		    $dataSet->SetYAxisName($_SESSION['text']['common']["Rank"]);
488
		} else {
489
	        $fontFile = "fonts/tahoma.ttf";
490
		    $dataSet->SetXAxisName("Date");
491
		    $dataSet->SetYAxisName("Rank");
492
		}
493
 
494
		/* commented to fix invalid date in graphical reports x axis issue */
495
		// $dataSet->SetXAxisFormat("date");
496
 
497
		# Initialise the graph
498
		$chart = new pChart(720, 520);
499
		$chart->setFixedScale($maxValue, 1);
500
		$chart->setFontProperties($fontFile, 8);
501
		$chart->setGraphArea(85, 30, 670, 425);
502
		$chart->drawFilledRoundedRectangle(7, 7, 713, 513, 5, 240, 240, 240);
503
		$chart->drawRoundedRectangle(5, 5, 715, 515, 5, 230, 230, 230);
504
 
505
		$chart->drawGraphArea(255, 255, 255, TRUE);
506
		$getData = $dataSet->GetData();
507
		$getDataDes = $dataSet->GetDataDescription();
508
		$chart->drawScale($getData, $getDataDes, SCALE_NORMAL, 150, 150, 150, TRUE, 90, 2);
509
		$chart->drawGrid(4, TRUE, 230, 230, 230, 50);
510
 
511
		# Draw the 0 line
512
		$chart->setFontProperties($fontFile, 6);
513
		$chart->drawTreshold(0, 143, 55, 72, TRUE, TRUE);
514
 
515
		# Draw the line graph
516
		$getData = $dataSet->GetData();
517
		$getDataDes = $dataSet->GetDataDescription();
518
		$chart->drawLineGraph($getData, $getDataDes);
519
		$getData = $dataSet->GetData();
520
		$getDataDes = $dataSet->GetDataDescription();
521
		$chart->drawPlotGraph($getData, $getDataDes, 3, 2, 255, 255, 255);
522
 
523
		$j = 1;
524
		$chart->setFontProperties($fontFile, 10);
525
		foreach($seList as $seDomain){
526
			$getData = $dataSet->GetData();
527
			$getDataDes = $dataSet->GetDataDescription();
528
			$chart->writeValues($getData, $getDataDes, "Serie".$j++);
529
		}
530
 
531
		# Finish the graph
532
		$chart->setFontProperties("fonts/tahoma.ttf", 8);
533
		$getDataDes = $dataSet->GetDataDescription();
534
		$chart->drawLegend(90, 35, $getDataDes, 255, 255, 255);
535
		$chart->setFontProperties($fontFile, 10);
536
		$kpText = ($_SESSION['lang_code'] == 'ja') ? $this->spTextKeyword["Keyword Position Report"] : "Keyword Position Report";
537
		$chart->drawTitle(60, 22, $kpText, 50, 50, 50, 585);
538
		$chart->stroke();
539
	}
540
 
541
	# func to show genearte reports interface
542
	function showGenerateReports($searchInfo = '') {
543
 
544
		$userId = isLoggedIn();
545
		$websiteController = New WebsiteController();
546
		$websiteList = $websiteController->__getAllWebsites($userId, true);
547
		$this->set('websiteList', $websiteList);
548
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
549
		$this->set('websiteId', $websiteId);
550
 
551
		$keywordController = New KeywordController();
552
		$keywordList = $keywordController->__getAllKeywords($userId, $websiteId, true);
553
		$this->set('keywordList', $keywordList);
554
		$this->set('keyNull', false);
555
		$keywordId = empty ($searchInfo['keyword_id']) ? '' : $searchInfo['keyword_id'];
556
		$this->set('keywordId', $keywordId);
557
 
558
		$seController = New SearchEngineController();
559
		$seList = $seController->__getAllSearchEngines();
560
		$this->set('seList', $seList);
561
		$seId = empty ($searchInfo['se_id']) ? '' : $searchInfo['se_id'];
562
		$this->set('seId', $seId);
563
		$this->set('seNull', true);
564
		$this->set('seStyle', 170);
565
 
566
		$this->render('report/generatereport');
567
	}
568
 
569
	# func to generate reports
570
	function generateReports( $searchInfo='' ) {
571
		$userId = isLoggedIn();
572
		$keywordId = empty ($searchInfo['keyword_id']) ? '' : intval($searchInfo['keyword_id']);
573
		$websiteId = empty ($searchInfo['website_id']) ? '' : intval($searchInfo['website_id']);
574
		$seId = empty ($searchInfo['se_id']) ? '' : intval($searchInfo['se_id']);
575
 
576
		$seController = New SearchEngineController();
577
		$this->seList = $seController->__getAllCrawlFormatedSearchEngines();
578
 
579
		$sql = "select k.*,w.url from keywords k,websites w where k.website_id=w.id and k.status=1";
580
		if(!empty($userId) && !isAdmin()) $sql .= " and w.user_id=$userId";
581
		if(!empty($websiteId)) $sql .= " and k.website_id=$websiteId";
582
		if(!empty($keywordId)) $sql .= " and k.id=$keywordId";
583
		$sql .= " order by k.name";
584
		$keywordList = $this->db->select($sql);
585
 
586
		if(count($keywordList) <= 0){
587
			echo "<p class='note error'>".$_SESSION['text']['common']['No Keywords Found']."</p>";
588
			exit;
589
		}
590
 
591
		# loop through each keyword
592
		foreach ( $keywordList as $keywordInfo ) {
593
			$this->seFound = 0;
594
			$crawlResult = $this->crawlKeyword($keywordInfo, $seId);
595
			foreach($crawlResult as $sengineId => $matchList){
596
				if($matchList['status']){
597
					foreach($matchList['matched'] as $i => $matchInfo){
598
						$remove = ($i == 0) ? true : false;
599
						$matchInfo['se_id'] = $sengineId;
600
						$matchInfo['keyword_id'] = $keywordInfo['id'];
601
						$this->saveMatchedKeywordInfo($matchInfo, $remove);
602
					}
603
					echo "<p class='note notesuccess'>".$this->spTextKeyword['Successfully crawled keyword']." <b>{$keywordInfo['name']}</b> ".$this->spTextKeyword['results from']." <b>".$this->seList[$sengineId]['domain']."</b>.....</p>";
604
				}else{
605
					echo "<p class='note notefailed'>".$this->spTextKeyword['Crawling keyword']." <b>{$keywordInfo['name']}</b> ".$this->spTextKeyword['results from']." <b>".$this->seList[$sengineId]['domain']."</b> ".$_SESSION['text']['common']['failed']."......</p>";
606
				}
607
			}
608
			if(empty($this->seFound)){
609
				echo "<p class='note notefailed'>".$_SESSION['text']['common']['Keyword']." <b>{$keywordInfo['name']}</b> ".$this->spTextKeyword['not assigned to required search engines']."........</p>";
610
			}
155 - 611
			sleep(SP_CRAWL_DELAY);
612
		}
103 - 613
	}
614
 
615
	# function to format pagecontent
616
	function formatPageContent($seInfoId, $pageContent) {
617
	    if (!empty($this->seList[$seInfoId]['from_pattern']) && $this->seList[$seInfoId]['to_pattern']) {
618
	        $pattern = $this->seList[$seInfoId]['from_pattern']."(.*)".$this->seList[$seInfoId]['to_pattern'];
619
	        if (preg_match("/$pattern/is", $pageContent, $matches)) {
620
	            if (!empty($matches[1])) {
621
	                $pageContent = $matches[1];
622
	            }
623
	        }
624
	    }
625
	    return $pageContent;
626
	}
627
 
628
	# func to crawl keyword
629
	function crawlKeyword( $keywordInfo, $seId='', $cron=false, $removeDuplicate=true) {
630
		$crawlResult = array();
631
		$websiteUrl = formatUrl($keywordInfo['url'], false);
632
		if(empty($websiteUrl)) return $crawlResult;
633
		if(empty($keywordInfo['name'])) return $crawlResult;
634
 
635
		$time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
636
		$seList = explode(':', $keywordInfo['searchengines']);
637
		foreach($seList as $seInfoId){
638
 
639
			// function to execute only passed search engine
640
			if(!empty($seId) && ($seInfoId != $seId)) continue;
641
 
642
			// if search engine not found continue
643
			if (empty($this->seList[$seInfoId])) continue;
644
 
645
			$this->seFound = 1;
646
 
647
			// if execution from cron check whether cron already executed
648
			/*if ($cron) {
649
			    if (SP_MULTIPLE_CRON_EXEC && $this->isCronExecuted($keywordInfo['id'], $seInfoId, $time)) continue;
650
			}*/
651
 
652
			$searchUrl = str_replace('[--keyword--]', urlencode(stripslashes($keywordInfo['name'])), $this->seList[$seInfoId]['url']);
653
			$searchUrl = str_replace('[--country--]', $keywordInfo['country_code'], $searchUrl);
654
			if (empty($keywordInfo['country_code']) && stristr($searchUrl, '&cr=country&')) {
655
			    $searchUrl = str_replace('&cr=country&', '&cr=&', $searchUrl);
656
			}
657
 
658
			$seUrl = str_replace('[--start--]', $this->seList[$seInfoId]['start'], $searchUrl);
659
 
660
			// if google add special parameters
661
			$isGoogle = false;
662
			if (stristr($this->seList[$seInfoId]['url'], 'google')) {
663
			    $isGoogle = true;
664
			    $seUrl .= "&ie=utf-8&pws=0&gl=".$keywordInfo['country_code'];
665
			    $seUrl = str_replace('[--lang--]', '', $seUrl);
666
			} else {
667
				$seUrl = str_replace('[--lang--]', $keywordInfo['lang_code'], $seUrl);
668
			}
669
 
670
			if(!empty($this->seList[$seInfoId]['cookie_send'])){
671
				$this->seList[$seInfoId]['cookie_send'] = str_replace('[--lang--]', $keywordInfo['lang_code'], $this->seList[$seInfoId]['cookie_send']);
672
				$this->spider->_CURLOPT_COOKIE = $this->seList[$seInfoId]['cookie_send'];
673
			}
674
 
675
			$result = $this->spider->getContent($seUrl);
676
			$pageContent = $this->formatPageContent($seInfoId, $result['page']);
677
 
678
			// testing code for regex
679
            /*$testFileName = SP_TMPPATH . "/google.html";
680
            $myfile = fopen($testFileName, "w") or die("Unable to open file!");
681
            fwrite($myfile, $pageContent);
682
            fclose($myfile);
683
            exit;
684
 
685
            $myfile = fopen($testFileName, "r") or die("Unable to open file!");
686
            $pageContent = fread($myfile,filesize($testFileName));
687
            fclose($myfile);*/
688
 
689
			$crawlLogCtrl = new CrawlLogController();
690
			$crawlInfo = [];
691
			$crawlInfo['crawl_type'] = 'keyword';
692
			$crawlInfo['ref_id'] = empty($keywordInfo['id']) ? $keywordInfo['name'] : $keywordInfo['id'];
693
			$crawlInfo['subject'] = $seInfoId;
694
 
695
			$seStart = $this->seList[$seInfoId]['start'] + $this->seList[$seInfoId]['start_offset'];
696
			while(empty($result['error']) && ($seStart < $this->seList[$seInfoId]['max_results']) ){
697
				$logId = $result['log_id'];
698
				if(SP_DEBUG){
699
					$crawlInfo['log_message'] = "Started at: $seStart";
700
				}
701
				$crawlLogCtrl->updateCrawlLog($logId, $crawlInfo);
702
				sleep(SP_CRAWL_DELAY);
703
				$seUrl = str_replace('[--start--]', $seStart, $searchUrl);
704
				$result = $this->spider->getContent($seUrl);
705
				$pageContent .= $this->formatPageContent($seInfoId, $result['page']);
706
				$seStart += $this->seList[$seInfoId]['start_offset'];
707
			}
708
 
709
			# to check whether utf8 conversion needed
710
			if(!empty($this->seList[$seInfoId]['encoding'])){
711
				$pageContent = mb_convert_encoding($pageContent, "UTF-8", $this->seList[$seInfoId]['encoding']);
712
			}
713
 
714
			$crawlStatus = 0;
715
			if(empty($result['error'])){
716
 
717
			    // to update cron that report executed for akeyword on a search engine
718
			    if (SP_MULTIPLE_CRON_EXEC && $cron) $this->saveCronTrackInfo($keywordInfo['id'], $seInfoId, $time);
719
 
720
			    // verify the urls existing in the result
721
			    preg_match_all($this->seList[$seInfoId]['regex'], $pageContent, $matches);
722
			    if (!empty($matches[$this->seList[$seInfoId]['url_index']])) {
723
 
724
					$urlList = $matches[$this->seList[$seInfoId]['url_index']];
725
					$crawlResult[$seInfoId]['matched'] = array();
726
					$rank = 1;
727
					$previousDomain = "";
728
					foreach($urlList as $i => $url){
729
						$url = urldecode(strip_tags($url));
730
 
731
						// add special condition for baidu
732
						if (stristr($this->seList[$seInfoId]['domain'], "baidu")) {
733
							$url =  addHttpToUrl($url);
734
							$url = str_replace("...", "", $url);
735
						}
736
 
737
						// if google engine, format the urls
738
						if ($isGoogle && stristr($url, '/url?q=')) {
739
							$url = preg_replace(array('/\/url\?q=/i', '/\&amp;sa=U.*$/i'), array("", ""), $url);
740
						}
741
 
742
						if(!preg_match('/^http:\/\/|^https:\/\//i', $url)) continue;
743
 
744
						// check for to remove bing ad links in page
745
						if(stristr($url, 'bat.bing.com')) continue;
746
 
747
						// check to remove duplicates from same domain if google is the search engine
748
						if ($removeDuplicate && $isGoogle) {
749
						    $currentDomain = parse_url($url, PHP_URL_HOST);
750
						    if ($previousDomain == $currentDomain) {
751
						        continue;
752
						    }
753
						    $previousDomain = $currentDomain;
754
						}
755
 
756
						if($this->showAll || (stristr($url, "http://" . $websiteUrl) || stristr($url, "https://" . $websiteUrl)) ){
757
 
758
							if ($this->showAll && (stristr($url, "http://" . $websiteUrl) || stristr($url, "https://" . $websiteUrl)) ) {
759
								$matchInfo['found'] = 1;
760
							} else {
761
								$matchInfo['found'] = 0;
762
							}
763
 
764
							$matchInfo['url'] = $url;
765
							$matchInfo['title'] = strip_tags($matches[$this->seList[$seInfoId]['title_index']][$i]);
766
							$matchInfo['description'] = strip_tags($matches[$this->seList[$seInfoId]['description_index']][$i]);
767
							$matchInfo['rank'] = $rank;
768
							$crawlResult[$seInfoId]['matched'][] = $matchInfo;
769
						}
770
 
771
						$rank++;
772
					}
773
 
774
					$crawlStatus = 1;
775
 
776
				} else {
777
 
778
					// set crawl log info
779
					$crawlInfo['crawl_status'] = 0;
780
					$crawlInfo['log_message'] = SearchEngineController::isCaptchInSearchResults($pageContent) ? "<font class=error>Captcha found</font> in search result page" : "Regex not matched error occured while parsing search results!";
781
 
782
					if(SP_DEBUG){
783
						echo "<p class='note' style='text-align:left;'>Error occured while parsing $seUrl ".formatErrorMsg("Regex not matched <br>\n")."</p>";
784
					}
785
				}
786
			} else {
787
				if (SP_DEBUG) {
788
					echo "<p class='note' style='text-align:left;'>Error occured while crawling $seUrl ".formatErrorMsg($result['errmsg']."<br>\n")."</p>";
789
				}
790
			}
791
			$crawlResult[$seInfoId]['status'] = $crawlStatus;
792
			sleep(SP_CRAWL_DELAY);
793
 
794
			// update crawl log
795
			$logId = $result['log_id'];
796
			$crawlLogCtrl->updateCrawlLog($logId, $crawlInfo);
797
 
798
			// if proxy enabled if crawl failed try to check next item
799
			if (!$crawlResult[$seInfoId]['status'] && SP_ENABLE_PROXY && CHECK_WITH_ANOTHER_PROXY_IF_FAILED) {
800
 
801
				// max proxy checked in one execution is exeeded
802
				if ($this->proxyCheckCount < CHECK_MAX_PROXY_COUNT_IF_FAILED) {
803
 
804
					// if proxy is available for execution
805
					$proxyCtrler = New ProxyController();
806
					if ($proxyInfo = $proxyCtrler->getRandomProxy()) {
807
						$this->proxyCheckCount++;
808
						sleep(SP_CRAWL_DELAY);
809
						$crawlResult = array_merge($crawlResult, $this->crawlKeyword($keywordInfo, $seInfoId, $cron, $removeDuplicate));
810
					}
811
 
812
				} else {
813
					$this->proxyCheckCount = 1;
814
				}
815
			}
816
 
817
		}
818
 
155 - 819
		return  $crawlResult;
103 - 820
	}
821
 
822
	# func to save the report
823
	function saveMatchedKeywordInfo($matchInfo, $remove=false) {
824
		$time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
825
		$resultDate = date('Y-m-d');
826
		$this->checkDBConn();
827
		if($remove){
828
			$sql = "select id from searchresults where keyword_id={$matchInfo['keyword_id']}
829
			and searchengine_id={$matchInfo['se_id']} and result_date='$resultDate'";
830
			$recordList = $this->db->select($sql);
831
 
832
			if(count($recordList) > 0){
833
				foreach($recordList as $recordInfo){
834
					$sql = "delete from searchresultdetails where searchresult_id=".$recordInfo['id'];
835
					$this->db->query($sql);
836
				}
837
 
838
				$sql = "delete from searchresults where keyword_id={$matchInfo['keyword_id']}
839
				and searchengine_id={$matchInfo['se_id']} and result_date='$resultDate'";
840
				$this->db->query($sql);
841
			}
842
		}
843
 
155 - 844
		$sql = "insert into searchresults(keyword_id,searchengine_id,`rank`,`time`,result_date)
103 - 845
				values({$matchInfo['keyword_id']},{$matchInfo['se_id']},{$matchInfo['rank']},$time,'$resultDate')";
846
		$this->db->query($sql);
847
 
848
		$recordId = $this->db->getMaxId('searchresults');
849
		$sql = "insert into searchresultdetails(searchresult_id,url,title,description)
850
				values($recordId,'{$matchInfo['url']}','".addslashes($matchInfo['title'])."','".addslashes($matchInfo['description'])."')";
851
		$this->db->query($sql);
852
	}
853
 
854
	# func to check keyword rank
855
	function quickRankChecker() {
856
 
857
		$seController = New SearchEngineController();
858
		$seList = $seController->__getAllSearchEngines();
859
		$this->set('seList', $seList);
860
		$this->set('seStyle', 230);
861
		$seId = empty ($searchInfo['se_id']) ? '' : $searchInfo['se_id'];
862
		$this->set('seId', $seId);
863
 
864
		$langController = New LanguageController();
865
		$this->set('langNull', true);
866
		$this->set('langStyle', 230);
867
		$this->set('langList', $langController->__getAllLanguages());
868
 
869
		$countryController = New CountryController();
870
		$this->set('countryList', $countryController->__getAllCountries());
871
		$this->set('countryNull', true);
872
		$this->set('countryStyle', 230);
873
 
874
		$this->render('report/quickrankchecker');
875
	}
876
 
877
	# func to show quick rank report
878
	function showQuickRankChecker($keywordInfo='') {
879
 
880
		$keywordInfo['searchengines'] = $keywordInfo['se_id'];
881
		$this->showAll = $keywordInfo['show_all'];
882
 
883
		$seController = New SearchEngineController();
884
		$this->seList = $seController->__getAllCrawlFormatedSearchEngines();
885
 
886
		$crawlResult = $this->crawlKeyword($keywordInfo);
887
 
888
		$resultList = array();
889
		if(!empty($crawlResult[$keywordInfo['se_id']]['status'])){
890
			$resultList = $crawlResult[$keywordInfo['se_id']]['matched'];
891
		}
892
		$this->set('list', $resultList);
893
 
894
		$this->render('report/showquickrankchecker');
895
	}
896
 
897
	#function to save keyword cron trcker for multiple execution of cron same day
898
	function saveCronTrackInfo($keywordId, $seId, $time) {
155 - 899
	    $sql = "Insert into keywordcrontracker(keyword_id,searchengine_id,`time`) values($keywordId,$seId,$time)";
103 - 900
	    $this->db->query($sql);
901
	}
902
 
903
	# function to check whether cron executed for a particular keyword and search engine
904
	function isCronExecuted($keywordId, $seId, $time) {
155 - 905
	    $sql = "select keyword_id from keywordcrontracker where keyword_id=$keywordId and searchengine_id=$seId and `time`=$time";
103 - 906
        $info = $this->db->select($sql, true);
907
	    return empty($info['keyword_id']) ? false : true;
908
	}
909
 
910
    # function to show system reports
911
	function showOverallReportSummary($searchInfo='', $cronUserId=false) {
912
 
913
		$spTextHome = $this->getLanguageTexts('home', $_SESSION['lang_code']);
914
        $this->set('spTextHome', $spTextHome);
915
        $this->set('cronUserId', $cronUserId);
916
 
917
		$exportVersion = false;
918
		switch($searchInfo['doc_type']){
919
 
920
			case "export":
921
				$exportVersion = true;
922
				$exportContent = "";
923
				break;
924
 
925
			case "pdf":
926
				$this->set('pdfVersion', true);
927
				break;
928
 
929
			case "print":
930
				$this->set('printVersion', true);
931
				break;
932
		}
933
 
934
		$this->set('sectionHead', $spTextHome['Overall Report Summary']);
935
		$userId = empty($cronUserId) ? isLoggedIn() : $cronUserId;
936
		$isAdmin = isAdmin();
937
 
938
		$keywordController = New KeywordController();
939
		$websiteCtrler = New WebsiteController();
940
		$websiteList = $websiteCtrler->__getAllWebsites($userId, true);
941
		$this->set('siteList', $websiteList);
942
		$websiteId = isset($searchInfo['website_id']) ? $searchInfo['website_id'] : $websiteList[0]['id'];
943
		$websiteId = intval($websiteId);
944
		$this->set('websiteId', $websiteId);
945
		$urlarg = "website_id=$websiteId";
946
 
947
		$websiteUrl = "";
948
		foreach ($websiteList as $websiteInfo) {
949
		    if ($websiteInfo['id'] == $websiteId) {
950
		        $websiteUrl = $websiteInfo['url'];
951
		        break;
952
		    }
953
		}
954
		$this->set('websiteUrl', $websiteUrl);
955
 
956
		$reportTypes = array(
957
			'keyword-position' => $this->spTextTools["Keyword Position Summary"],
958
			'website-stats' => $spTextHome["Website Statistics"],
959
			'website-search-reports' => $this->spTextTools['Website Search Summary'],
960
			'sitemap-reports' => $this->spTextTools['Sitemap Reports Summary'],
961
			'keyword-search-reports' => $this->spTextTools['Keyword Search Summary'],
962
		    'social-media-reports' => $this->spTextTools['Social Media Report Summary'],
963
		    'analytics-reports' => $this->spTextTools['Website Analytics Summary'],
964
		    'review-reports' => $this->spTextTools['Review Report Summary'],
965
		);
966
		$this->set('reportTypes', $reportTypes);
967
		$urlarg .= "&report_type=".$searchInfo['report_type'];
968
 
969
		if (!empty ($searchInfo['from_time'])) {
970
			$fromTime = strtotime($searchInfo['from_time'] . ' 00:00:00');
971
		} else {
972
			$fromTime = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
973
		}
974
 
975
		if (!empty ($searchInfo['to_time'])) {
976
			$toTime = strtotime($searchInfo['to_time'] . ' 00:00:00');
977
		} else {
978
			$toTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
979
		}
980
 
981
		$fromTimeShort = date('Y-m-d', $fromTime);
982
		$this->set('fromTime', $fromTimeShort);
983
		$toTimeShort = date('Y-m-d', $toTime);
984
		$this->set('toTime', $toTimeShort);
985
		$urlarg .= "&from_time=$fromTimeShort&to_time=$toTimeShort&search_name=" . $searchInfo['search_name'];
986
 
987
		$seSearchUserId = isAdmin() ? "" : $userId;
988
		$this->seLIst = $keywordController->getUserKeywordSearchEngineList($seSearchUserId);
989
		$this->set('seList', $this->seLIst);
990
 
991
		$this->set('isAdmin', $isAdmin);
992
		$this->set('urlarg', $urlarg);
993
 
994
		$scriptPath = SP_WEBPATH."/archive.php?website_id=$websiteId";
995
		$scriptPath .= "&from_time=$fromTimeShort&to_time=$toTimeShort&search_name=" . $searchInfo['search_name'];
996
 
997
		# keyword position report section
998
		if (empty($searchInfo['report_type']) ||  ($searchInfo['report_type'] == 'keyword-position')) {
999
 
1000
		    // to find order col
1001
            if (!empty($searchInfo['order_col'])) {
1002
    		    $orderCol = $searchInfo['order_col'];
1003
    		    $orderVal = getOrderByVal($searchInfo['order_val']);
1004
    		} else {
1005
    		    $orderCol = $this->seLIst[array_keys($this->seLIst)[0]]['id'];
1006
    		    $orderVal = 'ASC';
1007
    		}
1008
 
1009
    		$this->set('orderCol', $orderCol);
1010
    		$this->set('orderVal', $orderVal);
1011
			$scriptPath .= "&report_type=keyword-position&order_col=$orderCol&order_val=$orderVal";
1012
 
1013
    		$conditions = " and w.status=1 and k.status=1";
1014
    		$conditions .= isAdmin() ? "" : $websiteCtrler->getWebsiteUserAccessCondition($userId);
1015
    		$conditions .= !empty($websiteId) ? " and w.id=$websiteId" : "";
1016
    		$conditions .= !empty($searchInfo['search_name']) ? " and k.name like '%".addslashes($searchInfo['search_name'])."%'" : "";
1017
 
1018
    		$subSql = "select [col] from keywords k,searchresults r, websites w
1019
    		where k.id=r.keyword_id and k.website_id=w.id $conditions
1020
    		and r.searchengine_id=".intval($orderCol)." and r.result_date='" . addslashes($toTimeShort) . "'
1021
    		group by k.id";
1022
 
155 - 1023
    		$unionOrderCol = ($orderCol == "keyword") ? "name" : "`rank`";
1024
    		$sql = "(". str_replace("[col]", "k.id,k.name,min(`rank`) `rank`,w.name website,w.url weburl", $subSql) .")
103 - 1025
    		UNION
1026
    		(select k.id,k.name,1000,w.name website,w.url weburl
1027
    		from keywords k, websites w
1028
    		where w.id=k.website_id $conditions and k.id not in
1029
    		(". str_replace("[col]", "distinct(k.id)", $subSql) ."))
1030
    		order by $unionOrderCol $orderVal";
1031
 
1032
    		if ($unionOrderCol != 'name') $sql .= ", name";
1033
 
1034
    		// pagination setup, if not from cron job email send function, pdf and export action
1035
    		if (!in_array($searchInfo['doc_type'], array("pdf", "export")) && !$cronUserId) {
1036
 
1037
    			$this->db->query($sql, true);
1038
    			$this->paging->setDivClass('pagingdiv');
1039
    			$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
1040
    			$pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
1041
    			$this->set('keywordPagingDiv', $pagingDiv);
1042
    			$this->set('pageNo', $searchInfo['pageno']);
1043
 
1044
    			$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
1045
    		}
1046
 
1047
    		# set keywords list
1048
    		$list = $this->db->select($sql);
1049
 
1050
    		$indexList = array();
1051
    		foreach($list as $keywordInfo){
1052
    			$positionInfo = $this->__getKeywordSearchReport($keywordInfo['id'], $fromTime, $toTime, true);
1053
 
1054
    			// check whether the sorting search engine is there
1055
    		    $indexList[$keywordInfo['id']] = empty($positionInfo[$orderCol][$toTimeShort]) ? 10000 : $positionInfo[$orderCol][$toTimeShort];
1056
 
1057
    			$keywordInfo['position_info'] = $positionInfo;
1058
    			$keywordList[$keywordInfo['id']] = $keywordInfo;
1059
    		}
1060
 
1061
    		// sort array according the value
1062
    		if ($orderCol != 'keyword') {
1063
        		if ($orderVal == 'DESC') {
1064
        		    arsort($indexList);
1065
        		} else {
1066
        		    asort($indexList);
1067
        		}
1068
    		}
1069
    		$this->set('indexList', $indexList);
1070
 
1071
    		if ($exportVersion) {
1072
    			$spText = $_SESSION['text'];
1073
    			$reportHeading =  $this->spTextTools['Keyword Position Summary']."($fromTimeShort - $toTimeShort)";
1074
    			$exportContent .= createExportContent( array('', $reportHeading, ''));
1075
    			$exportContent .= createExportContent( array());
1076
    			$headList = array($spText['common']['Website'], $spText['common']['Keyword']);
1077
 
1078
    			$pTxt = str_replace("-", "/", substr($fromTimeShort, -5));
1079
    			$cTxt = str_replace("-", "/", substr($toTimeShort, -5));
1080
    			foreach ($this->seLIst as $seInfo) {
1081
    				$domainTxt = str_replace("www.", "", $seInfo['domain']);
1082
    				$headList[] = $domainTxt . "($cTxt)";
1083
    				$headList[] = $domainTxt . "($pTxt)";
1084
    				$headList[] = $domainTxt . "(+/-)";
1085
    			}
1086
 
1087
    			$exportContent .= createExportContent( $headList);
1088
 
1089
 
1090
    			foreach($indexList as $keywordId => $rankValue){
1091
    				$listInfo = $keywordList[$keywordId];
1092
    				$positionInfo = $listInfo['position_info'];
1093
 
1094
    				$valueList = array($listInfo['weburl'], $listInfo['name']);
1095
    				foreach ($this->seLIst as $index => $seInfo){
1096
 
1097
    					$rankInfo = $positionInfo[$seInfo['id']];
1098
    					$prevRank = isset($rankInfo[$fromTimeShort]) ? $rankInfo[$fromTimeShort] : "";
1099
    					$currRank = isset($rankInfo[$toTimeShort]) ? $rankInfo[$toTimeShort] : "";
1100
    					$rankDiff = "";
1101
 
1102
    					// if both ranks are existing
1103
    					if ($prevRank != '' && $currRank != '') {
1104
    						$rankDiff = $prevRank - $currRank;
1105
    					}
1106
 
1107
    					$valueList[] = $currRank;
1108
    					$valueList[] = $prevRank;
1109
    					$valueList[] = $rankDiff;
1110
    				}
1111
 
1112
    				$exportContent .= createExportContent( $valueList);
1113
    			}
1114
 
1115
    		} else {
1116
				$this->set('list', $keywordList);
1117
				$this->set('keywordPos', true);
1118
    		}
1119
 
1120
		}
1121
 
1122
		# website report section
1123
		if (empty($searchInfo['report_type']) ||  ($searchInfo['report_type'] == 'website-stats')) {
1124
 
1125
			// pagination setup
1126
			if (!in_array($searchInfo['doc_type'], array('export', 'pdf')) && !$cronUserId) {
1127
				$scriptPath .= "&report_type=website-stats";
1128
				$info['pageno'] = intval($info['pageno']);
1129
				$sql = "select * from websites w where w.status=1";
1130
				$sql .= isAdmin() ? "" : $websiteCtrler->getWebsiteUserAccessCondition($userId);
1131
    			$sql .= !empty($websiteId) ? " and w.id=$websiteId" : "";
1132
 
1133
				// search for user name
1134
				if (!empty($searchInfo['search_name'])) {
1135
					$sql .= " and (w.name like '%".addslashes($searchInfo['search_name'])."%'
1136
					or w.url like '%".addslashes($searchInfo['search_name'])."%')";
1137
				}
1138
 
1139
				$sql .= " order by w.name";
1140
				$this->db->query($sql, true);
1141
				$this->paging->setDivClass('pagingdiv');
1142
				$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
1143
				$pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
1144
				$this->set('websitePagingDiv', $pagingDiv);
1145
				$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
1146
				$this->set('pageNo', $searchInfo['pageno']);
1147
				$websiteList = $this->db->select($sql);
1148
			}
1149
 
1150
		    include_once(SP_CTRLPATH."/saturationchecker.ctrl.php");
1151
			include_once(SP_CTRLPATH."/rank.ctrl.php");
1152
			include_once(SP_CTRLPATH."/backlink.ctrl.php");
1153
			include_once(SP_CTRLPATH."/directory.ctrl.php");
1154
			include_once(SP_CTRLPATH."/pagespeed.ctrl.php");
1155
			$rankCtrler = New RankController();
1156
			$backlinlCtrler = New BacklinkController();
1157
			$saturationCtrler = New SaturationCheckerController();
1158
			$dirCtrler = New DirectoryController();
1159
			$pageSpeedCtrler = New PageSpeedController();
1160
 
1161
			$spTextPS = $this->getLanguageTexts('pagespeed', $_SESSION['lang_code']);
1162
			$this->set('spTextPS', $spTextPS);
1163
 
1164
			$websiteRankList = array();
1165
			foreach($websiteList as $listInfo){
1166
 
1167
			    // if only needs to show onewebsite selected
1168
			    if (!empty($websiteId) && ($listInfo['id'] != $websiteId)) continue;
1169
 
1170
				# rank reports
1171
				$report = $rankCtrler->__getWebsiteRankReport($listInfo['id'], $fromTime, $toTime);
1172
				$report = $report[0];
1173
				$listInfo['alexarank'] = empty($report['alexa_rank']) ? "-" : $report['alexa_rank']." ".$report['rank_diff_alexa'];
1174
				$listInfo['mozrank'] = empty($report['moz_rank']) ? "-" : $report['moz_rank']." ".$report['rank_diff_moz'];
1175
				$listInfo['domain_authority'] = empty($report['domain_authority']) ? "-" : $report['domain_authority']." ".$report['rank_diff_domain_authority'];
1176
				$listInfo['page_authority'] = empty($report['page_authority']) ? "-" : $report['page_authority']." ".$report['rank_diff_page_authority'];
1177
 
1178
				# back links reports
1179
				$report = $backlinlCtrler->__getWebsitebacklinkReport($listInfo['id'], $fromTime, $toTime);
1180
				$report = $report[0];
1181
				$listInfo['google']['backlinks'] = empty($report['google']) ? "-" : $report['google']." ".$report['rank_diff_google'];
1182
				$listInfo['alexa']['backlinks'] = empty($report['alexa']) ? "-" : $report['alexa']." ".$report['rank_diff_alexa'];
1183
				$listInfo['msn']['backlinks'] = empty($report['msn']) ? "-" : $report['msn']." ".$report['rank_diff_msn'];
1184
 
1185
				# rank reports
1186
				$report = $saturationCtrler->__getWebsiteSaturationReport($listInfo['id'], $fromTime, $toTime);
1187
				$report = $report[0];
1188
				$listInfo['google']['indexed'] = empty($report['google']) ? "-" : $report['google']." ".$report['rank_diff_google'];
1189
				$listInfo['msn']['indexed'] = empty($report['msn']) ? "-" : $report['msn']." ".$report['rank_diff_msn'];
1190
 
1191
				# pagespeed reports
1192
				$report = $pageSpeedCtrler->__getWebsitePageSpeedReport($listInfo['id'], $fromTime, $toTime);
1193
				$report = $report[0];
1194
				$listInfo['desktop_speed_score'] = empty($report['desktop_speed_score']) ? "-" : $report['desktop_speed_score']." ".$report['rank_diff_desktop_speed_score'];
1195
				$listInfo['mobile_speed_score'] = empty($report['mobile_speed_score']) ? "-" : $report['mobile_speed_score']." ".$report['rank_diff_mobile_speed_score'];
1196
 
1197
				$listInfo['dirsub']['total'] = $dirCtrler->__getTotalSubmitInfo($listInfo['id']);
1198
				$listInfo['dirsub']['active'] = $dirCtrler->__getTotalSubmitInfo($listInfo['id'], true);
1199
				$websiteRankList[] = $listInfo;
1200
			}
1201
 
1202
			// if export function called
1203
			if ($exportVersion) {
1204
				$exportContent .= createExportContent( array());
1205
				$exportContent .= createExportContent( array());
1206
				$exportContent .= createExportContent( array('', $spTextHome['Website Statistics']."($fromTimeShort - $toTimeShort)", ''));
1207
 
1208
				if ((isAdmin() && !empty($webUserId))) {
1209
				    $exportContent .= createExportContent( array());
1210
				    $exportContent .= createExportContent( array());
1211
				    $userInfo = $userCtrler->__getUserInfo($webUserId);
1212
				    $exportContent .= createExportContent( array($_SESSION['text']['common']['User'], $userInfo['username']));
1213
				}
1214
 
1215
				$exportContent .= createExportContent( array());
1216
				$headList = array(
1217
					$_SESSION['text']['common']['Website'],
1218
					$_SESSION['text']['common']['MOZ Rank'],
1219
					$_SESSION['text']['common']['Domain Authority'],
1220
					$_SESSION['text']['common']['Page Authority'],
1221
					$_SESSION['text']['common']['Alexa Rank'],
1222
					'Google '.$spTextHome['Backlinks'],
1223
					'alexa '.$spTextHome['Backlinks'],
1224
					'Bing '.$spTextHome['Backlinks'],
1225
					'Google '.$spTextHome['Indexed'],
1226
					'Bing '.$spTextHome['Indexed'],
1227
					$spTextPS['Desktop Speed'],
1228
					$spTextPS['Mobile Speed'],
1229
					$_SESSION['text']['common']['Total'].' Submission',
1230
					$_SESSION['text']['common']['Active'].' Submission',
1231
				);
1232
 
1233
				$exportContent .= createExportContent( $headList);
1234
				foreach ($websiteRankList as $websiteInfo) {
1235
					$valueList = array(
1236
						$websiteInfo['url'],
1237
						strip_tags($websiteInfo['mozrank']),
1238
						strip_tags($websiteInfo['domain_authority']),
1239
						strip_tags($websiteInfo['page_authority']),
1240
						strip_tags($websiteInfo['alexarank']),
1241
						strip_tags($websiteInfo['google']['backlinks']),
1242
						strip_tags($websiteInfo['alexa']['backlinks']),
1243
						strip_tags($websiteInfo['msn']['backlinks']),
1244
						strip_tags($websiteInfo['google']['indexed']),
1245
						strip_tags($websiteInfo['msn']['indexed']),
1246
						strip_tags($websiteInfo['desktop_speed_score']),
1247
						strip_tags($websiteInfo['mobile_speed_score']),
1248
						$websiteInfo['dirsub']['total'],
1249
						$websiteInfo['dirsub']['active'],
1250
					);
1251
					$exportContent .= createExportContent( $valueList);
1252
				}
1253
			}else {
1254
				$this->set('websiteRankList', $websiteRankList);
1255
				$this->set('websiteStats', true);
1256
			}
1257
		}
1258
 
1259
		# website search report section
1260
		if (empty($searchInfo['report_type']) || in_array($searchInfo['report_type'], array('review-reports', 'social-media-reports', 'website-search-reports', 'keyword-search-reports', 'sitemap-reports', 'analytics-reports')) ) {
1261
		    include_once(SP_CTRLPATH."/analytics.ctrl.php");
1262
			$webMasterCtrler = new WebMasterController();
1263
			$socialMediaCtrler = New SocialMediaController();
1264
			$reviewCtrler = New ReviewManagerController();
1265
			$webMasterCtrler->set('spTextTools', $this->spTextTools);
1266
			$webMasterCtrler->spTextTools = $this->spTextTools;
1267
			$filterList = $searchInfo;
1268
			$wmMaxFromTime = strtotime('-3 days');
1269
			$wmMaxEndTime = strtotime('-2 days');
1270
			$filterList['from_time'] = $fromTime > $wmMaxFromTime ? $wmMaxFromTime : $fromTime;
1271
			$filterList['to_time'] = $toTime > $wmMaxEndTime ? $wmMaxEndTime : $toTime;
1272
			$filterList['from_time'] = date('Y-m-d', $filterList['from_time']);
1273
			$filterList['to_time'] = date('Y-m-d', $filterList['to_time']);
1274
			$filterList['website_id'] = $websiteId;
1275
 
1276
			// if website search reports
1277
			if (empty($searchInfo['report_type']) || ($searchInfo['report_type'] == 'website-search-reports')) {
1278
				$websiteSearchReport = $webMasterCtrler->viewWebsiteSearchSummary($filterList, true, $cronUserId);
1279
			}
1280
 
1281
			// if keyword search reports
1282
			if (empty($searchInfo['report_type']) || ($searchInfo['report_type'] == 'keyword-search-reports')) {
1283
				$keywordSearchReport = $webMasterCtrler->viewKeywordSearchSummary($filterList, true, $cronUserId);
1284
			}
1285
 
1286
			// if sitemap reports
1287
			if (empty($searchInfo['report_type']) || ($searchInfo['report_type'] == 'sitemap-reports')) {
1288
				$websiteCtrler->set('spTextPanel', $this->spTextPanel);
1289
				$sitemapReport = $websiteCtrler->listSitemap($filterList, true, $cronUserId);
1290
			}
1291
 
1292
			// if website analytics reports
1293
			if (empty($searchInfo['report_type']) || ($searchInfo['report_type'] == 'analytics-reports')) {
1294
			    $analyticsCtrler = new AnalyticsController();
1295
			    $analyticsCtrler->set('spTextTools', $this->spTextTools);
1296
			    $analyticsCtrler->spTextTools = $this->spTextTools;
1297
			    $wmMaxFromTime = strtotime('-2 days');
1298
			    $wmMaxEndTime = strtotime('-1 days');
1299
			    $filterList['from_time'] = $fromTime > $wmMaxFromTime ? $wmMaxFromTime : $fromTime;
1300
			    $filterList['to_time'] = $toTime > $wmMaxEndTime ? $wmMaxEndTime : $toTime;
1301
			    $filterList['from_time'] = date('Y-m-d', $filterList['from_time']);
1302
			    $filterList['to_time'] = date('Y-m-d', $filterList['to_time']);
1303
			    $analyticsReport = $analyticsCtrler->viewAnalyticsSummary($filterList, true, $cronUserId);
1304
			}
1305
 
1306
			// if social media reports
1307
			if (empty($searchInfo['report_type']) || ($searchInfo['report_type'] == 'social-media-reports')) {
1308
				$filterList['from_time'] = $fromTimeShort;
1309
				$filterList['to_time'] = $toTimeShort;
1310
				$socialMediaCtrler->set('spTextTools', $this->spTextTools);
1311
				$socialMediaCtrler->set('spTextPanel', $this->spTextPanel);
1312
				$socialMediaCtrler->spTextTools = $this->spTextTools;
1313
				$socialMediaReport = $socialMediaCtrler->viewReportSummary($filterList, true, $cronUserId);
1314
			}
1315
 
1316
			// if social media reports
1317
			if (empty($searchInfo['report_type']) || ($searchInfo['report_type'] == 'review-reports')) {
1318
				$filterList['from_time'] = $fromTimeShort;
1319
				$filterList['to_time'] = $toTimeShort;
1320
				$reviewCtrler->set('spTextTools', $this->spTextTools);
1321
				$reviewCtrler->set('spTextPanel', $this->spTextPanel);
1322
				$reviewCtrler->spTextTools = $this->spTextTools;
1323
				$reviewReport = $reviewCtrler->viewReportSummary($filterList, true, $cronUserId);
1324
			}
1325
 
1326
			if ($exportVersion) {
1327
				$exportContent .= $websiteSearchReport;
1328
				$exportContent .= $keywordSearchReport;
1329
				$exportContent .= $socialMediaReport;
1330
			} else {
1331
				$this->set('websiteSearchReport', $websiteSearchReport);
1332
				$this->set('keywordSearchReport', $keywordSearchReport);
1333
				$this->set('sitemapReport', $sitemapReport);
1334
				$this->set('socialMediaReport', $socialMediaReport);
1335
				$this->set('reviewReport', $reviewReport);
1336
				$this->set('analyticsReport', $analyticsReport);
1337
			}
1338
 
1339
		}
1340
 
1341
		if ($exportVersion) {
1342
			exportToCsv('archived_report', $exportContent);
1343
		} else {
1344
			$this->set('searchInfo', $searchInfo);
1345
 
1346
			// if execution through cron job then just return the content to send through mail
1347
			if (!empty($cronUserId)) {
1348
				$this->set('cronUserId', $cronUserId);
1349
			    return $this->getViewContent('report/archive');
1350
			} else {
1351
 
1352
				// if pdf export
1353
				if ($searchInfo['doc_type'] == "pdf") {
1354
					exportToPdf($this->getViewContent('report/archive'), "overall_summary_$fromTimeShort-$toTimeShort.pdf");
1355
				} else {
1356
			    	$this->render('report/archive');
1357
				}
1358
			}
1359
		}
1360
	}
1361
 
1362
    # func to get report settings data
1363
	function getUserReportSettings($userId) {
1364
		$userId = intval($userId);
1365
		$sql = "select * from reports_settings where user_id=$userId";
1366
		$repSetInfo = $this->db->select($sql, true);
1367
 
1368
		// if report settings are empty add default interval
1369
		if (empty($repSetInfo)) {
1370
		    $repSetInfo['user_id'] = $userId;
1371
		    $repSetInfo['report_interval'] = SP_SYSTEM_REPORT_INTERVAL;
1372
		    $repSetInfo['email_notification'] = SP_REPORT_EMAIL_NOTIFICATION;
1373
		    $lastGeneratedDay = (SP_SYSTEM_REPORT_INTERVAL == 30) ? 1 : (date('d') - SP_SYSTEM_REPORT_INTERVAL);
1374
		    $repSetInfo['last_generated'] = mktime(0, 0, 0, date('m'), $lastGeneratedDay, date('Y'));
1375
		    $this->createUserReportSettings($repSetInfo);
1376
		    $repSetInfo['id'] = $this->db->getMaxId('reports_settings');
1377
		}
1378
 
1379
		return $repSetInfo;
1380
	}
1381
 
1382
	# func to insert report settings
1383
	function createUserReportSettings($setInfo) {
1384
		$sql = "Insert into reports_settings(user_id,report_interval,email_notification,last_generated)
1385
				values({$setInfo['user_id']},{$setInfo['report_interval']},{$setInfo['email_notification']},'{$setInfo['last_generated']}')";
1386
		$this->db->query($sql);
1387
	}
1388
 
1389
	# func to update user report generate interval
1390
	function updateUserReportSetting($userId, $col, $val) {
1391
		$sql = "Update reports_settings set $col='".addslashes($val)."' where user_id=$userId";
1392
		$this->db->query($sql);
1393
	}
1394
 
1395
	# func to update user report generation logs
1396
	function updateUserReportGenerationLogs($userId, $generateDate) {
1397
		$dataList = array(
1398
			'user_id|int' => $userId,
155 - 1399
			'report_date' => $generateDate,
103 - 1400
		);
1401
 
1402
		$this->dbHelper->insertRow("user_report_logs", $dataList);
1403
	}
1404
 
1405
	# func to schedule reports
1406
	function showReportsScheduler($success=false, $postInfo='') {
1407
		$userId = isLoggedIn();
1408
 
1409
		if (isAdmin()) {
1410
		    $userId = empty($postInfo['user_id']) ? $userId : $postInfo['user_id'];
1411
		}
1412
 
1413
		$repSetInfo = $this->getUserReportSettings($userId);
1414
		$this->set('repSetInfo', $repSetInfo);
1415
 
1416
		$reportInterval = !isset($postInfo['report_interval']) ? $repSetInfo['report_interval'] : $postInfo['report_interval'];
1417
		$this->set('reportInterval', $reportInterval);
1418
		if ($reportInterval == 30) {
1419
		    $nextGenTime = mktime(0, 0, 0, date('m') + 1, 1, date('Y'));
1420
		} else {
1421
		    $nextGenTime = $repSetInfo['last_generated'] + ( $repSetInfo['report_interval'] * 86400);
1422
		}
1423
		$this->set('nextReportTime', date('d M Y', $nextGenTime));
1424
 
1425
		$scheduleList = array(
1426
			1 => $_SESSION['text']['label']['Daily'],
1427
			2 => $this->spTextReport['2 Days'],
1428
			7 => $_SESSION['text']['label']['Weekly'],
1429
			30 => $_SESSION['text']['label']['Monthly'],
1430
		);
1431
 
1432
		$userCtrler = New UserController();
1433
		$userList = $userCtrler->__getAllUsers();
1434
		$this->set('userList', $userList);
1435
 
1436
		$this->set('success', $success);
1437
		$this->set('scheduleList', $scheduleList);
1438
		$this->render('report/reportscheduler');
1439
	}
1440
 
1441
	# func to save Report Schedule
1442
	function saveReportSchedule($info) {
1443
		$userId = isAdmin() ? $info['user_id'] : isLoggedIn();
1444
		$repSetInfo = $this->getUserReportSettings($userId);
1445
	    $this->updateUserReportSetting($userId, 'report_interval', $info['report_interval']);
1446
	    $this->updateUserReportSetting($userId, 'email_notification', $info['email_notification']);
1447
	    $this->showReportsScheduler(true, $info);
1448
	}
1449
 
1450
	# func to check whether report can be generated for user
1451
	function isGenerateReportsForUser($userId) {
1452
		$genReport = false;
1453
		$repSetInfo = $this->getUserReportSettings($userId);
1454
		if ($repSetInfo['report_interval'] > 0) {
1455
		    $lastGeneratedTime = $repSetInfo['last_generated'];
1456
		    $currentDateTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
1457
		    if ($lastGeneratedTime < $currentDateTime) {
1458
    		    // if monthly interval generate on first of each month
1459
    		    if ($repSetInfo['report_interval'] == 30) {
1460
    		        $genReport = (date('d') == 1) ? true : false;
1461
    		    } else {
1462
        			$nextGenTime = $lastGeneratedTime + ( $repSetInfo['report_interval'] * 86400);
1463
        			$genReport = (mktime() > $nextGenTime) ? true : false;
1464
    		    }
1465
		    }
1466
		}
1467
		$repSetInfo['generate_report'] = $genReport;
1468
		return $repSetInfo;
1469
	}
1470
 
1471
	# function to sent Email Notification For ReportGeneration
1472
	function sentEmailNotificationForReportGen($userInfo, $fromTime, $toTime) {
1473
		$fromTime = !empty($fromTime) ? $fromTime : date('Y-m-d', strtotime('-1 days'));
1474
		$searchInfo = array(
1475
    	    'website_id' => 0,
1476
            'report_type' => '',
1477
            'from_time' => date('Y-m-d', $fromTime),
1478
            'to_time' => date('Y-m-d', $toTime),
1479
            'doc_type' => 'print',
1480
        );
1481
 
1482
	    $this->spTextPanel = $this->getLanguageTexts('panel', $_SESSION['lang_code']);
1483
 
1484
        $reportContent = $this->showOverallReportSummary($searchInfo, $userInfo['id']);
1485
        $this->set('reportContent', $reportContent);
1486
 
1487
        $reportTexts = $this->getLanguageTexts('reports', $userInfo['lang_code']);
1488
        $this->set('reportTexts', $reportTexts);
1489
        $this->set('commonTexts', $this->getLanguageTexts('common', $userInfo['lang_code']));
1490
        $this->set('loginTexts', $this->getLanguageTexts('login', $userInfo['lang_code']));
1491
 
1492
		$name = $userInfo['first_name'].' '.$userInfo['last_name'];
1493
		$this->set('name', $name);
1494
		$subject = $reportTexts['report_email_subject'];
1495
		$content = $this->getViewContent('email/emailnotificationreportgen');
1496
 
1497
		$userController =  New UserController();
1498
		$adminInfo = $userController->__getAdminInfo();
1499
		$adminName = $adminInfo['first_name']."-".$adminInfo['last_name'];
1500
		$this->set('adminName', $adminName);
1501
 
1502
		if (!sendMail($adminInfo['email'], $adminName, $userInfo['email'], $subject, $content)) {
1503
			echo 'An internal error occured while sending mail!';
1504
		} else {
1505
		    echo "Reports send successfully to ".$userInfo['email']."\n";
1506
		}
1507
	}
1508
 
1509
	# func to show user report generation logs
1510
	function showReportGenerationLogs($searchInfo = '') {
1511
 
1512
		$userCtrler = New UserController();
1513
		$fromTimeDate = !empty ($searchInfo['from_time']) ? addslashes($searchInfo['from_time']) : date('Y-m-d', strtotime('-1 days'));
1514
		$toTimeDate = !empty ($searchInfo['to_time']) ? addslashes($searchInfo['to_time']) : date('Y-m-d');
1515
		$this->set('fromTime', $fromTimeDate);
1516
		$this->set('toTime', $toTimeDate);
1517
 
1518
		$userList = $userCtrler->__getAllUsersHavingWebsite();
1519
		$this->set('userList', $userList);
1520
 
1521
		$userTypeCtrler = new UserTypeController();
1522
		$typeList = $userTypeCtrler->__getAllUserTypeList();
1523
		foreach ($typeList as $info) $userTypeList[$info['id']] = $info;
1524
		$this->set('userTypeList', $userTypeList);
1525
 
1526
		if (!empty($searchInfo['user_id'])) {
1527
			$logUserList = array($userCtrler->__getUserInfo($searchInfo['user_id']));
1528
			$this->set('userId', intval($searchInfo['user_id']));
1529
		} else {
1530
			$logUserList = $userList;
1531
		}
1532
 
1533
		$this->set('logUserList', $logUserList);
1534
 
1535
		$whereCond = "report_date >='$fromTimeDate 00:00:00' and report_date<='$toTimeDate 23:59:59'";
1536
		$whereCond .= !empty($searchInfo['user_id']) ? " and user_id=" . intval($searchInfo['user_id']) : "";
1537
		$whereCond .= " order by report_date desc";
1538
		$list = $this->dbHelper->getAllRows("user_report_logs", $whereCond, "id,user_id,date(report_date) as report_date");
1539
 
1540
		// loop through the list
1541
		$logList = array();
1542
		foreach ($list as $listInfo) {
1543
			$logList[$listInfo['report_date']][$listInfo['user_id']] = 1;
1544
		}
1545
 
1546
		$this->set('logDateList', getDateRange($fromTimeDate, $toTimeDate));
1547
		$this->set('logList', $logList);
1548
		$this->set('spTextUser', $this->getLanguageTexts('user', $_SESSION['lang_code']));
1549
		$this->render('report/report_generation_logs');
1550
 
1551
	}
1552
}
1553
?>