Subversion Repositories cheapmusic

Rev

Go to most recent revision | Details | 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
		'mobile_usability_score' => 'mobile_usability_score',
30
	);
31
 
32
	// function to get moz rank
33
	function __getPageSpeedInfo ($url, $params = array(), $apiKey = '', $returnLog = false) {
34
 
35
		include_once(SP_LIBPATH . "/google-api-php-client/vendor/autoload.php");
36
		$pageSpeedInfo = array();
37
		$crawlInfo = array();
38
 
39
		$apiKey = !empty($apiKey) ? $apiKey : SP_GOOGLE_API_KEY;
40
 
41
		// if empty no need to crawl
42
		if (!empty($apiKey)) {
43
 
44
			$client = new Google_Client();
45
			$client->setApplicationName("SP_CHECKER");
46
			$client->setDeveloperKey($apiKey);
47
 
48
			try {
49
 
50
				// split and select main language if sub language selected
51
				if (stristr($params['locale'], '-')) {
52
					list($params['locale'], $tmpVar) = explode('-', $params['locale']);
53
				}
54
 
55
				$service = new Google_Service_Pagespeedonline($client);
56
				$pageSpeedInfo = $service->pagespeedapi->runpagespeed($url, $params);
57
				$pageSpeedInfo = self::formatPageSpeedData($pageSpeedInfo);
58
			} catch (Exception $e) {
59
				$err = $e->getMessage();
60
				$errData = json_decode($err);
61
				$crawlInfo['crawl_status'] = 0;
62
				$crawlInfo['log_message'] = $_SESSION['text']['label']['Fail'];
63
				$crawlInfo['log_message'] .= !empty($errData->error->errors[0]->reason) ? ": " . $errData->error->errors[0]->reason . " :: " . $errData->error->errors[0]->message : "";
64
			}
65
 
66
		} else {
67
			$crawlInfo['crawl_status'] = 0;
68
			$crawlInfo['log_message'] = "Google api key not set.";
69
 
70
			$alertCtler = new AlertController();
71
			$alertInfo = array(
72
				'alert_subject' => "Click here to enter Google API key",
73
				'alert_message' => "Error: Google API key not found",
74
				'alert_url' => SP_WEBPATH ."/admin-panel.php?sec=google-settings",
75
				'alert_type' => "danger",
76
				'alert_category' => "reports",
77
			);
78
			$alertCtler->createAlert($alertInfo, false, true);
79
 
80
		}
81
 
82
		return $returnLog ? array($pageSpeedInfo, $crawlInfo) : $pageSpeedInfo;
83
 
84
	}
85
 
86
	public static function formatPageSpeedData($pageSpeedInfo) {
87
 
88
		$pageSpeedData = array(
89
			'speed_score' => !empty($pageSpeedInfo['ruleGroups']['SPEED']['score'])	? $pageSpeedInfo['ruleGroups']['SPEED']['score'] : 0,
90
			'usability_score' => !empty($pageSpeedInfo['ruleGroups']['USABILITY']['score'])	? $pageSpeedInfo['ruleGroups']['USABILITY']['score'] : 0,
91
		);
92
 
93
		$detailsInfo = array();
94
		foreach ($pageSpeedInfo['formattedResults']['ruleResults'] as $ruleSet => $ruleSetInfo) {
95
 
96
			$detailsInfo[$ruleSet] = array(
97
				'localizedRuleName' => $ruleSetInfo['localizedRuleName'],
98
				'ruleImpact' => $ruleSetInfo['ruleImpact'],
99
				'impactGroup' => implode(',', $ruleSetInfo['groups']),
100
				'summary' => self::formatSummaryText($ruleSetInfo['summary']),
101
				'urlBlocks' => self::formatUrlBlock($ruleSetInfo['urlBlocks']),
102
			);
103
 
104
		}
105
 
106
		$pageSpeedData['details'] = $detailsInfo;
107
		return $pageSpeedData;
108
 
109
	}
110
 
