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
 *   Copyright (C) 2009-2011 by Geo Varghese(www.seopanel.in)  	   *
4
 *   sendtogeo@gmail.com   												   *
5
 *                                                                         *
6
 *   This program is free software; you can redistribute it and/or modify  *
7
 *   it under the terms of the GNU General Public License as published by  *
8
 *   the Free Software Foundation; either version 2 of the License, or     *
9
 *   (at your option) any later version.                                   *
10
 *                                                                         *
11
 *   This program is distributed in the hope that it will be useful,       *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU General Public License for more details.                          *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU General Public License     *
17
 *   along with this program; if not, write to the                         *
18
 *   Free Software Foundation, Inc.,                                       *
19
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20
 ***************************************************************************/
21
 
22
# class defines all pagespeed api controller functions
23
class PageSpeedController extends Controller{
24
 
25
 
26
	var $colList = array(
27
		'desktop_speed_score' => 'desktop_speed_score',
28
		'mobile_speed_score' => 'mobile_speed_score',
29
	);
30
 
31
	// function to get moz rank
32
	function __getPageSpeedInfo ($url, $params = array(), $apiKey = '', $returnLog = false) {
33
 
34
		include_once(SP_LIBPATH . "/google-api-php-client/vendor/autoload.php");
35
		$pageSpeedInfo = array();
36
		$crawlInfo = array();
37
 
38
		$apiKey = !empty($apiKey) ? $apiKey : SP_GOOGLE_API_KEY;
39
 
40
		// if empty no need to crawl
41
		if (!empty($apiKey)) {
42
 
43
			$client = new Google_Client();
44
			$client->setApplicationName("SP_CHECKER");
155 - 45
			$client->setDeveloperKey($apiKey);
103 - 46
 
47
			try {
48
 
49
				// split and select main language if sub language selected
50
				if (stristr($params['locale'], '-')) {
51
					list($params['locale'], $tmpVar) = explode('-', $params['locale']);
52
				}
53
 
54
				$service = new Google_Service_Pagespeedonline($client);
55
				$pageSpeedInfo = $service->pagespeedapi->runpagespeed($url, $params);
56
				$pageSpeedInfo = self::formatPageSpeedData($pageSpeedInfo);
57
			} catch (Exception $e) {
58
				$err = $e->getMessage();
59
				$errData = json_decode($err);
60
				$crawlInfo['crawl_status'] = 0;
61
				$crawlInfo['log_message'] = $_SESSION['text']['label']['Fail'];
62
				$crawlInfo['log_message'] .= !empty($errData->error->errors[0]->reason) ? ": " . $errData->error->errors[0]->reason . " :: " . $errData->error->errors[0]->message : "";
63
			}
64
 
65
		} else {
66
			$crawlInfo['crawl_status'] = 0;
67
			$crawlInfo['log_message'] = "Google api key not set.";
68
 
69
			$alertCtler = new AlertController();
70
			$alertInfo = array(
71
				'alert_subject' => "Click here to enter Google API key",
72
				'alert_message' => "Error: Google API key not found",
73
				'alert_url' => SP_WEBPATH ."/admin-panel.php?sec=google-settings",
74
				'alert_type' => "danger",
75
				'alert_category' => "reports",
76
			);
77
			$alertCtler->createAlert($alertInfo, false, true);
78
 
79
		}
80
 
81
		return $returnLog ? array($pageSpeedInfo, $crawlInfo) : $pageSpeedInfo;
82
 
83
	}
84
 
85
	public static function formatPageSpeedData($pageSpeedInfo) {
86
 
87
		$pageSpeedData = array(
155 - 88
			'speed_score' => !empty($pageSpeedInfo['lighthouseResult']['categories']['performance']['score']) ? $pageSpeedInfo['lighthouseResult']['categories']['performance']['score'] * 100 : 0,
89
			'usability_score' => !empty($pageSpeedInfo['lighthouseResult']['categories']['performance']['score']) ? $pageSpeedInfo['lighthouseResult']['categories']['performance']['score'] * 100 : 0,
103 - 90
		);
91
 
92
		$detailsInfo = array();
93
 
155 - 94
		// commented for API v5 version
95
		/*foreach ($pageSpeedInfo['formattedResults']['ruleResults'] as $ruleSet => $ruleSetInfo) {
96
 
103 - 97
			$detailsInfo[$ruleSet] = array(
98
				'localizedRuleName' => $ruleSetInfo['localizedRuleName'],
99
				'ruleImpact' => $ruleSetInfo['ruleImpact'],
100
				'impactGroup' => implode(',', $ruleSetInfo['groups']),
101
				'summary' => self::formatSummaryText($ruleSetInfo['summary']),
102
				'urlBlocks' => self::formatUrlBlock($ruleSetInfo['urlBlocks']),
103
			);
104
 
155 - 105
		}*/
103 - 106
 
107
		$pageSpeedData['details'] = $detailsInfo;
108
		return $pageSpeedData;
109
 
110
	}
111
 
112
	public static function formatUrlBlock($urlBlockList) {
113
		$urlList = array();
114
 
115
		foreach ($urlBlockList as $urlBlockInfo) {
116
			$info['header'] = self::formatSummaryText($urlBlockInfo['header']);
117
			$info['urls'] = array();
118
 
119
			foreach ($urlBlockInfo['urls'] as $urlInfo) {
120
				$info['urls'][] = self::formatSummaryText($urlInfo['result']);
121
			}
122
 
123
			$urlList[] = $info;
124
 
125
		}
126
 
127
		return $urlList;
128
 
129
	}
130
 
131
	public static function formatSummaryText($summaryInfo) {
132
 
133
		$formatTxt = $summaryInfo['format'];
134
 
135
		// loop through arg information list
136
		foreach ($summaryInfo['args'] as $argInfo) {
137
 
138
			switch ($argInfo['type']) {
139
 
140
				case "HYPERLINK":
141
					$formatTxt = str_replace('{{BEGIN_LINK}}', "<a href='{$argInfo['value']}' target='_blank'>", $formatTxt);
142
					$formatTxt = str_replace('{{END_LINK}}', "</a>", $formatTxt);
143
					break;
144
 
145
				case "URL":
146
					$formatTxt = str_replace('{{' . $argInfo['key'] . '}}', "<a>{$argInfo['value']}</a>" , $formatTxt);
147
					break;
148
 
149
				default:
150
					$formatTxt = str_replace('{{' . $argInfo['key'] . '}}', $argInfo['value'], $formatTxt);
151
					break;
152
 
153
			}
154
 
155
		}
156
 
157
		return $formatTxt;
158
 
159
	}
160
 
161
	// function to show pagespeed checker
162
	function showQuickChecker() {
163
		$this->render('pagespeed/showquickchecker');
164
	}
165
 
166
	function findPageSpeedInfo($searchInfo) {
167
 
168
		// check google api setup
169
		SettingsController::showCheckCategorySettings('google', true);
170
 
171
		$urlList = explode("\n", $searchInfo['website_urls']);
172
		$list = array();
173
		$reportList = array();
174
 
175
		$i = 1;
176
		foreach ($urlList as $url) {
177
			$url = sanitizeData($url);
178
			if(!preg_match('/\w+/', $url)) continue;
179
			if ($i++ > 5) break;
180
			$url = addHttpToUrl($url);
181
			$list[] = str_replace(array("\n", "\r", "\r\n", "\n\r"), "", trim($url));
182
		}
183
 
184
		// loop through the list
185
		foreach ($list as $url) {
186
			$reportList[$url] = array();
187
			$params = array('screenshot' => false, 'strategy' => 'desktop', 'locale' => $_SESSION['lang_code']);
188
			$reportList[$url]['desktop'] = $this->__getPageSpeedInfo($url, $params);
189
			$params = array('screenshot' => false, 'strategy' => 'mobile', 'locale' => $_SESSION['lang_code']);
190
			$reportList[$url]['mobile'] = $this->__getPageSpeedInfo($url, $params);
191
		}
192
 
193
		$this->set('reportList', $reportList);
194
		$this->set('list', $list);
195
		$this->render('pagespeed/findpagespeedinfo');
196
 
197
	}
198
 
199
	# func to show reports
200
	function showReports($searchInfo = '') {
201
 
202
		$userId = isLoggedIn();
203
		if (!empty ($searchInfo['from_time'])) {
204
			$fromTime = $searchInfo['from_time'];
205
		} else {
206
			$fromTime = date('Y-m-d', strtotime('-30 days'));
207
		}
208
 
209
		if (!empty ($searchInfo['to_time'])) {
210
			$toTime = $searchInfo['to_time'];
211
		} else {
212
			$toTime = date('Y-m-d');
213
		}
214
 
215
		$fromTime = addslashes($fromTime);
216
		$toTime = addslashes($toTime);
217
		$this->set('fromTime', $fromTime);
218
		$this->set('toTime', $toTime);
219
 
220
		$websiteController = New WebsiteController();
221
		$websiteList = $websiteController->__getAllWebsites($userId, true);
222
		$this->set('websiteList', $websiteList);
223
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval( $searchInfo['website_id']);
224
		$this->set('websiteId', $websiteId);
225
 
226
		$conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId";
227
		$sql = "select s.* ,w.name from pagespeedresults s,websites w where s.website_id=w.id
228
		and result_date >= '$fromTime' and result_date <= '$toTime' $conditions order by result_date";
229
		$reportList = $this->db->select($sql);
230
 
231
		$i = 0;
232
		$colList = $this->colList;
233
		foreach ($colList as $col => $dbCol) {
234
			$prevRank[$col] = 0;
235
		}
236
 
237
		# loop throgh rank
238
		foreach ($reportList as $key => $repInfo) {
239
 
240
			foreach ($colList as $col => $dbCol) {
241
				$rankDiff[$col] = '';
242
			}
243
 
244
			foreach ($colList as $col => $dbCol) {
245
				if ($i > 0) {
246
					$rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1;
247
					if ($rankDiff[$col] > 0) {
248
						$rankDiff[$col] = "<font class='green'>($rankDiff[$col])</font>";
249
					}elseif ($rankDiff[$col] < 0) {
250
						$rankDiff[$col] = "<font class='red'>($rankDiff[$col])</font>";
251
					}
252
				}
253
				$reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col];
254
			}
255
 
256
			foreach ($colList as $col => $dbCol) {
257
				$prevRank[$col] = $repInfo[$dbCol];
258
			}
259
 
260
			$i++;
261
 
262
		}
263
 
264
		$detailsInfo = $this->dbHelper->getRow("pagespeeddetails", "website_id=$websiteId");
265
		$this->set('detailsInfo', $detailsInfo);
266
 
267
		$this->set('fromPopUp', $searchInfo['fromPopUp']);
268
		$this->set('list', array_reverse($reportList, true));
269
		$this->render('pagespeed/pagespeedreport');
270
	}
