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
/***************************************************************************
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 website controller functions
24
class WebsiteController extends Controller{
25
 
26
	# func to show websites
27
	function listWebsites($info=''){
28
 
29
		$userId = isLoggedIn();
30
		$info['pageno'] = intval($info['pageno']);
31
		$pageScriptPath = 'websites.php?stscheck=';
32
		$pageScriptPath .= isset($info['stscheck']) ? $info['stscheck'] : "select";
33
 
34
		// if admin add user filter
35
		if(isAdmin()){
36
			$sql = "select w.*,u.username from websites w,users u where u.id=w.user_id";
37
			$this->set('isAdmin', 1);
38
 
39
			// if user id is not empty
40
			if (!empty($info['userid'])) {
41
				$sql .= " and w.user_id=".intval($info['userid']);
42
				$pageScriptPath .= "&userid=" . intval($info['userid']);
43
			}
44
 
45
			$userCtrler = New UserController();
46
			$userList = $userCtrler->__getAllUsers();
47
			$this->set('userList', $userList);
48
 
49
		}else{
50
			$sql = "select * from websites w where user_id=$userId";
51
		}
52
 
53
		// search for user name
54
		if (!empty($info['search_name'])) {
55
			$sql .= " and (w.name like '%".addslashes($info['search_name'])."%'
56
			or w.url like '%".addslashes($info['search_name'])."%')";
57
			$pageScriptPath .= "&search_name=" . $info['search_name'];
58
		}
59
 
60
		// if status set
61
		if (isset($info['stscheck']) && $info['stscheck'] != 'select') {
62
			$info['stscheck'] = intval($info['stscheck']);
63
			$sql .= " and w.status='{$info['stscheck']}'";
64
		}
65
 
66
		$sql .= " order by w.name";
67
		$this->set('userId', empty($info['userid']) ? 0 : $info['userid']);
68
 
69
		# pagination setup
70
		$this->db->query($sql, true);
71
		$this->paging->setDivClass('pagingdiv');
72
		$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
73
		$pagingDiv = $this->paging->printPages($pageScriptPath);
74
		$this->set('pagingDiv', $pagingDiv);
75
		$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
76
 
77
		$statusList = array(
78
			$_SESSION['text']['common']['Active'] => 1,
79
			$_SESSION['text']['common']['Inactive'] => 0,
80
		);
81
 
82
		$this->set('statusList', $statusList);
83
		$this->set('info', $info);
84
 
85
		$websiteList = $this->db->select($sql);
86
		$this->set('pageNo', $info['pageno']);
87
		$this->set('list', $websiteList);
88
		$this->render('website/list');
89
	}
90
 
91
	# func to get all Websites
92
	function __getAllWebsites($userId = '', $isAdminCheck = false, $searchName = '') {
93
		$sql = "select * from websites where status=1";
94
		if(!$isAdminCheck || !isAdmin() ) {
95
			if(!empty($userId)) {
96
				$sql .= $this->getWebsiteUserAccessCondition($userId, "id", "user_id");
97
			}
98
		}
99
 
100
		// if search string is not empty
101
		if (!empty($searchName)) {
102
			$sql .= " and (name like '%".addslashes($searchName)."%' or url like '%".addslashes($searchName)."%')";
103
		}
104
 
105
		$sql .= " order by name";
106
		$websiteList = $this->db->select($sql);
107
		return $websiteList;
108
	}
109
 
110
	function __getUserWebsites($userId, $searchInfo=[]) {
111
	    $cond = "user_id=".intval($userId);
112
	    $cond .= isset($searchInfo['status']) ? " and status=".intval($searchInfo['status']) : "";
113
	    $cond .= isset($searchInfo['search']) ? " and url like '%".addslashes($searchInfo['search'])."%'" : "";
114
        return $this->dbHelper->getAllRows('websites', $cond);
115
	}
116
 
117
	# func to get all Websites
118
	function __getCountAllWebsites($userId='', $statusCheck = true, $statusVal = 1){
119
 
120
		$sql = "select count(*) count from websites where 1=1";
121
		$sql .= $statusCheck ? " and status=" . $statusVal : "";
122
 
123
		if (!empty($userId)) {
124
			$sql .= " and user_id=" . intval($userId);
125
		}
126
 
127
		$countInfo = $this->db->select($sql, true);
128
		$count = empty($countInfo['count']) ? 0 : $countInfo['count'];
129
		return $count;
130
	}
131
 
132
	# func to get all Websites having active keywords
133
	function __getAllWebsitesWithActiveKeywords($userId='', $isAdminCheck=false){
134
		$sql = "select w.* from websites w,keywords k where w.id=k.website_id and w.status=1 and k.status=1";
135
		if(!$isAdminCheck || !isAdmin() ){
136
			if(!empty($userId)) {
137
				$sql .= $this->getWebsiteUserAccessCondition($userId);
138
			}
139
		}
140
 
141
		$sql .= " group by w.id order by w.name";
142
		$websiteList = $this->db->select($sql);
143
		return $websiteList;
144
	}
145
 
146
	function getWebsiteUserAccessCondition($userId, $col="w.id", $userCol = "w.user_id") {
147
		if (SP_CUSTOM_DEV) {
148
			$userCtrl = new UserController();
149
			$webAccessList = $userCtrl->getUserWebsiteAccessList($userId);
150
			$webIdList = array_keys($webAccessList);
151
			$webIdList = !empty($webIdList) ? $webIdList : array(0);
152
			$cond = " and ($userCol=" . intval($userId) . " or $col in (".implode($webIdList, ',')."))";
153
		} else {
154
			$cond = " and $userCol=" . intval($userId);
155
		}
156
 
157
		return $cond;
158
	}
159
 
160
	# func to change status
161
	function __changeStatus($websiteId, $status){
162
 
163
		$websiteId = intval($websiteId);
164
		$sql = "update websites set status=$status where id=$websiteId";
165
		$this->db->query($sql);
166
 
167
		$sql = "update keywords set status=$status where website_id=$websiteId";
168
		$this->db->query($sql);
169
	}
170
 
171
	# func to delete website
172
	function __deleteWebsite($websiteId){
173
 
174
		$websiteId = intval($websiteId);
175
		$sql = "delete from websites where id=$websiteId";
176
		$this->db->query($sql);
177
 
178
		# delete all keywords under this website
179
		$sql = "select id from keywords where website_id=$websiteId";
180
		$keywordList = $this->db->select($sql);
181
		$keywordCtrler = New KeywordController();
182
		foreach($keywordList as $keywordInfo){
183
			$keywordCtrler->__deleteKeyword($keywordInfo['id']);
184
		}
185
 
186
		# remove rank results
187
		$sql = "delete from rankresults where website_id=$websiteId";
188
		$this->db->query($sql);
189
 
190
		# remove backlink results
191
		$sql = "delete from backlinkresults where website_id=$websiteId";
192
		$this->db->query($sql);
193
 
194
		# remove saturation results
195
		$sql = "delete from saturationresults where website_id=$websiteId";
196
		$this->db->query($sql);
197
 
198
		# remove site auditor results
199
		$sql = "select id from auditorprojects where website_id=$websiteId";
200
		$info = $this->db->select($sql, true);
201
		if (!empty($info['id'])) {
202
		    $auditorObj = $this->createController('SiteAuditor');
203
		    $auditorObj->__deleteProject($info['id']);
204
		}
205
 
206
		#remove directory results
207
		$sql = "delete from dirsubmitinfo where website_id=$websiteId";
208
		$this->db->query($sql);
209
		$sql = "delete from skipdirectories where website_id=$websiteId";
210
		$this->db->query($sql);
211
 
212
	}
213
 
214
	function newWebsite($info=''){
215
 
216
		$userId = isLoggedIn();
217
		if(!empty($info['check']) && !$this->__getCountAllWebsites($userId)){
218
			$this->set('msg', $this->spTextWeb['plscrtwebsite'].'<br>Please <a href="javascript:void(0);" onclick="scriptDoLoad(\'websites.php\', \'content\')">'.strtolower($_SESSION['text']['common']['Activate']).'</a> '.$this->spTextWeb['yourwebalreday']);
219
		}
220
 
221
		# Validate website count
222
		if (!$this->validateWebsiteCount($userId)) {
223
			$this->set('validationMsg', $this->spTextWeb['Your website count already reached the limit']);
224
		}
225
 
226
		# get all users
227
		if(isAdmin()){
228
			$userCtrler = New UserController();
229
			$userList = $userCtrler->__getAllUsers();
230
			$this->set('userList', $userList);
231
			$this->set('userSelected', empty($info['userid']) ? $userId : $info['userid']);
232
			$this->set('isAdmin', 1);
233
		}
234
 
235
		$this->render('website/new');
236
	}
237
 
238
	function __checkName($name, $userId){
239
 
240
		$sql = "select id from websites where name='".addslashes($name)."' and user_id=$userId";
241
		$listInfo = $this->db->select($sql, true);
242
		return empty($listInfo['id']) ? false :  $listInfo['id'];
243
	}
244
 
245
	function __checkWebsiteUrl($url, $websiteId=0){
246
		$sql = "select id from websites where url='".addslashes($url)."'";
247
		$sql .= $websiteId ? " and id!=$websiteId" : "";
248
		$listInfo = $this->db->select($sql, true);
249
		return empty($listInfo['id']) ? false :  $listInfo['id'];
250
	}
251
 
252
	function createWebsite($listInfo, $apiCall = false){
253
 
254
		// add user id when using as admin or calling api
255
		if (isAdmin() || $apiCall) {
256
			$userId = empty($listInfo['userid']) ? isLoggedIn() : intval($listInfo['userid']);
257
		} else {
258
			$userId = isLoggedIn();
259
		}
260
 
261
		$errMsg = [];
262
		$listInfo['name'] = strip_tags($listInfo['name']);
263
		$this->set('post', $listInfo);
264
		$errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name']));
265
		$errMsg['url'] = formatErrorMsg($this->validate->checkBlank($listInfo['url']));
266
		$listInfo['url'] = addHttpToUrl($listInfo['url']);
267
		$statusVal = isset($listInfo['status']) ? intval($listInfo['status']) : 1;
268
 
269
		// verify the limit for the user
270
		if (!$this->validateWebsiteCount($userId)) {
271
			$this->set('validationMsg', $this->spTextWeb["Your website count already reached the limit"]);
272
			$this->validate->flagErr = true;
273
			$errMsg['limit_error'] = $this->spTextWeb["Your website count already reached the limit"];
274
		}
275
 
276
		// validate website creation
277
		if(!$this->validate->flagErr){
278
			if (!$this->__checkName($listInfo['name'], $userId)) {
279
			    if (!$this->__checkWebsiteUrl($listInfo['url'])) {
280
    				$sql = "insert into websites(name,url,title,description,analytics_view_id,keywords,user_id,status)
281
    				values('".addslashes($listInfo['name'])."','".addslashes($listInfo['url'])."','".
282
    				addslashes($listInfo['title'])."','".addslashes($listInfo['description'])."', '".addslashes($listInfo['analytics_view_id'])."', '".
283
    				addslashes($listInfo['keywords'])."', $userId, $statusVal)";
284
    				$this->db->query($sql);
285
 
286
    				// if api call
287
    				if ($apiCall) {
288
    					return array('success', 'Successfully created website');
289
    				} else {
290
	    				$this->listWebsites();
291
	    				exit;
292
    				}
293
 
294
			    } else {
295
			        $errMsg['url'] = formatErrorMsg($this->spTextWeb['Website already exist']);
296
			    }
297
			}else{
298
				$errMsg['name'] = formatErrorMsg($this->spTextWeb['Website already exist']);
299
			}
300
		}
301
 
302
		// if api call
303
		if ($apiCall) {
304
			return array('error', $errMsg);
305
		} else {
306
			$this->set('errMsg', $errMsg);
307
			$this->newWebsite($listInfo);
308
		}
309
	}
310
 
311
	function __getWebsiteInfo($websiteId){
312
		$websiteId = intval($websiteId);
313
		$sql = "select * from websites where id=$websiteId";
314
		$listInfo = $this->db->select($sql, true);
315
		return empty($listInfo['id']) ? false :  $listInfo;
316
	}
317
 
318
	function editWebsite($websiteId, $listInfo=''){
319
 
320
		$websiteId = intval($websiteId);
321
		if(!empty($websiteId)){
322
			if(empty($listInfo)){
323
				$listInfo = $this->__getWebsiteInfo($websiteId);
324
				$listInfo['oldName'] = $listInfo['name'];
325
			}
326
			$listInfo['title'] = stripslashes($listInfo['title']);
327
			$listInfo['description'] = stripslashes($listInfo['description']);
328
			$listInfo['keywords'] = stripslashes($listInfo['keywords']);
329
			$this->set('post', $listInfo);
330
 
331
			# get all users
332
			if(isAdmin()){
333
				$userCtrler = New UserController();
334
				$userList = $userCtrler->__getAllUsers();
335
				$this->set('userList', $userList);
336
				$this->set('isAdmin', 1);
337
			}
338
 
339
			$this->render('website/edit');
340
			exit;
341
		}
342
		$this->listWebsites();
343
	}
344
 
345
	function updateWebsite($listInfo, $apiCall = false){
346
 
347
		// check whether admin or api calll
348
		if (isAdmin() || $apiCall) {
349
			$userId = empty($listInfo['user_id']) ? isLoggedIn() : $listInfo['user_id'];
350
		} else {
351
			$userId = isLoggedIn();
352
		}
353
 
354
		$listInfo['id'] = intval($listInfo['id']);
355
		$listInfo['name'] = strip_tags($listInfo['name']);
356
		$this->set('post', $listInfo);
357
		$errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name']));
358
		$errMsg['url'] = formatErrorMsg($this->validate->checkBlank($listInfo['url']));
359
		$listInfo['url'] = addHttpToUrl($listInfo['url']);
360
		$statusVal = isset($listInfo['status']) ? "status = " . intval($listInfo['status']) ."," : "";
361
 
362
		// check limit
363
		if(!$this->validate->flagErr && !empty($listInfo['user_id'])){
364
			$websiteInfo = $this->__getWebsiteInfo($listInfo['id']);
365
 
366
			// if user is changed for editing
367
			if ($websiteInfo['user_id'] != $listInfo['user_id']) {
368
 
369
				// verify the limit for the user
370
				if (!$this->validateWebsiteCount($listInfo['user_id'])) {
371
					$this->set('validationMsg', $this->spTextWeb["Your website count already reached the limit"]);
372
					$this->validate->flagErr = true;
373
					$errMsg['limit_error'] = $this->spTextWeb["Your website count already reached the limit"];
374
				}
375
			}
376
		}
377
 
378
		// verify the form
379
		if(!$this->validate->flagErr){
380
 
381
			if($listInfo['name'] != $listInfo['oldName']){
382
				if ($this->__checkName($listInfo['name'], $userId)) {
383
					$errMsg['name'] = formatErrorMsg($this->spTextWeb['Website already exist']);
384
					$this->validate->flagErr = true;
385
				}
386
			}
387
 
388
			if ($this->__checkWebsiteUrl($listInfo['url'], $listInfo['id'])) {
389
			    $errMsg['url'] = formatErrorMsg($this->spTextWeb['Website already exist']);
390
				$this->validate->flagErr = true;
391
			}
392
 
393
			if (!$this->validate->flagErr) {
394
				$sql = "update websites set
395
						name = '".addslashes($listInfo['name'])."',
396
						url = '".addslashes($listInfo['url'])."',
397
						user_id = $userId,
398
						title = '".addslashes($listInfo['title'])."',
399
						description = '".addslashes($listInfo['description'])."',
400
						analytics_view_id = '".addslashes($listInfo['analytics_view_id'])."',
401
						$statusVal
402
						keywords = '".addslashes($listInfo['keywords'])."'
403
						where id={$listInfo['id']}";
404
				$this->db->query($sql);
405
 
406
				// if api call
407
				if ($apiCall) {
408
					return array('success', 'Successfully updated website');
409
				} else {
410
					$this->listWebsites();
411
					exit;
412
				}
413
 
414
			}
415
		}
416
 
417
		// if api call
418
		if ($apiCall) {
419
			return array('error', $errMsg);
420
		} else {
421
			$this->set('errMsg', $errMsg);
422
			$this->editWebsite($listInfo['id'], $listInfo);
423
		}
424
 
425
	}
426
 
427
	# func to crawl meta data of a website
428
	public static function crawlMetaData($websiteUrl, $keyInput='', $pageContent='', $returVal=false) {
429
	    if (empty($pageContent)) {
430
    		if(!preg_match('/\w+/', $websiteUrl)) return;
431
    		$websiteUrl = addHttpToUrl($websiteUrl);
432
    		$spider = New Spider();
433
    		$ret = $spider->getContent($websiteUrl);
434
	    } else {
435
	        $ret['page'] = $pageContent;
436
	        $metaInfo = array();
437
	    }
438
		if(!empty($ret['page'])){
439
 
440
		    if (empty($keyInput)) {
441
 
442
    			# meta title
443
    			preg_match('/<TITLE>(.*?)<\/TITLE>/si', $ret['page'], $matches);
444
    			if(!empty($matches[1])){
445
    			    if ($returVal) {
446
    			        $metaInfo['page_title'] = $matches[1];
447
    			    } else {
448
    				    WebsiteController::addInputValue($matches[1], 'webtitle');
449
    			    }
450
    			}
451
 
452
    			# meta description
453
    			preg_match('/<META.*?name="description".*?content="(.*?)"/si', $ret['page'], $matches);
454
    			if(empty($matches[1])){
455
    				preg_match("/<META.*?name='description'.*?content='(.*?)'/si", $ret['page'], $matches);
456
    			}
457
    			if(empty($matches[1])){
458
    				preg_match('/<META content="(.*?)" name="description"/si', $ret['page'], $matches);
459
    			}
460
    			if(!empty($matches[1])){
461
    			    if ($returVal) {
462
    			        $metaInfo['page_description'] = $matches[1];
463
    			    } else {
464
    				    WebsiteController::addInputValue($matches[1], 'webdescription');
465
    			    }
466
    			}
467
		    }
468
 
469
			# meta keywords
470
			preg_match('/<META.*?name="keywords".*?content="(.*?)"/si', $ret['page'], $matches);
471
			if(empty($matches[1])){
472
				preg_match("/<META.*?name='keywords'.*?content='(.*?)'/si", $ret['page'], $matches);
473
			}
474
			if(empty($matches[1])){
475
				preg_match('/<META content="(.*?)" name="keywords"/si', $ret['page'], $matches);
476
			}
477
 
478
			if(!empty($matches[1])){
479
    	        if ($returVal) {
480
    			    $metaInfo['page_keywords'] = $matches[1];
481
    			} else {
482
				    WebsiteController::addInputValue($matches[1], 'webkeywords');
483
    			}
484
			}
485
		}
486
		return $metaInfo;
487
	}
488
 
489
	public static function addInputValue($value, $col) {
490
 
491
		$value = removeNewLines($value);
492
		?>
493
		<script type="text/javascript">
494
			document.getElementById('<?php echo $col;?>').value = '<?php echo str_replace("'", "\'", $value);?>';
495
		</script>
496
		<?php
497
	}
498
 
499
	function showImportWebsites() {
500
 
501
		$userId = isLoggedIn();
502
 
503
		# get all users
504
		if(isAdmin()){
505
			$userCtrler = New UserController();
506
			$userList = $userCtrler->__getAllUsers();
507
			$this->set('userList', $userList);
508
			$this->set('userSelected', empty($info['userid']) ? $userId : $info['userid']);
509
			$this->set('isAdmin', 1);
510
		}
511
 
512
		// Check the user website count for validation
513
		if (!isAdmin()) {
514
			$this->setValidationMessageForLimit($userId);
515
		}
516
 
517
		$this->set('delimiter', ',');
518
		$this->set('enclosure', '"');
519
		$this->set('escape', '\\');
520
		$this->render('website/importwebsites');
521
	}
522
 
523
	# function to set validation message for the limit
524
	function setValidationMessageForLimit($userId) {
525
 
526
		// Check the user website count for validation
527
		$userTypeCtrlr = new UserTypeController();
528
		$userWebsiteCount = $this->__getCountAllWebsites($userId, false);
529
		$userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId);
530
		$validCount = $userTypeDetails['websitecount'] - $userWebsiteCount;
531
		$validCount = $validCount > 0 ? $validCount : 0;
532
		$validationMsg = str_replace("[websitecount]", "<b>$validCount</b>", $this->spTextWeb['You can add only websitecount websites more']);
533
		$this->set('validationMsg', $validationMsg);
534
		return $validationMsg;
535
 
536
	}
537
 
538
	function importWebsiteFromCsv($info) {
539
 
540
		// if csv file is not uploaded
541
		if (empty($_FILES['website_csv_file']['name'])) {
542
			print "<script>alert('".$this->spTextWeb['Please enter CSV file']."')</script>";
543
			return False;
544
		}
545
 
546
		$userId = isAdmin() ? intval($info['userid']) : isLoggedIn();
547
 
548
		$resultInfo = array(
549
			'total' => 0,
550
			'valid' => 0,
551
			'invalid' => 0,
552
		);
553
		$count = 0;
554
 
555
		// process file upload option
556
		$fileInfo = $_FILES['website_csv_file'];
557
		if (!empty($fileInfo['name']) && !empty($userId)) {
558
			if ($fileInfo["type"] == "text/csv" || $fileInfo["type"] == "application/vnd.ms-excel") {
559
				$targetFile = SP_TMPPATH . "/".$fileInfo['name'];
560
				if(move_uploaded_file($fileInfo['tmp_name'], $targetFile)) {
561
 
562
					$delimiterChar = empty($info['delimiter']) ? ',' : $info['delimiter'];
563
					$enclosureChar = empty($info['enclosure']) ? '"' : $info['enclosure'];
564
					$escapeChar = empty($info['escape']) ? '\\' : $info['escape'];
565
 
566
					// open file read through csv file
567
					if (($handle = fopen($targetFile, "r")) !== FALSE) {
568
 
569
						// loop through the data row
570
						while (($websiteInfo = fgetcsv($handle, 4096, $delimiterChar, $enclosureChar, $escapeChar)) !== FALSE) {
571
							if (empty($websiteInfo[0])) continue;
572
							$count++;
573
						}
574
 
575
						fclose($handle);
576
					}
577
 
578
					// Check the user website count for validation
579
					if (!$this->validateWebsiteCount($userId, $count)) {
580
						$validationMag = strip_tags($this->setValidationMessageForLimit($userId));
581
						print "<script>alert('$validationMag')</script>";
582
						return False;
583
					}
584
 
585
					// open file read through csv file
586
					if (($handle = fopen($targetFile, "r")) !== FALSE) {
587
 
588
						// loop through the data row
589
						while (($websiteInfo = fgetcsv($handle, 4096, $delimiterChar, $enclosureChar, $escapeChar)) !== FALSE) {
590
							if (empty($websiteInfo[0])) continue;
591
							$status = $this->importWebsite($websiteInfo, $userId);
592
							$resultInfo[$status] += 1;
593
							$resultInfo['total'] += 1;
594
						}
595
 
596
						fclose($handle);
597
					}
598
				}
599
			}
600
		}
601
 
602
 
603
		$text = "<p class=\'note\' id=\'note\'><b>Website import process started. It will take some time depends on the number of websites needs to be imported!</b></p><div id=\'subcontmed\'></div>";
604
		print "<script type='text/javascript'>parent.document.getElementById('import_website_div').innerHTML = '$text';</script>";
605
		print "<script>parent.showLoadingIcon('subcontmed', 0)</script>";
606
		$spText = $_SESSION['text'];
607
		$resText = '<table width="40%" border="0" cellspacing="0" cellpadding="0px" class="summary_tab" align="center">'.
608
		'<tr><td class="topheader" colspan="10">Import Summary</td></tr>'.
609
				'<tr><th class="leftcell">'.$spText['common']['Total'].':</th><td>'.$resultInfo['total'].'</td><th>Valid:</th><td>'.$resultInfo['valid'].'</td></tr>'.
610
				'<tr><th>Invalid:</th><td>'.$resultInfo['invalid'].'</td><th>&nbsp;</th><td>&nbsp;</td></tr>'.
611
		'</table>';
612
		echo "<script type='text/javascript'>parent.document.getElementById('subcontmed').innerHTML = '$resText'</script>";
613
        echo "<script type='text/javascript'>parent.document.getElementById('note').style.display='none';</script>";
614
	}
615
 
616
	function importWebsite($wInfo, $userId) {
617
		$status = 'invalid';
618
 
619
		if (!empty($wInfo[0]) && !empty($wInfo[1])) {
620
		    $listInfo = [];
621
			$listInfo['name'] = trim($wInfo[0]);
622
			$listInfo['url'] = trim($wInfo[1]);
623
			$listInfo['title'] = $wInfo[2] ? trim($wInfo[2]) : "";
624
			$listInfo['description'] = $wInfo[3] ? trim($wInfo[3]) : "";
625
			$listInfo['keywords'] = $wInfo[4] ? trim($wInfo[4]) : "";
626
			$listInfo['status'] = intval($wInfo[5]);
627
			$listInfo['analytics_view_id'] = $wInfo[6] ? trim($wInfo[6]) : "";
628
			$listInfo['userid'] = $userId;
629
			$return = $this->createWebsite($listInfo, true);
630
 
631
			if ($return[0] == 'success') {
632
				$status = "valid";
633
			}
634
		}
635
 
636
		return $status;
637
	}
638
 
639
	// Function to check / validate the user type website count
640
	function validateWebsiteCount($userId, $newCount = 1) {
641
		$userCtrler = new UserController();
642
 
643
		// if admin user id return true
644
		if ($userCtrler->isAdminUserId($userId)) {
645
			return true;
646
		}
647
 
648
		$userTypeCtrlr = new UserTypeController();
649
		$userWebsiteCount = $this->__getCountAllWebsites($userId, false);
650
		$userWebsiteCount += $newCount;
651
		$userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId);
652
 
653
		// if limit is set and not -1
654
		if (isset($userTypeDetails['websitecount']) && $userTypeDetails['websitecount'] >= 0) {
655
 
656
			// check whether count greater than limit
657
			if ($userWebsiteCount <= $userTypeDetails['websitecount']) {
658
				return true;
659
			} else {
660
				return false;
661
			}
662
 
663
		} else {
664
			return true;
665
		}
666
 
667
	}
668
 
669
	function showimportWebmasterToolsWebsites() {
670
 
671
		$userId = isLoggedIn();
672
		$this->set('spTextTools', $this->getLanguageTexts('seotools', $_SESSION['lang_code']));
673
		$userCtrler = New UserController();
674
 
675
		// get all users
676
		if(isAdmin()){
677
			$userList = $userCtrler->__getAllUsers();
678
			$this->set('userList', $userList);
679
			$this->set('userSelected', empty($info['userid']) ? $userId : $info['userid']);
680
			$this->set('isAdmin', 1);
681
		} else {
682
			$userInfo = $userCtrler->__getUserInfo($userId);
683
			$this->set('userName', $userInfo['username']);
684
		}
685
 
686
		// Check the user website count for validation
687
		if (!isAdmin()) {
688
			$this->setValidationMessageForLimit($userId);
689
		}
690
 
691
		$this->render('website/import_webmaster_tools_websites');
692
	}
693
 
694
	function importWebmasterToolsWebsites($info) {
695
		$userId = isAdmin() ? intval($info['userid']) : isLoggedIn();
696
		$limitReached = false;
697
		$importList = array();
698
 
699
		// verify the limit for the user
700
		if (!$this->validateWebsiteCount($userId)) {
701
			showErrorMsg($this->spTextWeb["Your website count already reached the limit"]);
702
		}
703
 
704
		$gapiCtrler = new WebMasterController();
705
		$result = $gapiCtrler->getAllSites($userId);
706
 
707
		// check whether error occured while api call
708
		if (!$result['status']) {
709
			showErrorMsg($result['msg']);
710
		}
711
 
712
		// loop through website list
713
		foreach ($result['resultList'] as $websiteInfo) {
714
 
715
			if ($websiteInfo->permissionLevel != 'siteOwner') continue;
716
 
717
			// chekc whether website existing or not
718
			if (!$this->__checkWebsiteUrl($websiteInfo->siteUrl) && !$this->__checkWebsiteUrl(Spider::removeTrailingSlash($websiteInfo->siteUrl))) {
719
				$websiteName = formatUrl($websiteInfo->siteUrl, false);
720
				$websiteName = Spider::removeTrailingSlash($websiteName);
721
				$listInfo['name'] = $websiteName;
722
				$listInfo['url'] = $websiteInfo->siteUrl;
723
				$listInfo['title'] = $websiteName;
724
				$listInfo['description'] = $websiteName;
725
				$listInfo['keywords'] = $websiteName;
726
				$listInfo['status'] = 1;
727
				$listInfo['userid'] = $userId;
728
				$return = $this->createWebsite($listInfo, true);
729
 
730
				// if success, check of number of websites can be added
731
				if ($return[0] == 'success') {
732
					$importList[] = $websiteInfo->siteUrl;
733
 
734
					// if reached website add limit
735
					if (!$this->validateWebsiteCount($userId)) {
736
						$limitReached = true;
737
						break;
738
					}
739
 
740
				}
741
 
742
			}
743
 
744
		}
745
 
746
		// show results
747
		showSuccessMsg("<b>".$this->spTextWeb["Successfully imported following websites"]."</b>:", false);
748
		foreach ($importList as $url) showSuccessMsg($url, false);
749
 
750
		// if website add limit reached
751
		if ($limitReached) {
752
			showErrorMsg($this->spTextWeb["Your website count already reached the limit"]);
753
		}
754
 
755
	}
756
 
757
	function addToWebmasterTools($websiteId) {
758
		$webisteInfo = $this->__getWebsiteInfo($websiteId);
759
		$gapiCtrler = new WebMasterController();
760
		$result = $gapiCtrler->addWebsite($webisteInfo['url'], $webisteInfo['user_id']);
761
 
762
		// chekc whether error occured while api call
763
		if ($result['status']) {
764
			$activateUrl = "https://www.google.com/webmasters/verification/verification?tid=alternate&siteUrl=" . $webisteInfo['url'];
765
			$successMsg = $this->spTextWeb["Website successfully added to webmaster tools"] . ": " . $webisteInfo['url'] . "<br><br>";
766
			$successMsg .= "<a href='$activateUrl' target='_blank'>Click Here</a> to activate the website in webmaster tools.";
767
			showSuccessMsg($successMsg, false);
768
		} else {
769
			showErrorMsg($result['msg'], false);
770
		}
771
 
772
	}
773
 
774
	// func to list sitemaps
775
	function listSitemap($info, $summaryPage = false, $cronUserId=false) {
776
		$userId = !empty($cronUserId) ? $cronUserId : isLoggedIn();
777
		$this->set('spTextTools', $this->getLanguageTexts('seotools', $_SESSION['lang_code']));
778
		$this->set('spTextSitemap', $this->getLanguageTexts('sitemap', $_SESSION['lang_code']));
779
		$this->set('spTextHome', $this->getLanguageTexts('home', $_SESSION['lang_code']));
780
		$this->set('spTextDirectory', $this->getLanguageTexts('directory', $_SESSION['lang_code']));
781
 
782
		$websiteList = $this->__getAllWebsites($userId, true);
783
		$this->set('websiteList', $websiteList);
784
		$websiteId = isset($info['website_id']) ? intval($info['website_id']) : $websiteList[0]['id'];
785
		$this->set('websiteId', $websiteId);
786
 
787
		$whereCond = "status=1";
788
 
789
		// check whethere request from cron job
790
		if ($cronUserId && empty($websiteId)) {
791
			$wIdList = [];
792
			foreach ($websiteList as $websiteInfo) $wIdList[] = $websiteInfo['id'];
793
			$whereCond .= " and website_id in (".implode(',', $wIdList).")";
794
		} else {
795
			$whereCond .= !empty($websiteId) ? " and website_id=$websiteId" : "";
796
		}
797
 
798
		$sitemapList = $this->dbHelper->getAllRows("webmaster_sitemaps", $whereCond);
799
 
800
		$this->set('list', $sitemapList);
801
		$this->set('summaryPage', $summaryPage);
802
 
803
		// if pdf export
804
		if ($summaryPage) {
805
			return $this->getViewContent('sitemap/list_webmaster_sitemap_list');
806
		} else {
807
			$this->render('sitemap/list_webmaster_sitemap_list');
808
		}
809
 
810
	}
811
 
812
	// func to import webmaster tools sitemaps
813
	function importWebmasterToolsSitemaps($websiteId, $cronJob = false) {
814
		$websiteId = intval($websiteId);
815
		$webisteInfo = $this->__getWebsiteInfo($websiteId);
816
 
817
		// call webmaster api
818
		$gapiCtrler = new WebMasterController();
819
		$result = $gapiCtrler->getAllSitemap($webisteInfo['url'], $webisteInfo['user_id']);
820
 
821
		// check whether error occured while api call
822
		if ($result['status']) {
823
 
824
			// change status of all sitemaps
825
			$dataList = array('status' => 0);
826
			$this->dbHelper->updateRow("webmaster_sitemaps", $dataList, " website_id=$websiteId");
827
 
828
			// loop through webmaster tools list
829
			foreach ($result['resultList'] as $sitemapInfo) {
830
 
831
				$dataList = array(
832
					'last_submitted' => date('Y-m-d H:i:s', strtotime($sitemapInfo->lastSubmitted)),
833
					'last_downloaded' => date('Y-m-d H:i:s', strtotime($sitemapInfo->lastDownloaded)),
834
					'is_pending|int' => $sitemapInfo->isPending,
835
					'warnings|int' => $sitemapInfo->warnings,
836
					'errors|int' => $sitemapInfo->errors,
837
					'submitted|int' => $sitemapInfo->contents[0]['submitted'],
838
					'indexed|int' => $sitemapInfo->contents[0]['indexed'],
839
					'status' => 1,
840
				);
841
 
842
				$rowInfo = $this->dbHelper->getRow("webmaster_sitemaps", " website_id=$websiteId and path='$sitemapInfo->path'");
843
				if (!empty($rowInfo['id'])) {
844
					$this->dbHelper->updateRow("webmaster_sitemaps", $dataList, " id=" . $rowInfo['id']);
845
				} else {
846
					$dataList['website_id|int'] = $websiteId;
847
					$dataList['path'] = $sitemapInfo->path;
848
					$this->dbHelper->insertRow("webmaster_sitemaps", $dataList);
849
				}
850
 
851
			}
852
 
853
			if ($cronJob) {
854
				echo $this->spTextWeb["Successfully sync sitemaps from webmaster tools"] . "<br>\n";
855
			} else {
856
				showSuccessMsg($this->spTextWeb["Successfully sync sitemaps from webmaster tools"], false);
857
			}
858
 
859
		} else {
860
			showErrorMsg($result['msg'], false);
861
		}
862
 
863
	}
864
 
865
	// func to show submit sitemap form
866
	function showSubmitSitemap($info) {
867
		$userId = isLoggedIn();
868
		$this->set('websiteList', $this->__getAllWebsites($userId, true));
869
		$this->set('websiteId', intval($info['website_id']));
870
		$this->set('spTextTools', $this->getLanguageTexts('seotools', $_SESSION['lang_code']));
871
		$this->render('sitemap/submit_sitemap');
872
	}
873
 
874
	// func to submit sitemap
875
	function submitSitemap($info) {
876
		$webisteInfo = $this->__getWebsiteInfo($info['website_id']);
877
		$spTextWebproxy = $this->getLanguageTexts('QuickWebProxy', $_SESSION['lang_code']);
878
 
879
		if (empty($info['sitemap_url'])) {
880
			showErrorMsg($spTextWebproxy["Please enter a valid url"]);
881
		}
882
 
883
		$info['sitemap_url'] = addHttpToUrl($info['sitemap_url']);
884
 
885
		// if website url not correct
886
		if (!preg_match("/". preg_quote($webisteInfo['url'], '/') ."/i", $info['sitemap_url'])) {
887
			showErrorMsg($spTextWebproxy["Please enter a valid url"]);
888
		}
889
 
890
		// call webmaster api
891
		$gapiCtrler = new WebMasterController();
892
		$result = $gapiCtrler->submitSitemap($webisteInfo['url'], $info['sitemap_url'], $webisteInfo['user_id']);
893
 
894
		// check whether error occured while api call
895
		if ($result['status']) {
896
			showSuccessMsg($this->spTextWeb["Sitemap successfully added to webmaster tools"] . ": " . $info['sitemap_url'], false);
897
 
898
			// update seo panel webmaster tool sitemaps
899
			$this->importWebmasterToolsSitemaps($webisteInfo['id']);
900
 
901
		} else {
902
			showErrorMsg($result['msg'], false);
903
		}
904
 
905
	}
906
 
907
	function deleteWebmasterToolSitemap($sitemapId) {
908
		$sitemapId = intval($sitemapId);
909
		$sitemapInfo = $this->dbHelper->getRow("webmaster_sitemaps", "id=$sitemapId");
910
 
911
		if (empty($sitemapInfo['id'])) {
912
			showErrorMsg("Please provide a valid sitemap id");
913
		}
914
 
915
		$webisteInfo = $this->__getWebsiteInfo($sitemapInfo['website_id']);
916
		$gapiCtrler = new WebMasterController();
917
		$result = $gapiCtrler->deleteWebsiteSitemap($webisteInfo['url'], $sitemapInfo['path'], $webisteInfo['user_id']);
918
 
919
		// check whether error occured while api call
920
		if ($result['status']) {
921
			$this->dbHelper->updateRow("webmaster_sitemaps", array('status' => 0), "id=$sitemapId");
922
			showSuccessMsg($this->spTextWeb["Successfully deleted sitemap from webmaster tools"], false);
923
		} else {
924
			showErrorMsg($result['msg'], false);
925
		}
926
 
927
		$this->listSitemap(array('website_id' => $sitemapInfo['website_id']));
928
 
929
	}
930
 
931
 
932
}
933
?>