111
	public static function formatUrlBlock($urlBlockList) {
112
		$urlList = array();
113
 
114
		foreach ($urlBlockList as $urlBlockInfo) {
115
			$info['header'] = self::formatSummaryText($urlBlockInfo['header']);
116
			$info['urls'] = array();
117
 
118
			foreach ($urlBlockInfo['urls'] as $urlInfo) {
119
				$info['urls'][] = self::formatSummaryText($urlInfo['result']);
120
			}
121
 
122
			$urlList[] = $info;
123
 
124
		}
125
 
126
		return $urlList;
127
 
128
	}
129
 
130
	public static function formatSummaryText($summaryInfo) {
131
 
132
		$formatTxt = $summaryInfo['format'];
133
 
134
		// loop through arg information list
135
		foreach ($summaryInfo['args'] as $argInfo) {
136
 
137
			switch ($argInfo['type']) {
138
 
139
				case "HYPERLINK":
140
					$formatTxt = str_replace('{{BEGIN_LINK}}', "<a href='{$argInfo['value']}' target='_blank'>", $formatTxt);
141
					$formatTxt = str_replace('{{END_LINK}}', "</a>", $formatTxt);
142
					break;
143
 
144
				case "URL":
145
					$formatTxt = str_replace('{{' . $argInfo['key'] . '}}', "<a>{$argInfo['value']}</a>" , $formatTxt);
146
					break;
147
 
148
				default:
149
					$formatTxt = str_replace('{{' . $argInfo['key'] . '}}', $argInfo['value'], $formatTxt);
150
					break;
151
 
152
			}
153
 
154
		}
155
 
156
		return $formatTxt;
157
 
158
	}
159
 
160
	// function to show pagespeed checker
161
	function showQuickChecker() {
162
		$this->render('pagespeed/showquickchecker');
163
	}
164
 
165
	function findPageSpeedInfo($searchInfo) {
166
 
167
		// check google api setup
168
		SettingsController::showCheckCategorySettings('google', true);
169
 
170
		$urlList = explode("\n", $searchInfo['website_urls']);
171
		$list = array();
172
		$reportList = array();
173
 
174
		$i = 1;
175
		foreach ($urlList as $url) {
176
			$url = sanitizeData($url);
177
			if(!preg_match('/\w+/', $url)) continue;
178
			if ($i++ > 5) break;
179
			$url = addHttpToUrl($url);
180
			$list[] = str_replace(array("\n", "\r", "\r\n", "\n\r"), "", trim($url));
181
		}
182
 
183
		// loop through the list
184
		foreach ($list as $url) {
185
			$reportList[$url] = array();
186
			$params = array('screenshot' => false, 'strategy' => 'desktop', 'locale' => $_SESSION['lang_code']);
187
			$reportList[$url]['desktop'] = $this->__getPageSpeedInfo($url, $params);
188
			$params = array('screenshot' => false, 'strategy' => 'mobile', 'locale' => $_SESSION['lang_code']);
189
			$reportList[$url]['mobile'] = $this->__getPageSpeedInfo($url, $params);
190
		}
191
 
192
		$this->set('reportList', $reportList);
193
		$this->set('list', $list);
194
		$this->render('pagespeed/findpagespeedinfo');
195
 
196
	}
197
 
198
	# func to show reports