271
 
272
	# func to get backlink report for a website
273
	function __getWebsitePageSpeedReport($websiteId, $fromTime, $toTime) {
274
 
275
		$fromTimeLabel = date('Y-m-d', $fromTime);
276
		$toTimeLabel = date('Y-m-d', $toTime);
277
		$conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId";
278
		$sql = "select s.* ,w.name 	from pagespeedresults s,websites w
279
		where s.website_id=w.id" . $conditions . "
280
		and (result_date='$fromTimeLabel' or result_date='$toTimeLabel')
281
		order by result_date DESC Limit 0,2";
282
		$reportList = $this->db->select($sql);
283
		$reportList = array_reverse($reportList);
284
 
285
		$i = 0;
286
		$colList = $this->colList;
287
		foreach ($colList as $col => $dbCol) {
288
			$prevRank[$col] = 0;
289
		}
290
 
291
		# loop throgh rank
292
		foreach ($reportList as $key => $repInfo) {
293
			foreach ($colList as $col => $dbCol) {
294
				$rankDiff[$col] = '';
295
			}
296
 
297
			foreach ($colList as $col => $dbCol) {
298
				if ($i > 0) {
299
					$rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1;
300
					if ($rankDiff[$col] > 0) {
301
						$rankDiff[$col] = "<font class='green'>($rankDiff[$col])</font>";
302
					}elseif ($rankDiff[$col] < 0) {
303
						$rankDiff[$col] = "<font class='red'>($rankDiff[$col])</font>";
304
					}
305
				}
306
				$reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col];
307
			}
308
 
309
			foreach ($colList as $col => $dbCol) {
310
				$prevRank[$col] = $repInfo[$dbCol];
311
			}
312
 
313
			$i++;
314
		}
