Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 1
<?php
2
 
3
/***************************************************************************
4
 *   Copyright (C) 2009-2011 by Geo Varghese(www.seopanel.in)  	           *
5
 *   sendtogeo@gmail.com   												   *
6
 *                                                                         *
7
 *   This program is free software; you can redistribute it and/or modify  *
8
 *   it under the terms of the GNU General Public License as published by  *
9
 *   the Free Software Foundation; either version 2 of the License, or     *
10
 *   (at your option) any later version.                                   *
11
 *                                                                         *
12
 *   This program is distributed in the hope that it will be useful,       *
13
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
14
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
15
 *   GNU General Public License for more details.                          *
16
 *                                                                         *
17
 *   You should have received a copy of the GNU General Public License     *
18
 *   along with this program; if not, write to the                         *
19
 *   Free Software Foundation, Inc.,                                       *
20
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
21
 ***************************************************************************/
22
 
23
# class defines all social media controller functions
24
class SocialMediaController extends Controller{
25
 
26
    var $linkTable = "social_media_links";
27
    var $linkReportTable = "social_media_link_results";
28
    var $layout = "ajax";
29
    var $pageScriptPath = 'social_media.php';
30
    var $serviceList;
31
    var $colList;
32
 
33
    function __construct() {
34
 
35
    	$this->serviceList = [
36
    		"facebook" => [
37
    			"label" => "Facebook",
38
    			"regex" => [
39
    				"like" => '/id="PagesLikesCountDOMID.*?<span.*?>(.*?)<span/is',
40
    				"follower" => '/people like this.*?<div>(\d.*?)people follow this/is',
41
    			],
42
    			"url_part" => '?locale=en_US'
43
    		],
44
    		"twitter" => [
45
    			"label" => "Twitter",
46
    			"regex" => [
47
    				"follower" => '/\/followers".*?<div.*?>(.*?)<\/div>/is'
48
    			],
49
    		],
50
    		"instagram" => [
51
    			"label" => "Instagram",
52
    			"regex" => [
53
    				"follower" => '/edge_followed_by.*?"count":(.*?)\}/is'
54
    			],
55
    		],
56
    		/*"linkedin" => [
57
    			"label" => "LinkedIn",
58
    			"regex" => "",
59
    		],*/
60
    		"pinterest" => [
61
    			"label" => "Pinterest",
62
    			"regex" => [
63
    				"follower" => '/pinterestapp:followers.*?content="(.*?)"/is'
64
    			],
65
    		],
66
    		"youtube" => [
67
    			"label" => "Youtube",
68
    			"regex" => [
69
    				"follower" => '/aria-label=.*?subscribers.*?>(.*?)</is'
70
    			],
71
    		],
72
    	];
73
 
74
    	$this->set('pageScriptPath', $this->pageScriptPath);
75
    	$this->set( 'serviceList', $this->serviceList );
76
    	$this->set( 'pageNo', $_REQUEST['pageno']);
77
 
78
		$this->colList = array(
79
			'url' => $_SESSION['text']['common']['Url'],
80
			'followers' => $_SESSION['text']['label']['Followers'],
81
			'likes' => $_SESSION['text']['label']['Likes'],
82
		);
83
 
84
    	parent::__construct();
85
    }
86
 
87
    function showSocialMediaLinks($searchInfo = '') {
88
    	$userId = isLoggedIn();
89
    	$this->set('searchInfo', $searchInfo);
90
    	$sql = "select l.*, w.name as website_name from $this->linkTable l, websites w where l.website_id=w.id";
91
 
92
    	if (!isAdmin()) {
93
    	    $sql .= " and w.user_id=$userId";
94
    	}
95
 
96
    	// search conditions
97
    	$sql .= !empty($searchInfo['name']) ? " and l.name like '%".addslashes($searchInfo['name'])."%'" : "";
98
    	$sql .= !empty($searchInfo['website_id']) ? " and l.website_id=".intval($searchInfo['website_id']) : "";
99
    	$sql .= !empty($searchInfo['type']) ? " and `type`='".addslashes($searchInfo['type'])."'" : "";
100
 
101
    	if (!empty($searchInfo['status'])) {
102
    	    $sql .= ($searchInfo['status'] == 'active') ? " and l.status=1" : " and l.status=0";
103
    	}
104
 
105
    	$webSiteCtrler = new WebsiteController();
106
    	$websiteList = $webSiteCtrler->__getAllWebsites($userId, true);
107
    	$this->set( 'websiteList', $websiteList );
108
 
109
    	// pagination setup
110
    	$this->db->query( $sql, true );
111
    	$this->paging->setDivClass( 'pagingdiv' );
112
    	$this->paging->loadPaging( $this->db->noRows, SP_PAGINGNO );
113
    	$pagingDiv = $this->paging->printPages( $this->pageScriptPath, 'searchForm', 'scriptDoLoadPost', 'content', '' );
114
    	$this->set( 'pagingDiv', $pagingDiv );
115
    	$sql .= " limit " . $this->paging->start . "," . $this->paging->per_page;
116
 
117
    	$linkList = $this->db->select( $sql );
118
    	$this->set( 'list', $linkList );
119
    	$this->render( 'socialmedia/show_social_media_links');
120
    }
121
 
122
    function __checkName($name, $websiteId, $linkId = false){
123
        $whereCond = "name='".addslashes($name)."'";
124
        $whereCond .= " and website_id='".intval($websiteId)."'";
125
        $whereCond .= !empty($linkId) ? " and id!=".intval($linkId) : "";
126
        $listInfo = $this->dbHelper->getRow($this->linkTable, $whereCond);
127
        return empty($listInfo['id']) ? false :  $listInfo['id'];
128
    }
129
 
130
    function __checkUrl($url, $websiteId, $linkId = false){
131
        $whereCond = "url='".addslashes($url)."'";
132
        $whereCond .= " and website_id=".intval($websiteId);
133
        $whereCond .= !empty($linkId) ? " and id!=".intval($linkId) : "";
134
        $listInfo = $this->dbHelper->getRow($this->linkTable, $whereCond);
135
        return empty($listInfo['id']) ? false :  $listInfo['id'];
136
    }
137
 
138
    function validateSocialMediaLink($listInfo) {
139
        $errMsg = [];
140
        $errMsg['name'] = formatErrorMsg($this->validate->checkBlank($listInfo['name']));
141
        $errMsg['url'] = formatErrorMsg($this->validate->checkBlank($listInfo['url']));
142
        $errMsg['website_id'] = formatErrorMsg($this->validate->checkBlank($listInfo['website_id']));
143
        $errMsg['type'] = formatErrorMsg($this->validate->checkBlank($listInfo['type']));
144
 
145
        if(!$this->validate->flagErr){
146
            if ($this->__checkName($listInfo['name'], $listInfo['website_id'], $listInfo['id'])) {
147
                $errMsg['name'] = formatErrorMsg($_SESSION['text']['label']['already exist']);
148
                $this->validate->flagErr = true;
149
            }
150
        }
151
 
152
        if(!$this->validate->flagErr){
153
            if ($this->__checkUrl($listInfo['url'], $listInfo['website_id'], $listInfo['id'])) {
154
                $errMsg['url'] = formatErrorMsg($_SESSION['text']['label']['already exist']);
155
                $this->validate->flagErr = true;
156
            }
157
        }
158
 
159
        if(!$this->validate->flagErr){
160
            if (!stristr($listInfo['url'], $listInfo['type'])) {
161
                $errMsg['url'] = formatErrorMsg($_SESSION['text']['common']["Invalid value"]);
162
                $this->validate->flagErr = true;
163
            }
164
        }
165
 
166
        // Validate link count
167
        if(!$this->validate->flagErr){
168
            $websiteCtrl = new WebsiteController();
169
            $websiteInfo = $websiteCtrl->__getWebsiteInfo($listInfo['website_id']);
170
            $newCount = !empty($listInfo['id']) ? 0 : 1;
171
            if (! $this->validateSocialMediaLinkCount($websiteInfo['user_id'], $newCount)) {
172
                $this->set('validationMsg', $this->spTextSMC['Your social media link count already reached the limit']);
173
                $this->validate->flagErr = true;
174
            }
175
        }
176
 
177
        return $errMsg;
178
    }
179
 
180
    // Function to check / validate the user type social media count
181
    function validateSocialMediaLinkCount($userId, $newCount = 1) {
182
        $userCtrler = new UserController();
183
 
184
        // if admin user id return true
185
        if ($userCtrler->isAdminUserId($userId)) {
186
            return true;
187
        }
188
 
189
        $userTypeCtrlr = new UserTypeController();
190
        $userTypeDetails = $userTypeCtrlr->getUserTypeSpecByUser($userId);
191
 
192
        $whereCond = "l.website_id=w.id and w.user_id=".intval($userId);
193
        $existingInfo = $this->dbHelper->getRow("$this->linkTable l, websites w", $whereCond, "count(*) count");
194
        $userSMLinkCount = $existingInfo['count'];
195
        $userSMLinkCount += $newCount;
196
 
197
        // if limit is set and not -1
198
        if (isset($userTypeDetails['social_media_link_count']) && $userTypeDetails['social_media_link_count'] >= 0) {
199
 
200
            // check whether count greater than limit
201
            if ($userSMLinkCount <= $userTypeDetails['social_media_link_count']) {
202
                return true;
203
            } else {
204
                return false;
205
            }
206
 
207
        } else {
208
            return true;
209
        }
210
 
211
    }
212
 
213
    function newSocialMediaLink($info = '') {
214
        $userId = isLoggedIn();
215
        $this->set('post', $info);
216
        $webSiteCtrler = new WebsiteController();
217
        $websiteList = $webSiteCtrler->__getAllWebsites($userId, true);
218
        $this->set( 'websiteList', $websiteList );
219
        $this->set('editAction', 'createSocialMediaLink');
220
        $this->render( 'socialmedia/edit_social_media_link');
221
    }
222
 
223
    function createSocialMediaLink($listInfo = '') {
224
 
225
        $errMsg = $this->validateSocialMediaLink($listInfo);
226
 
227
        // if no error occured
228
        if (!$this->validate->flagErr) {
229
            $dataList = [
230
                'name' => $listInfo['name'],
231
                'url' => addHttpToUrl($listInfo['url']),
232
                'type' => $listInfo['type'],
233
                'website_id|int' => $listInfo['website_id'],
234
            ];
235
            $this->dbHelper->insertRow($this->linkTable, $dataList);
236
            $this->showSocialMediaLinks(['name' => $listInfo['name']]);
237
            exit;
238
        }
239
 
240
        $this->set('errMsg', $errMsg);
241
        $this->newSocialMediaLink($listInfo);
242
 
243
    }
244
 
245
    function editSocialMediaLink($linkId, $listInfo = '') {
246
 
247
        if (!empty($linkId)) {
248
            $userId = isLoggedIn();
249
            $webSiteCtrler = new WebsiteController();
250
            $websiteList = $webSiteCtrler->__getAllWebsites($userId, true);
251
            $this->set( 'websiteList', $websiteList );
252
 
253
            if(empty($listInfo)){
254
                $listInfo = $this->__getSocialMediaLinkInfo($linkId);
255
            }
256
 
257
            $this->set('post', $listInfo);
258
            $this->set('editAction', 'updateSocialMediaLink');
259
            $this->render( 'socialmedia/edit_social_media_link');
260
        }
261
 
262
    }
263
 
264
    function updateSocialMediaLink($listInfo) {
265
        $this->set('post', $listInfo);
266
        $errMsg = $this->validateSocialMediaLink($listInfo);
267
 
268
        if (!$this->validate->flagErr) {
269
            $dataList = [
270
                'name' => $listInfo['name'],
271
                'url' => addHttpToUrl($listInfo['url']),
272
                'type' => $listInfo['type'],
273
                'website_id|int' => $listInfo['website_id'],
274
            ];
275
            $this->dbHelper->updateRow($this->linkTable, $dataList, "id=".intval($listInfo['id']));
276
            $this->showSocialMediaLinks(['name' => $listInfo['name']]);
277
            exit;
278
        }
279
 
280
        $this->set('errMsg', $errMsg);
281
        $this->editSocialMediaLink($listInfo['id'], $listInfo);
282
    }
283
 
284
    function deleteSocialMediaLink($linkId) {
285
        $this->dbHelper->deleteRows($this->linkTable, "id=" . intval($linkId));
286
        $this->showSocialMediaLinks();
287
    }
288
 
289
    function __changeStatus($linkId, $status){
290
        $linkId = intval($linkId);
291
        $this->dbHelper->updateRow($this->linkTable, ['status|int' => $status], "id=$linkId");
292
    }
293
 
294
    function __getSocialMediaLinkInfo($linkId) {
295
        $whereCond = "id=".intval($linkId);
296
        $info = $this->dbHelper->getRow($this->linkTable, $whereCond);
297
        return $info;
298
    }
299
 
300
    function verifyActionAllowed($linkId) {
301
        $allowed = true;
302
 
303
        // if not admin, check the permissions
304
        if (!isAdmin()) {
305
            $userId = isLoggedIn();
306
            $linkInfo = $this->__getSocialMediaLinkInfo($linkId);
307
            $webSiteCtrler = new WebsiteController();
308
            $webSiteInfo = $webSiteCtrler->__getWebsiteInfo($linkInfo['website_id']);
309
            $allowed = ($userId == $webSiteInfo['user_id']) ? true : false;
310
        }
311
 
312
        if (!$allowed) {
313
            showErrorMsg($_SESSION['text']['label']['Access denied']);
314
        }
315
 
316
    }
317
 
318
	function viewQuickChecker($info='') {
319
		$this->render('socialmedia/quick_checker');
320
	}
321
 
322
	function doQuickChecker($listInfo = '') {
323
 
324
		if (!stristr($listInfo['url'], $listInfo['type'])) {
325
			$errorMsg = formatErrorMsg($_SESSION['text']['common']["Invalid value"]);
326
			$this->validate->flagErr = true;
327
		}
328
 
329
		// if no error occured find social media details
330
		if (!$this->validate->flagErr) {
331
			$smLink = addHttpToUrl($listInfo['url']);
332
			$result = $this->getSocialMediaDetails($listInfo['type'], $smLink);
333
 
334
			// if call is success
335
			if ($result['status']) {
336
				$this->set('smType', $listInfo['type']);
337
				$this->set('smLink', $smLink);
338
				$this->set('statInfo', $result);
339
				$this->render('socialmedia/quick_checker_results');
340
				exit;
341
			} else {
342
				$errorMsg = $result['msg'];
343
			}
344
 
345
		}
346
 
347
		$errorMsg = !empty($errorMsg) ? $errorMsg : $_SESSION['text']['common']['Internal error occured'];
348
		showErrorMsg($errorMsg);
349
 
350
	}
351
 
352
	function getSocialMediaDetails($smType, $smLink) {
353
		$result = ['status' => 0, 'likes' => 0, 'followers' => 0, 'msg' => $_SESSION['text']['common']['Internal error occured']];
354
		$smInfo = $this->serviceList[$smType];
355
 
356
		if (!empty($smInfo) && !empty($smLink)) {
357
 
358
			// if params needs to be added with url
359
			if (!empty($smInfo['url_part'])) {
360
				$smLink .= stristr($smLink, '?') ? str_replace("?", "&", $smInfo['url_part']) : $smInfo['url_part'];
361
			}
362
 
363
			$smContentInfo = $this->spider->getContent($smLink);
364
 
365
			if (!empty($smContentInfo['page'])) {
366
			    $matches = [];
367
 
368
				// find likes
369
				if (!empty($smInfo['regex']['like'])) {
370
					preg_match($smInfo['regex']['like'], $smContentInfo['page'], $matches);
371
 
372
					if (!empty($matches[1])) {
373
						$result['status'] = 1;
374
						$result['likes'] = formatNumber($matches[1]);
375
					}
376
 
377
				}
378
 
379
				// find followers
380
				if (!empty($smInfo['regex']['follower'])) {
381
					preg_match($smInfo['regex']['follower'], $smContentInfo['page'], $matches);
382
 
383
					if (!empty($matches[1])) {
384
						$result['status'] = 1;
385
						$result['followers'] = formatNumber($matches[1]);
386
					}
387
 
388
				}
389
 
390
			} else {
391
				$result['msg'] = $smContentInfo['errmsg'];
392
			}
393
 
394
		}
395
 
396
		return $result;
397
 
398
	}
399
 
400
	/*
401
	 * function to get all links with out reports for a day
402
	 */
403
	function getAllLinksWithOutReports($websiteId, $date) {
404
		$websiteId = intval($websiteId);
405
		$date = addslashes($date);
406
		$sql = "select link.*, lr.id result_id from social_media_links link left join
407
			social_media_link_results lr on (link.id=lr.sm_link_id and lr.report_date='$date')
408
			where link.status=1 and link.website_id=$websiteId and lr.id is NULL";
409
 
410
		$linkList = $this->db->select($sql);
411
		return $linkList;
412
 
413
	}
414
 
415
	function saveSocialMediaLinkResults($linkId, $linkInfo) {
416
		$dataList = [
417
			'sm_link_id|int' => $linkId,
418
			'likes|int' => $linkInfo['likes'],
419
			'followers|int' => $linkInfo['followers'],
420
			'report_date' => date('Y-m-d'),
421
		];
422
 
423
		$this->dbHelper->insertRow($this->linkReportTable, $dataList);
424
	}
425
 
426
	/*
427
	 * func to show report summary
428
	 */
429
	function viewReportSummary($searchInfo = '', $summaryPage = false, $cronUserId=false) {
430
 
431
		$userId = !empty($cronUserId) ? $cronUserId : isLoggedIn();
432
		$this->set('summaryPage', $summaryPage);
433
		$this->set('searchInfo', $searchInfo);
434
		$this->set('cronUserId', $cronUserId);
435
 
436
		$exportVersion = false;
437
		switch($searchInfo['doc_type']){
438
 
439
			case "export":
440
				$exportVersion = true;
441
				$exportContent = "";
442
				break;
443
 
444
			case "pdf":
445
				$this->set('pdfVersion', true);
446
				break;
447
 
448
			case "print":
449
				$this->set('printVersion', true);
450
				break;
451
		}
452
 
453
		$fromTime = !empty($searchInfo['from_time']) ? addslashes($searchInfo['from_time']) : date('Y-m-d', strtotime('-1 days'));
454
		$toTime = !empty($searchInfo['to_time']) ? addslashes($searchInfo['to_time']) : date('Y-m-d');
455
		$this->set('fromTime', $fromTime);
456
		$this->set('toTime', $toTime);
457
 
458
		$websiteController = New WebsiteController();
459
		$wList = $websiteController->__getAllWebsites($userId, true);
460
		$websiteList = [];
461
		foreach ($wList as $wInfo) $websiteList[$wInfo['id']] = $wInfo;
462
		$websiteList = count($websiteList) ? $websiteList : array(0);
463
		$this->set('websiteList', $websiteList);
464
		$websiteId = intval($searchInfo['website_id']);
465
		$this->set('websiteId', $websiteId);
466
 
467
		// to find order col
468
		if (!empty($searchInfo['order_col'])) {
469
			$orderCol = $searchInfo['order_col'];
470
			$orderVal = getOrderByVal($searchInfo['order_val']);
471
		} else {
472
			$orderCol = "followers";
473
			$orderVal = 'DESC';
474
		}
475
 
476
		$this->set('orderCol', $orderCol);
477
		$this->set('orderVal', $orderVal);
478
		$scriptName = $summaryPage ? "archive.php" : $this->pageScriptPath;
479
		$scriptPath = SP_WEBPATH . "/$scriptName?sec=reportSummary&website_id=$websiteId";
480
		$scriptPath .= "&from_time=$fromTime&to_time=$toTime&search_name=" . $searchInfo['search_name'] . "&type=" . $searchInfo['type'];
481
		$scriptPath .= "&order_col=$orderCol&order_val=$orderVal&report_type=social-media-reports";
482
 
483
		// set website id to get exact keywords of a user
484
		if (!empty($websiteId)) {
485
			$conditions = " and sml.website_id=$websiteId";
486
		} else {
487
			$conditions = " and sml.website_id in (".implode(',', array_keys($websiteList)).")";
488
		}
489
 
490
		$conditions .= !empty($searchInfo['search_name']) ? " and sml.url like '%".addslashes($searchInfo['search_name'])."%'" : "";
491
		$conditions .= !empty($searchInfo['type']) ? " and sml.type='".addslashes($searchInfo['type'])."'" : "";
492
 
493
		$subSql = "select [cols] from $this->linkTable sml, $this->linkReportTable r where sml.id=r.sm_link_id
494
		and sml.status=1 $conditions and r.report_date='$toTime'";
495
 
496
		$sql = "
497
		(" . str_replace("[cols]", "sml.id,sml.url,sml.website_id,sml.type,r.likes,r.followers", $subSql) . ")
498
			UNION
499
			(select sml.id,sml.url,sml.website_id,sml.type,0,0 from $this->linkTable sml where sml.status=1 $conditions
500
			and sml.id not in (". str_replace("[cols]", "distinct(sml.id)", $subSql) ."))
501
		order by " . addslashes($orderCol) . " " . addslashes($orderVal);
502
 
503
		if ($orderCol != 'url') $sql .= ", url";
504
 
505
		// pagination setup, if not from cron job email send function, pdf and export action
506
		if (!in_array($searchInfo['doc_type'], array("pdf", "export"))) {
507
			$this->db->query($sql, true);
508
			$this->paging->setDivClass('pagingdiv');
509
			$this->paging->loadPaging($this->db->noRows, SP_PAGINGNO);
510
			$pagingDiv = $this->paging->printPages($scriptPath, '', 'scriptDoLoad', 'content', "");
511
			$this->set('pagingDiv', $pagingDiv);
512
			$this->set('pageNo', $searchInfo['pageno']);
513
			$sql .= " limit ".$this->paging->start .",". $this->paging->per_page;
514
		}
515
 
516
		# set report list
517
		$baseReportList = $this->db->select($sql);
518
		$this->set('baseReportList', $baseReportList);
519
		$this->set('colList', $this->colList);
520
 
521
		// if keywords existing
522
		if (!empty($baseReportList)) {
523
 
524
			$keywordIdList = array();
525
			foreach ($baseReportList as $info) {
526
				$keywordIdList[] = $info['id'];
527
			}
528
 
529
			$sql = "select sml.id,sml.url,sml.website_id,sml.type,r.followers,r.likes
530
			from $this->linkTable sml, $this->linkReportTable r where sml.id=r.sm_link_id
531
			and sml.status=1 $conditions and r.report_date='$fromTime'";
532
			$sql .= " and sml.id in(" . implode(",", $keywordIdList) . ")";
533
			$reportList = $this->db->select($sql);
534
			$compareReportList = array();
535
 
536
			foreach ($reportList as $info) {
537
				$compareReportList[$info['id']] = $info;
538
			}
539
 
540
			$this->set('compareReportList', $compareReportList);
541
 
542
		}
543
 
544
		if ($exportVersion) {
545
			$spText = $_SESSION['text'];
546
			$reportHeading =  $this->spTextTools['Social Media Report Summary']."($fromTime - $toTime)";
547
			$exportContent .= createExportContent( array('', $reportHeading, ''));
548
			$exportContent .= createExportContent( array());
549
			$headList = array($spText['common']['Website'], $spText['common']['Url']);
550
 
551
			$pTxt = str_replace("-", "/", substr($fromTime, -5));
552
			$cTxt = str_replace("-", "/", substr($toTime, -5));
553
			foreach ($this->colList as $colKey => $colLabel) {
554
				if ($colKey == 'url') continue;
555
				$headList[] = $colLabel . "($pTxt)";
556
				$headList[] = $colLabel . "($cTxt)";
557
				$headList[] = $colLabel . "(+/-)";
558
			}
559
 
560
			$exportContent .= createExportContent($headList);
561
			foreach($baseReportList as $listInfo){
562
 
563
				$valueList = array($websiteList[$listInfo['website_id']]['url'], $listInfo['url']);
564
				foreach ($this->colList as $colName => $colVal) {
565
					if ($colName == 'url') continue;
566
 
567
					$currRank = isset($listInfo[$colName]) ? $listInfo[$colName] : 0;
568
					$prevRank = isset($compareReportList[$listInfo['id']][$colName]) ? $compareReportList[$listInfo['id']][$colName] : 0;
569
					$rankDiff = "";
570
 
571
					// if both ranks are existing
572
					if ($prevRank != '' && $currRank != '') {
573
						$rankDiff = $currRank - $prevRank;
574
					}
575
 
576
					$valueList[] = $prevRank;
577
					$valueList[] = $currRank;
578
					$valueList[] = $rankDiff;
579
				}
580
 
581
				$exportContent .= createExportContent( $valueList);
582
			}
583
 
584
			if ($summaryPage) {
585
				return $exportContent;
586
			} else {
587
				exportToCsv('social_media_report_summary', $exportContent);
588
			}
589
 
590
		} else {
591
 
592
			// if pdf export
593
			if ($summaryPage) {
594
				return $this->getViewContent('socialmedia/social_media_report_summary');
595
			} else {
596
				// if pdf export
597
				if ($searchInfo['doc_type'] == "pdf") {
598
					exportToPdf($this->getViewContent('socialmedia/social_media_report_summary'), "social_media_report_summary_$fromTime-$toTime.pdf");
599
				} else {
600
					$this->set('searchInfo', $searchInfo);
601
					$this->render('socialmedia/social_media_report_summary');
602
				}
603
			}
604
 
605
		}
606
	}
607
 
608
	function __getSocialMediaLinks($whereCond = false) {
609
	    $linkList = $this->dbHelper->getAllRows($this->linkTable, $whereCond);
610
	    return !empty($linkList) ? $linkList : false;
611
	}
612
 
613
	// func to show detailed reports
614
	function viewDetailedReports($searchInfo = '') {
615
 
616
		$userId = isLoggedIn();
617
 
618
		if (!empty ($searchInfo['from_time'])) {
619
			$fromTimeDate = addslashes($searchInfo['from_time']);
620
		} else {
621
			$fromTimeDate = date('Y-m-d', strtotime('-15 days'));
622
		}
623
 
624
		if (!empty ($searchInfo['to_time'])) {
625
			$toTimeDate = addslashes($searchInfo['to_time']);
626
		} else {
627
			$toTimeDate = date('Y-m-d');
628
		}
629
 
630
		$this->set('fromTime', $fromTimeDate);
631
		$this->set('toTime', $toTimeDate);
632
 
633
	    if(!empty($searchInfo['link_id']) && !empty($searchInfo['rep'])){
634
			$searchInfo['link_id'] = intval($searchInfo['link_id']);
635
			$linkInfo = $this->__getSocialMediaLinkInfo($searchInfo['link_id']);
636
			$searchInfo['website_id'] = $linkInfo['website_id'];
637
		}
638
 
639
		$websiteController = New WebsiteController();
640
		$websiteList = $websiteController->__getAllWebsites($userId, true);
641
		$this->set('websiteList', $websiteList);
642
		$websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
643
		$this->set('websiteId', $websiteId);
644
 
645
		$linkList = $this->__getSocialMediaLinks("website_id=$websiteId and status=1 order by name");
646
		$this->set('linkList', $linkList);
647
		$linkId = empty($searchInfo['link_id']) ? $linkList[0]['id'] : intval($searchInfo['link_id']);
648
		$this->set('linkId', $linkId);
649
 
650
		$list = [];
651
		if (!empty($linkId)) {
652
 
653
    		$sql = "select s.* from $this->linkReportTable s
654
    		where report_date>='$fromTimeDate' and report_date<='$toTimeDate' and s.sm_link_id=$linkId
655
    		order by s.report_date";
656
    		$reportList = $this->db->select($sql);
657
 
658
    		$colList = array_keys($this->colList);
659
    		array_shift($colList);
660
    		foreach ($colList as $col) $prevRank[$col] = 0;
661
 
662
    		# loop through rank
663
    		foreach ($reportList as $key => $repInfo) {
664
 
665
    			// if not the first row, find differences in rank
666
    			if ($key)  {
667
 
668
    				foreach ($colList as $col) $rankDiff[$col] = '';
669
 
670
    				foreach ($colList as $col) {
671
    					$rankDiff[$col] = round($repInfo[$col] - $prevRank[$col], 2);
672
    					if (empty($rankDiff[$col])) continue;
673
 
674
    					if ($col == "average_position" ) $rankDiff[$col] = $rankDiff[$col] * -1;
675
    					$rankClass = ($rankDiff[$col] > 0) ? 'green' : 'red';
676
 
677
    					$rankDiff[$col] = "<font class='$rankClass'>($rankDiff[$col])</font>";
678
    					$reportList[$key]['rank_diff_'.$col] = empty($rankDiff[$col]) ? '' : $rankDiff[$col];
679
    				}
680
 
681
    			}
682
 
683
    			foreach ($colList as $col) $prevRank[$col] = $repInfo[$col];
684
 
685
    		}
686
 
687
    		$list = array_reverse($reportList, true);
688
		}
689
 
690
		$this->set('list', $list);
691
		$this->render('socialmedia/social_media_reports');
692
 
693
	}
694
 
695
	// func to show social media link select box
696
	function showSocialMediaLinkSelectBox($websiteId, $linkId = ""){
697
	    $websiteId = intval($websiteId);
698
	    $this->set('linkList', $this->__getSocialMediaLinks("website_id=$websiteId and status=1 order by name"));
699
	    $this->set('linkId', $linkId);
700
	    $this->render('socialmedia/social_media_link_select_box');
701
	}
702
 
703
	// func to show link search reports in graph
704
	function viewGraphReports($searchInfo = '') {
705
 
706
	    $userId = isLoggedIn();
707
 
708
	    if (!empty ($searchInfo['from_time'])) {
709
	        $fromTimeDate = addslashes($searchInfo['from_time']);
710
	    } else {
711
	        $fromTimeDate = date('Y-m-d', strtotime('-15 days'));
712
	    }
713
 
714
	    if (!empty ($searchInfo['to_time'])) {
715
	        $toTimeDate = addslashes($searchInfo['to_time']);
716
	    } else {
717
	        $toTimeDate = date('Y-m-d');
718
	    }
719
 
720
	    $this->set('fromTime', $fromTimeDate);
721
	    $this->set('toTime', $toTimeDate);
722
 
723
	    if(!empty($searchInfo['link_id']) && !empty($searchInfo['rep'])){
724
	        $searchInfo['link_id'] = intval($searchInfo['link_id']);
725
	        $linkInfo = $this->__getSocialMediaLinkInfo($searchInfo['link_id']);
726
	        $searchInfo['website_id'] = $linkInfo['website_id'];
727
	    }
728
 
729
	    $websiteController = New WebsiteController();
730
	    $websiteList = $websiteController->__getAllWebsites($userId, true);
731
	    $this->set('websiteList', $websiteList);
732
	    $websiteId = empty ($searchInfo['website_id']) ? $websiteList[0]['id'] : intval($searchInfo['website_id']);
733
	    $this->set('websiteId', $websiteId);
734
 
735
	    $linkList = $this->__getSocialMediaLinks("website_id=$websiteId and status=1 order by name");
736
	    $this->set('linkList', $linkList);
737
	    $linkId = empty($searchInfo['link_id']) ? $linkList[0]['id'] : intval($searchInfo['link_id']);
738
	    $this->set('linkId', $linkId);
739
 
740
	    // if reports not empty
741
	    $colList = $this->colList;
742
	    array_shift($colList);
743
	    $this->set('colList', $colList);
744
	    $this->set('searchInfo', $searchInfo);
745
 
746
	    $graphContent = showErrorMsg($_SESSION['text']['common']['No Records Found'], false, true);
747
	    if (!empty($linkId)) {
748
 
749
	        $sql = "select s.* from $this->linkReportTable s
750
    		where report_date>='$fromTimeDate' and report_date<='$toTimeDate'  and s.sm_link_id=$linkId
751
    		order by s.report_date";
752
	        $reportList = $this->db->select($sql);
753
 
754
    		$graphColList = array();
755
    		if (!empty($searchInfo['attr_type'])) {
756
    			$graphColList[$searchInfo['attr_type']] = $colList[$searchInfo['attr_type']];
757
    		} else {
758
    			//array_pop($colList);
759
    			$graphColList = $colList;
760
    		}
761
 
762
    		if (!empty($reportList)) {
763
 
764
    			$dataArr = "['Date', '" . implode("', '", array_values($graphColList)) . "']";
765
 
766
    			// loop through data list
767
    			foreach ($reportList as $dataInfo) {
768
 
769
    				$valStr = "";
770
    				foreach ($graphColList as $seId => $seVal) {
771
    					$valStr .= ", ";
772
    					$valStr .= !empty($dataInfo[$seId]) ? $dataInfo[$seId] : 0;
773
    				}
774
 
775
    				$dataArr .= ", ['{$dataInfo['report_date']}' $valStr]";
776
    			}
777
 
778
    			$this->set('dataArr', $dataArr);
779
    			$this->set('graphTitle', $this->spTextTools['Graphical Reports']);
780
    			$graphContent = $this->getViewContent('report/graph');
781
    		} else {
782
    			$graphContent = showErrorMsg($_SESSION['text']['common']['No Records Found'], false, true);
783
    		}
784
 
785
	    }
786
 
787
		// get graph content
788
		$this->set('graphContent', $graphContent);
789
		$this->render('socialmedia/graphicalreport');
790
 
791
	}
792
 
793
}
794
?>