199
	function showReports($searchInfo = '') {
200
 
201
		$userId = isLoggedIn();
202
		if (!empty ($searchInfo['from_time'])) {
203
			$fromTime = $searchInfo['from_time'];
204
		} else {
205
			$fromTime = date('Y-m-d', strtotime('-30 days'));
206
		}
207
 
208
		if (!empty ($searchInfo['to_time'])) {
209
			$toTime = $searchInfo['to_time'];
210
		} else {
211
			$toTime = date('Y-m-d');
212
		}
213
 
214
		$fromTime = addslashes($fromTime);
215
		$toTime = addslashes($toTime);
216
		$this->set('fromTime', $fromTime);
217
		$this->set('toTime', $toTime);
218
 
219
		$websiteController = New WebsiteController();
220
		$websiteList = $websiteController->__getAllWebsites($userId, true);
221
		$this->set('websiteList', $websiteList);
222
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval( $searchInfo['website_id']);
223
		$this->set('websiteId', $websiteId);
224
 
225
		$conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId";
226
		$sql = "select s.* ,w.name from pagespeedresults s,websites w where s.website_id=w.id
227
		and result_date >= '$fromTime' and result_date <= '$toTime' $conditions order by result_date";
228
		$reportList = $this->db->select($sql);
229
 
230
		$i = 0;
231
		$colList = $this->colList;
232
		foreach ($colList as $col => $dbCol) {
233
			$prevRank[$col] = 0;
234
		}
235
 
236
		# loop throgh rank
237
		foreach ($reportList as $key => $repInfo) {
238
 
239
			foreach ($colList as $col => $dbCol) {
240
				$rankDiff[$col] = '';
241
			}
242
 
243
			foreach ($colList as $col => $dbCol) {
244
				if ($i > 0) {
245
					$rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1;
246
					if ($rankDiff[$col] > 0) {
247
						$rankDiff[$col] = "<font class='green'>($rankDiff[$col])</font>";
248
					}elseif ($rankDiff[$col] < 0) {
249
						$rankDiff[$col] = "<font class='red'>($rankDiff[$col])</font>";
250
					}
251
				}
252
				$reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col];
253
			}
254
 
255
			foreach ($colList as $col => $dbCol) {
256
				$prevRank[$col] = $repInfo[$dbCol];
257
			}
258
 
259
			$i++;
260
 
261
		}
262
 
263
		$detailsInfo = $this->dbHelper->getRow("pagespeeddetails", "website_id=$websiteId");
264
		$this->set('detailsInfo', $detailsInfo);
265
 
266
		$this->set('fromPopUp', $searchInfo['fromPopUp']);
267
		$this->set('list', array_reverse($reportList, true));
268
		$this->render('pagespeed/pagespeedreport');
269
	}
270
 
271
	# func to get backlink report for a website
272
	function __getWebsitePageSpeedReport($websiteId, $fromTime, $toTime) {
273
 
274
		$fromTimeLabel = date('Y-m-d', $fromTime);
275
		$toTimeLabel = date('Y-m-d', $toTime);
276
		$conditions = empty ($websiteId) ? "" : " and s.website_id=$websiteId";
277
		$sql = "select s.* ,w.name 	from pagespeedresults s,websites w
278
		where s.website_id=w.id" . $conditions . "
279
		and (result_date='$fromTimeLabel' or result_date='$toTimeLabel')
280
		order by result_date DESC Limit 0,2";
281
		$reportList = $this->db->select($sql);
282
		$reportList = array_reverse($reportList);
283
 
284
		$i = 0;
285
		$colList = $this->colList;
286
		foreach ($colList as $col => $dbCol) {
287
			$prevRank[$col] = 0;
288
		}
289
 
290
		# loop throgh rank
291
		foreach ($reportList as $key => $repInfo) {
292
			foreach ($colList as $col => $dbCol) {
293
				$rankDiff[$col] = '';
294
			}
295
 
296
			foreach ($colList as $col => $dbCol) {
297
				if ($i > 0) {
298
					$rankDiff[$col] = ($prevRank[$col] - $repInfo[$dbCol]) * -1;
299
					if ($rankDiff[$col] > 0) {
300
						$rankDiff[$col] = "<font class='green'>($rankDiff[$col])</font>";
301
					}elseif ($rankDiff[$col] < 0) {
302
						$rankDiff[$col] = "<font class='red'>($rankDiff[$col])</font>";
303
					}
304
				}
305
				$reportList[$key]['rank_diff_'.$col] = empty ($rankDiff[$col]) ? '' : $rankDiff[$col];
306
			}
307
 
308
			foreach ($colList as $col => $dbCol) {
309
				$prevRank[$col] = $repInfo[$dbCol];
310
			}
311
 
312
			$i++;
313
		}
314
 
315
		$reportList = array_reverse(array_slice($reportList, count($reportList) - 1));
316
		return $reportList;
317
	}
318
 
319
	# func to show graphical reports
320
	function showGraphicalReports($searchInfo = '') {
321
 
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
 
343
			$colLableList = array($this->spTextPS['Desktop Speed'], $this->spTextPS['Mobile Speed'], $this->spTextPS['Mobile Usability']);
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
?>