315
 
316
		$reportList = array_reverse(array_slice($reportList, count($reportList) - 1));
317
		return $reportList;
318
	}
319
 
320
	# func to show graphical reports
155 - 321
	function showGraphicalReports($searchInfo = '') {
103 - 322
		$userId = isLoggedIn();
323
		$fromTime = !empty($searchInfo['from_time']) ? $searchInfo['from_time'] : date('Y-m-d', strtotime('-30 days'));
324
		$toTime = !empty ($searchInfo['to_time']) ? $searchInfo['to_time'] : date("Y-m-d");
325
		$this->set('fromTime', $fromTime);
326
		$this->set('toTime', $toTime);
327
 
328
		$websiteController = New WebsiteController();
329
		$websiteList = $websiteController->__getAllWebsites($userId, true);
330
		$this->set('websiteList', $websiteList);
331
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
332
		$this->set('websiteId', $websiteId);
333
 
334
		$conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId";
335
		$sql = "select s.* ,w.name from pagespeedresults s,websites w where s.website_id=w.id
336
		and result_date >= '$fromTime' and result_date <= '$toTime' $conditions order by result_date";
337
		$reportList = $this->db->select($sql);
338
 
339
		// if reports not empty
340
		$colList = $this->colList;
341
		if (!empty($reportList)) {
342
 
155 - 343
			$colLableList = array($this->spTextPS['Desktop Speed'], $this->spTextPS['Mobile Speed']);
103 - 344
			$dataArr = "['Date', '" . implode("', '", $colLableList) . "']";
345
 
346
			// loop through data list
347
			foreach ($reportList as $dataInfo) {
348
 
349
				$valStr = "";
350
				foreach ($colList as $seId => $seVal) {
351
					$valStr .= ", ";
352
					$valStr .= !empty($dataInfo[$seId])    ? $dataInfo[$seId] : 0;
353
				}
354
 
355
				$dataArr .= ", ['{$dataInfo['result_date']}' $valStr]";
356
			}
357
 
358
			$this->set('dataArr', $dataArr);
359
			$this->set('graphTitle', $this->spTextTools['Backlinks Reports']);
360
			$graphContent = $this->getViewContent('report/graph');
361
 
362
		} else {
363
			$graphContent = showErrorMsg($_SESSION['text']['common']['No Records Found'], false, true);
364
		}
365
 
366
		// get graph content
367
		$this->set('graphContent', $graphContent);
368
		$this->render('pagespeed/graphicalreport');
369
	}
370
 
371
	# func to show genearte reports interface
372
	function showGenerateReports($searchInfo = '') {
373
 
374
		// check google api setup
375
		SettingsController::showCheckCategorySettings('google', true);
376
 
377
		$userId = isLoggedIn();
378
		$websiteController = New WebsiteController();
379
		$websiteList = $websiteController->__getAllWebsites($userId, true);
380
		$this->set('websiteList', $websiteList);
381
		$this->render('pagespeed/generatereport');
382
 
383
	}
384
 
385
	# func to generate reports
386
	function generateReports( $searchInfo='' ) {
387
		$userId = isLoggedIn();
388
		$websiteId = empty ($searchInfo['website_id']) ? '' : intval($searchInfo['website_id']);
389
 
390
		$sql = "select id,url from websites where status=1";
391
		if(!empty($userId) && !isAdmin()) $sql .= " and user_id=$userId";
392
		if(!empty($websiteId)) $sql .= " and id=$websiteId";
393
		$sql .= " order by name";
394
		$websiteList = $this->db->select($sql);
395
 
396
		if(count($websiteList) <= 0){
397
			echo "<p class='note'>".$_SESSION['text']['common']['nowebsites']."!</p>";
398
			exit;
399
		}
400
 
401
		# loop through each websites
402
		foreach ( $websiteList as $websiteInfo ) {
403
			$websiteUrl = addHttpToUrl($websiteInfo['url']);
404
 
405
			$params = array('screenshot' => false, 'strategy' => 'desktop', 'locale' => $_SESSION['lang_code']);
406
			$websiteInfo['desktop'] = $this->__getPageSpeedInfo($websiteUrl, $params);
407
			$params = array('screenshot' => false, 'strategy' => 'mobile', 'locale' => $_SESSION['lang_code']);
408
			$websiteInfo['mobile'] = $this->__getPageSpeedInfo($websiteUrl, $params);
409
 
410
			$this->savePageSpeedResults($websiteInfo, true);
411
 
412
			echo "<p class='note notesuccess'>".$this->spTextPS['Saved page speed results of']." <b>$websiteUrl</b>.....</p>";
413
		}
414
 
415
	}
416
 
417
	# function to save rank details
418
	function savePageSpeedResults($matchInfo, $remove=false) {
419
		$resultDate = date('Y-m-d');
420
 
421
		if($remove){
422
			$sql = "delete from pagespeedresults where website_id={$matchInfo['id']} and result_date='$resultDate'";
423
			$this->db->query($sql);
424
			$sql = "delete from pagespeeddetails where website_id={$matchInfo['id']}";
425
			$this->db->query($sql);
426
		}
427
 
428
		$matchInfo['id'] = intval($matchInfo['id']);
429
		$matchInfo['desktop']['speed_score'] = intval($matchInfo['desktop']['speed_score']);
430
		$matchInfo['mobile']['speed_score'] = intval($matchInfo['mobile']['speed_score']);
431
		$matchInfo['mobile']['usability_score'] = intval($matchInfo['mobile']['usability_score']);
432
 
433
		$sql = "insert into pagespeedresults(website_id, desktop_speed_score, mobile_speed_score, mobile_usability_score, result_date)
434
		values({$matchInfo['id']},{$matchInfo['desktop']['speed_score']},{$matchInfo['mobile']['speed_score']},{$matchInfo['mobile']['usability_score']}, '$resultDate')";
435
		$this->db->query($sql);
436
 
437
		$sql = "insert into pagespeeddetails(website_id, desktop_score_details, mobile_score_details, result_date)
438
		values({$matchInfo['id']},'" . addslashes(serialize($matchInfo['desktop']['details'])) . "',
439
		'" . addslashes(serialize($matchInfo['mobile']['details'])) . "', '$resultDate')";
440
		$this->db->query($sql);
441
 
442
	}
443
 
444
	# function check whether reports already saved
445
	function isReportsExists($websiteId, $time) {
446
		$resultDate = date('Y-m-d', $time);
447
		$sql = "select website_id from pagespeedresults where website_id=$websiteId and result_date='$resultDate'";
448
		$info = $this->db->select($sql, true);
449
		return empty($info['website_id']) ? false : true;
450
	}
451
 
452
}
453
?>