3tl.tabbuilder /editor/functions.php

Language PHP Lines 782
MD5 Hash bd8a8ceb3f66d506dcf10f5730fd51f3 Estimated Cost $11,955 (why?)
Repository https://bitbucket.org/3tierlogic/3tl.tabbuilder.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
<?php

	session_start();


	//------------------- GLOBAL CONSTANTS ------------------//

	// uploaded files directory
	define("DIR_UPLOADS", "uploads/");
	// editor file name
	define("EDITOR", "editor.php");
	// website url, where the editor is
	define("DEV_WEBSITE_URL", "http://platform.3tierlogic.com/tabbuilder1_3/editor/");
	// max size of the uploaded files, currently - 1Mb
	define("MAX_FILE_SIZE", 1024 * 1024 * 1 );
	// users with these ids are admins (get ids from the users table)
	$arrayAdmins = array( 1, 2 ); // don't forget to remove "2"
	// tabs per pager limit
	define("TABS_PER_PAGE", 10 );
	// apps id/secret
	$app_details = array(
		array( '379739182116899', 'dfa4432ebba89adab0c058ebd9643668' ),
		array( '192358084235512', '16b3f9fe38467433aabc5d8abc0e39f5' ),
		array( '265487816910972', '040bac342203d77cb3358ec1f208e9f7' ),
		array( '522527257771475', '3bfd2f8cd4acaaaa52f10ebbf4accb31' ),
		array( '448855071830201', 'ad12a90e0db5825609367a3f9897935b' ),

		array( '278867175575177', '1ec16b5a75f92387e6c5eef1b781ecc9' ),
		array( '305258642910575', 'dbc1d25a1e2a41f9b6e76d2d0dc29b42' ),
		array( '470866732978919', '04dd8f6a3c3a2bed54be14632d0eb74c' ),
		array( '522825104424666', 'fffb9111d88a55765515aab5f1a28c5d' ),
		array( '208927432578401', '9cd6e62925586c5a3298f9d14aaafa24' )
	);



	//------------------------ FUNCTIONS ------------------------//


	# REDIRECT UNAUTHORIZED USERS TO THE HOMEPAGE
	function ars_is_user_authorized() {
		if ( ! $_SESSION['user_info'] ) header( 'Location: index.php' );
	}

	# Check whether the current user has full access
	function ars_is_user_superuser() {
		if ( isset($_SESSION['superaccount'])) {
			return $_SESSION['superaccount'];
		} else {
			return false;
		}
	}


	# SAVE INFORMATION ABOUT NEW USERS
	function ars_save_new_user_info( $user ) {
		$query = "SELECT * FROM users WHERE fb_id = '" . $user['id'] . "' ";
		$query = mysql_query( $query ) or exit( mysql_error() );
		// if we have no records about the user, add it
		if ( mysql_num_rows( $query ) == 0 ) {
			$query = mysql_query("INSERT INTO users VALUES ( 0,
															'".TABS_PER_PAGE."',
															'1',
															'".$user['id']."',
															'".$user['name']."',
															'".$user['first_name']."',
															'".$user['last_name']."',
															'".$user['link']."',
															'".$user['username']."',
															'".$user['hometown']['name']."',
															'".$user['location']['name']."',
															'".$user['gender']."',
															'".$user['email']."',
															'".$user['timezone']."',
															'".$user['locale']."',
															'".$user['verified']."',
															'".$user['updated_time']."'
															);") or exit( mysql_error() );
		}
	} // ars_save_new_user_info() end




	# CHECK IF CURRENT USER IS WEBSITE ADMIN
	function ars_is_admin( $fb_id ) {
		global $arrayAdmins;
		$userIsAdmin = false;
		$query = "SELECT id FROM users WHERE fb_id = '".$fb_id."' ";
		$query = mysql_query( $query ) or exit( mysql_error() );
		$user = mysql_fetch_assoc( $query );
		for ( $i = 0; $i < count($arrayAdmins); $i++ ) {
			if ( $user['id'] == $arrayAdmins[$i] ) {
				$userIsAdmin = true;
				break;
			}
		}
		return $userIsAdmin;
	}




	# CHECK IF EDITED PAGE BELONGS TO THE USER
	function ars_is_it_my_page( $pageId, $userId ) {
		$result = false;
		// is user website admin?
		if ( ars_is_admin( $userId ) )
			$result = true;
		// has user fb admin rights for current tab?
		else {
			$user_pages = $_SESSION['user_pages'];
			for ( $i = 0; $i < count($user_pages); $i++ ) {
				$query = "SELECT * FROM pages WHERE fan_page_id = '".$user_pages[$i]['id']."' ";
				$query = mysql_query( $query ) or exit( mysql_error() );
				if ( mysql_num_rows( $query ) > 0 ) {
					while ( $tab = mysql_fetch_assoc( $query ) ) {
						if ( $tab['id'] == $pageId ) {
							$result = true;
							break;
						}
					}
				} // endif
			} // endfor
		} // user has fb admin rights for current page
		if ( $result == false ) header( 'Location: dashboard.php' );
	} // ars_is_it_my_page() end




	# SHORTEN TAB NAME (EDITOR - PREVIEW)
	function shortName( $name, $chars = 10 ) {
		if ( strlen($name) > $chars ) {
			// search spaces among the first "$chars" symbols
			$cut = ( strpos( $str, ' ' ) !== false && strpos( $str, ' ' ) < $chars ? false : true );
			$name = wordwrap( $name, $chars, ';;', $cut );
			$name = explode( ';;', $name );
			$name = $name[0] . '...';
		}
		return $name;
	}




	# ESCAPE AGAINST SQL INJECTION
	function escapeStr( $str ) {
		return mysql_real_escape_string( trim($str) );
	}




	# PAGE INFO
	// if $pageID is undefined, function will return the page with the biggest id (latest added)
	function ars_getPageInfo( $pageID = '' ) {
		$where = $pageID == '' ? '' : "WHERE id = '".$pageID."' ";
		$query = "SELECT * FROM pages ".$where." ORDER BY id DESC LIMIT 1";
		$query = mysql_query( $query ) or exit( mysql_error() );
		$page = mysql_fetch_assoc( $query );
		return $page;
	}




	# GET PAGE NAME BY ID
	function ars_get_page_name_by_id( $id ) {
		$user_pages = $_SESSION['user_pages'];
		for ( $i = 0; $i < count($user_pages); $i++ ) {
			if ( $user_pages[$i]['id'] == $id ) $page_name = $user_pages[$i]['name'];
		}
		return $page_name;
	}




	# GET CONTEST DESCRIPTION BY CAMPAIGN ID
	function getContestDescription( $id ) {
		$query = "SELECT campaign_description FROM sp_campaign_info WHERE campaign_sid = '".$id."' LIMIT 1";
		$query = mysql_query( $query ) or exit( mysql_error() );
		return mysql_result( $query, 0 );
	}




	# REMOVE SPACES
	function removeSpaces( $str ) {
		return str_replace( ' ', '-', $str );
	}




	# CHECK UPLOADED FILE FOR ERRORS
	function ars_check_file( $inputName ) {

		$error = false;

		// check extension
		$allow = array( 'jpeg', 'jpg', 'png', 'gif' );
		$myExt = pathinfo( $_FILES[$inputName]['name'], PATHINFO_EXTENSION );
		if ( ! in_array( $myExt, $allow ) )
			$error = 'ERROR_Only jpg, png and gif files are allowed';

		// check size
		elseif ( $_FILES[$inputName]['size'] > MAX_FILE_SIZE )
			$error = 'ERROR_Max file size is ' . MAX_FILE_SIZE / 1024 / 1024 . ' Mb';

		return $error;

	} // ars_check_file()

	# AVAILABLE WIDGET INFO
	// if $pageID is undefined, function will return the page with the biggest id (latest added)
	function ars_getWidgetsInfo( $partnerID ) {
		$where = "WHERE partner_sid = '".$partnerID."' ";
		$query = "SELECT * FROM sp_partner_widgets ".$where." LIMIT 1";
		$query = mysql_query( $query ) or exit( mysql_error() );
		$widgets = mysql_fetch_assoc( $query );
		return $widgets;
	}


	# DECODE URL
	function ars_urldecode( $string ) {
		$string = str_replace( "%3C", "<", $string );
		$string = str_replace( "%3E", ">", $string );
		$string = str_replace( "%20", " ", $string );
		$string = str_replace( "%0A", " ", $string );
		$string = str_replace( "%0D", " ", $string );
		$string = str_replace( "%3D", "=", $string );
		$string = str_replace( "%27", "\'", $string );
		$string = str_replace( "%22", "\"", $string );
		$string = str_replace( "%3A", ":", $string );
		$string = str_replace( "%3B", ";", $string );
		$string = str_replace( "%2F", "/", $string );
		$string = str_replace( "%21", "!", $string );
		$string = str_replace( "%23", "#", $string );
		$string = str_replace( "%7B", "{", $string );
		$string = str_replace( "%7D", "}", $string );
		$string = str_replace( "%28", "(", $string );
		$string = str_replace( "%29", ")", $string );
		$string = str_replace( "%3F", "?", $string );
		$string = str_replace( "%2C", ",", $string );
		$string = str_replace( "%26", "&", $string );
		$string = str_replace( "%25", "%", $string );
		$string = str_replace( "%24", "$", $string );
		$string = str_replace( "%09", "\t", $string );
		return $string;
	}




	//------------------------- FACEBOOK ------------------------//


	# GET SECRET BY APP ID
	function ars_get_secret_by_app_id( $appId, $app_details ) {
		for ( $i = 0; $i < count($app_details); $i++ ) {
			if ( $app_details[$i][0] == $appId ) return $app_details[$i][1];
		}
	}




	# GET FREE APP ID FOR TAB INSTALLATION
	function ars_get_free_app_id( $pageId, $app_details ) {
		$appId;

		// get all used apps ids
		$query = "SELECT app_id FROM pages WHERE fan_page_id = '".$pageId."' ";
		$query = mysql_query( $query ) or exit( mysql_error() );

		// user has already created tabs...
		if ( mysql_num_rows( $query ) > 0 ) {
			// make array of all used apps
			$usedApps = array();
			while ( $app = mysql_fetch_assoc( $query ) ) {
				array_push( $usedApps, $app['app_id'] );
			}
			// make array of all existing apps
			$existingApps = array();
			for ( $i = 0; $i < count($app_details); $i++ ) {
				array_push( $existingApps, $app_details[$i][0] );
			}
			// comare arrays
			$freeApps = array_diff( $existingApps, $usedApps );
			$appId = array_shift( array_values($freeApps) );
		}
		// no result, return the first app id in array
		else {
			$appId = $app_details[0][0];
		}

		return $appId;
	} // ars_get_free_app_id() end




	########### DELETE PAGES AND / OR FILES ############

	/* arguments:
	* $id 							the id of the page (file) to delete
	* $rel							if = 'id', deletes itelf; if = 'parent', deletes all children elements
	* $whereSpec			additional conditions for delete operation
	*/

	function ars_delete( $id, $rel = 'id', $whereSpec = '' ) {
		// if can't delete, return false
		$result = false;
		$whereSpec = $whereSpec == '' ? '' : "AND ".$whereSpec;
		// delete files, if any
		$query = "SELECT name FROM pages WHERE ".$rel." = '".$id."' ".$whereSpec;
		$query = mysql_query( $query ) or exit( mysql_error() );
		if ( mysql_num_rows( $query ) > 0 ) {
			while ( $file = mysql_fetch_assoc( $query ) ) {
				$path = DIR_UPLOADS . $file['name'];
				if ( file_exists ( $path ) ) unlink ( DIR_UPLOADS . $file['name'] );
			}
		}
		// delete record(s) from db
		$query = "DELETE FROM pages WHERE ".$rel." = '".$id."' ".$whereSpec;
		$query = mysql_query( $query ) or exit( mysql_error() );
		if ( $query ) $result = true;
		return $result;
	} // ars_delete() end




	################## FILE UPLOAD ##################

	/* arguments:
	* $inputName 		the name of the file input, which is used for sending
	* $parentID			the id of the parent page
	* $type						the type (role) of the uploaded image
	*/

	function ars_uploadFile( $inputName, $parentID, $type, $fbUserId = 0 ) {

		$uploadedFileName = '';

		// file was sent?
		if ( $_FILES[$inputName]['size'] != 0 ) {

			// check for errors
			$error = ars_check_file( $inputName );
			if ( $error ) { return $error; exit(); }

			$filename = 				$_FILES[$inputName]['name'];
			$tmp_filename = 	$_FILES[$inputName]['tmp_name'];

			// if there're spaces in the file name, replace them by valid symbols
			$filename = str_replace( ' ', '-', $filename );

			// if there's a file with the same name, as our file has
			$newFilename = $parentID . '_' . $filename;
			$query = "SELECT id FROM pages WHERE name = '".$newFilename."' ";
			$query = mysql_query( $query ) or exit( mysql_error() );
			if ( mysql_num_rows( $query ) > 0 ) $newFilename = $parentID . '_' . mt_rand() . '_' . $filename;

			// ...upload the file
			if ( move_uploaded_file( $tmp_filename, DIR_UPLOADS . $newFilename ) )
				$uploadedFileName = $newFilename;
			else exit('Error when uploading the file');

			// if file was uploaded, record it in db
			if ( $uploadedFileName != '' ) {
				$query = mysql_query("INSERT INTO pages VALUES ( 0,
																'".$fbUserId."',
																'',
																'',
																'".$parentID."',
																'".$type."',
																'".$uploadedFileName."',
																'', '', '', '', '', '', '', '0', '0', '0', '0'
																);") or exit( mysql_error() );
			} // file was uploaded
		} // file was sent
		return $uploadedFileName;
	} // ars_uploadFile() end




	################## FILE UPDATE ##################

	/* arguments:
	* $inputName 		the name of the file input, which is used for sending
	* $id							the id of the image, which has to be updated
	*/

	function ars_updateFile( $inputName, $id ) {

		$uploadedFileName = '';

		// file was sent?
		if ( $_FILES[$inputName]['size'] != 0 ) {

			// check for errors
			$error = ars_check_file( $inputName );
			if ( $error ) { return $error; exit(); }

			$filename = 				$_FILES[$inputName]['name'];
			$tmp_filename = 	$_FILES[$inputName]['tmp_name'];

			// if there're spaces in the file name, replace them by valid symbols
			$filename = str_replace( ' ', '-', $filename );

			// get old name
			$query = "SELECT name FROM pages WHERE id = '".$id."' ";
			$query = mysql_query( $query ) or exit( mysql_error() );
			$oldFilename = mysql_result( $query, 0 );

			// delete old file
			$path = DIR_UPLOADS . $oldFilename;
			if ( file_exists ( $path ) ) unlink ( DIR_UPLOADS . $oldFilename );

			// create new file name
			$parentID = substr( $oldFilename, 0, strpos( $oldFilename, '_' ) );
			$newFilename = $parentID . '_' . $filename;

			// if there's a file with the same name, as our file has
			$query = "SELECT id FROM pages WHERE name = '" . $newFilename . "' ";
			$query = mysql_query( $query ) or exit( mysql_error() );
			if ( mysql_num_rows( $query ) > 0 ) $newFilename = $parentID . '_' . mt_rand() . '_' . $filename;

			// upload new file
			if ( move_uploaded_file( $tmp_filename, DIR_UPLOADS . $newFilename ) )
				$uploadedFileName = $newFilename;
			else exit('Error when uploading the file');

			// if file was uploaded, update the record in db
			if ( $uploadedFileName != '' ) {
				mysql_query("UPDATE pages SET
											name = '".$uploadedFileName."'
											WHERE id = '".$id."'
											") or exit( mysql_error() );
			} // file was uploaded
		} // file was sent
		return $uploadedFileName;
	} // ars_updateFile() end




	############## DELETE UNUSED FILES ###############

	/* arguments:
	* $pageId					the id of the page, which is to be ckecked for unused files
	*/

	function ars_deleteUnusedFiles( $pageId ) {

		// get content
		$query = "SELECT * FROM pages WHERE id='".$pageId."' LIMIT 1 ";
		$query = mysql_query( $query ) or exit( mysql_error() );
		$content = mysql_fetch_assoc( $query );
		$cNonFans = $content['content_nonfans'];
		$cFans = $content['content_fans'];
		$cContestFans = $content['content_contest_fans'];
		$cContestForm = $content['content_contest_form'];
		$cContestUGCForm = $content['content_contest_ugc_form'];
		$cContestUGCGallery = $content['content_contest_ugc_gallery'];
		$cContestThank = $content['content_contest_thank'];

		// get files to be ckecked
		$query = "SELECT name FROM pages WHERE parent_id = '".$pageId."' AND saved = '0' ";
		$query = mysql_query( $query ) or exit( mysql_error() );
		if ( mysql_num_rows( $query ) > 0 ) {

			while ( $file = mysql_fetch_assoc( $query ) ) {
				if ( ! strpos( $cNonFans, $file['name'] ) && ! strpos( $cFans, $file['name'] ) && ! strpos( $cContestFans, $file['name'] ) && ! strpos( $cContestForm, $file['name'] ) && ! strpos( $cContestUGCForm, $file['name'] ) && ! strpos( $cContestUGCGallery, $file['name'] ) && ! strpos( $cContestThank, $file['name'] ) ) {
					// delete file
					$path = DIR_UPLOADS . $file['name'];
					if ( file_exists ( $path ) ) unlink ( DIR_UPLOADS . $file['name'] );
					// delete record from db
					$query2 = "DELETE FROM pages WHERE name = '".$file['name']."' ";
					$query2 = mysql_query( $query2 ) or exit( mysql_error() );
				} // endif
			} // endwhile

		} // endif
	} // ars_deleteUnusedFiles() end




	############# DASHBOARD - SHOW PAGES ############

	function ars_show_user_pages( $pages, $currentPageId = 0 ) {

		if ( count($pages) > 0 ) :

			// choose only pages, which have tabs
			$pagesWithTabs = array();
			for ( $i = 0; $i < count($pages); $i++ ) {
				$query = "SELECT * FROM pages WHERE type = 'tab' AND fan_page_id = '".$pages[$i]['id']."' ";
				$query = mysql_query( $query ) or exit( mysql_error() );
				if ( mysql_num_rows( $query ) > 0 ) {
					array_push( $pagesWithTabs, array( $pages[$i]['id'], $pages[$i]['name'] ) );
				}
			}

			// if we have pages with tabs
			if ( count($pagesWithTabs) > 0 ) : ?>

				<div class="userPages">
					<ul>
						<li><a href="dashboard.php" <?php if ( ! $currentPageId ) echo 'class="active"'; ?>>All tabs</a></li>
						<?php for ( $i = 0; $i < count($pagesWithTabs); $i++ ) : ?>
							<li><a href="dashboard.php?id=<?php echo $pagesWithTabs[$i][0]; ?>"
								<?php if ( $currentPageId == $pagesWithTabs[$i][0] ) echo 'class="active"'; ?>>
								<?php echo $pagesWithTabs[$i][1]; ?></a>
							</li>
						<?php endfor; ?>
					</ul>
				</div><!-- / .userPages -->

			<?php else : echo "<p>No pages with tabs found</p>"; ?>
			<?php endif; ?>
		<?php else : echo "<p>You have no created pages on Facebook</p>"; ?>
		<?php endif;
	} // ars_show_user_pages() end




	# DASHBOARD - SHOW USER TABS (AND TABS, WHERE HE IS ADMIN)

	function ars_get_allowed_tabs( $pages, $id = 0, $searchWord = '' ) {
		$query = "";
		// show tabs only from the chosen page
		if ( $id ) {
			$query .= "SELECT * FROM pages WHERE type = 'tab' AND fan_page_id = '".$id."' ";
		}
		// show tabs that match to $searchWord
		elseif ( $searchWord ) {
			for ( $i = 0; $i < count($pages); $i++ ) {
				$query .= "SELECT * FROM pages WHERE type = 'tab' AND fan_page_id = '".$pages[$i]['id']."'
										AND LOWER(name) LIKE '%".$searchWord."%' ";
				if ( count($pages) - $i > 1 ) $query .= "UNION ";
			}
		}
		// show tabs from all pages
		else {
			for ( $i = 0; $i < count($pages); $i++ ) {
				$query .= "SELECT * FROM pages WHERE type = 'tab' AND fan_page_id = '".$pages[$i]['id']."' ";
				if ( count($pages) - $i > 1 ) $query .= "UNION ";
			}
		}
		$query = mysql_query( $query ) or exit( mysql_error() );
		return $query;
	}




	############ FILTER APPS FROM USER PAGES ##########

	function ars_filter_apps_from_pages( $arr ) {
		foreach ( $arr['data'] as $key => $value ) {
			if ( $arr['data'][$key]['category'] == 'Application' ) {
				unset( $arr['data'][$key] );
			}
		}
		// new array keys
		$arr = array_values( $arr );
		return $arr[0];
	}




	############### CREATE GRID IMAGES ##############

	// run this function once to create background images for grid widget
	function create_grid_images() {
		$gridSizeMin = 1;
		$gridSizeMax = 810;
		$gridPath = 'images/grid';
		// if no grid folder exist
		if ( ! is_dir($gridPath) ) {
			// create folder
			mkdir($gridPath);
			// create grid images
			for ( $i = $gridSizeMin; $i <= $gridSizeMax; $i++ ) {
				// create canvas
				$canvas = imagecreatetruecolor( $i, $i );
				imagesavealpha( $canvas, true );
				$transparentBgColor = imagecolorallocatealpha( $canvas, 0, 0, 0, 127 );
				imagefill( $canvas, 0, 0, $transparentBgColor );
				// create border color
				$gridColor = imagecolorallocate( $canvas, 153, 153, 153 ); // #999
				// draw left border
				imageline( $canvas, 0, 0, 0, $i - 1, $gridColor );
				// draw top border
				imageline( $canvas, 0, 0, $i - 1, 0, $gridColor );
				// save grid image
				$filePath = $gridPath . '/grid-' . $i . '.png';
				imagepng( $canvas, $filePath );
			} // endfor
		} // endif
	} // create_grid_images()




	################## UGC GALLERY #################

	// auxiliary function
	function getImgUgcSidAndCampaignSid( $name, $resultToReturn ) {
		$query = "SELECT * FROM sp_campaign_ugc WHERE ugc_photo_name = '".$name."' LIMIT 1";
		$query = mysql_query( $query ) or exit( mysql_error() );
		$query = mysql_fetch_assoc( $query );
		// return ugc_sid
		if ( $resultToReturn == 'img' )
			return $query['ugc_sid'];
		// return ugc_campaign_sid
		else // ( $resultToReturn == 'campaign' )
			return $query['ugc_campaign_sid'];
	}



	// check if a user can vote for an image
	function checkVotingAbility( $campaign_id, $fb_user_id, $img_ugc_sid ) {

		// get voting start-end dates and frequency
		$query = "SELECT * FROM sp_campaign_info WHERE campaign_sid = '".$campaign_id."' LIMIT 1 ";
		$query = mysql_query( $query ) or exit( mysql_error() );
		$voting = mysql_fetch_assoc( $query );
		$votingStart = $voting['campaign_voting_start_time'];
		$votingEnd = $voting['campaign_voting_end_time'];
		$votingFrequency = $voting['campaign_vote_frequency'];

		// vars for allowing
		$votingAbility = $allow_start = $allow_end = $allow_frequency = false;

		// start date
		if ( strtotime( $votingStart ) < time() ) {
			$allow_start = true;
		} else {
			$votingAbility = 'Voting starts on ' . date( 'M d, Y', strtotime( $votingStart ) ) . '.';
		}

		// end date
		if ( strtotime( $votingEnd ) > time() ) {
			$allow_end = true;
		} else {
			$votingAbility = 'Voting has ended.';
		}

		// frequency

		// unlimited times per campaign, but only once per any image
		if ( $votingFrequency == '-1' ) {
			$query = "SELECT * FROM sp_campaign_ugc_vote WHERE vc_facebookid = '".$fb_user_id."'
									AND vc_contentid = '".$img_ugc_sid."' ";
			$query = mysql_query( $query ) or exit( mysql_error() );
			$votesPerImage = mysql_num_rows( $query );
			if ( $votesPerImage == 0 ) $allow_frequency = true;
			else $votingAbility = 'You can vote only once per image.';
		}
		// once per campaign
		elseif ( $votingFrequency == '0' ) {
			$query = "SELECT * FROM sp_campaign_ugc_vote WHERE vc_facebookid = '".$fb_user_id."'
									AND vc_campaign_sid = '".$campaign_id."' ";
			$query = mysql_query( $query ) or exit( mysql_error() );
			$votesPerCampaign = mysql_num_rows( $query );
			if ( $votesPerCampaign == 0 ) $allow_frequency = true;
			else $votingAbility = 'You can vote only once per campaign.';
		}
		// one or more times per day
		else {
			// get user's votes during the last 24 hours
			$query = "SELECT * FROM sp_campaign_ugc_vote WHERE vc_facebookid = '".$fb_user_id."'
								AND vc_campaign_sid = '".$campaign_id."' AND vc_voteTime > ( NOW() - INTERVAL 1 DAY )";
			$query = mysql_query( $query ) or exit( mysql_error() );
			$votesDuring24Hours = mysql_num_rows( $query );
			// check if a user has voted for an image during the last 24 hours
			$query = "SELECT * FROM sp_campaign_ugc_vote WHERE vc_facebookid = '".$fb_user_id."'
								AND vc_contentid = '".$img_ugc_sid."' AND vc_voteTime > ( NOW() - INTERVAL 1 DAY )";
			$query = mysql_query( $query ) or exit( mysql_error() );
			$votesForImageDuring24Hours = mysql_num_rows( $query );

			if ( $votesDuring24Hours >= $votingFrequency )
				$votingAbility = 'You can vote up to ' . $votingFrequency . ' times per day.';
			elseif ( $votesForImageDuring24Hours > 0 )
				$votingAbility = 'You have already voted for this image today.';
			else $allow_frequency = true;

			/* $votes (24 hours) < frequency && $votes( img ) == 0 */
			// ORDER BY vc_voteTime DESC



					/*
			if ( $votesPerCampaign < $votingFrequency ) 
			else {
				if ( $votesPerImage == 0 ) $allow_frequency = true;
				else {
					if ( $votesPerImage == 1 ) 
					$i = 0;
					while ( $vote = mysql_fetch_assoc( $votesLatest ) ) {
						// we have to check only one vote: the last one - $votingFrequency
						if ( $i == $votingFrequency - 1 ) {
							if ( time() - 24 * 60 * 60 < strtotime( $vote['vc_voteTime'] ) ) {
								$votingAbility = 'You can vote up to ' . $votingFrequency . ' times per day.';
							} else {
								$votingAbility = 'You have already voted for this image today.';
							}
							break;
						}
						$i++;
					} // endwhile
				}
			}
			*/
		} // one or more times per day

		if ( $allow_start && $allow_end && $allow_frequency ) $votingAbility = true;

		return $votingAbility;
	} // checkVotingAbility()



	// prepare images for showing
	function prepareUgcGalleryImages( $campaign_id, $fb_user_id ) {
		$result = '';
		// get all ugc contest images
		$query = "SELECT * FROM sp_campaign_ugc WHERE ugc_campaign_sid = '".$campaign_id."'
								AND ugc_approve_state=1
								ORDER BY ugc_upload_time DESC";
		$query = mysql_query( $query ) or exit( mysql_error() );
		if ( mysql_num_rows( $query ) == 0 ) {
			$result = '<p>This campaign has no contest images yet.</p>';
		} else {
			while ( $img = mysql_fetch_assoc( $query ) ) {
				// get user name
				$query1 = "SELECT * FROM sp_campaign_result
					WHERE cpresult_sid = '".$img['ugc_user_id']."' LIMIT 1";
				$query1 = mysql_query( $query1 ) or exit( mysql_error() );
				$user = mysql_fetch_assoc( $query1 );
				$userName = $user['cpresult_first_name'];
				$userSurname = $user['cpresult_last_name'];
				if ( $userSurname != '' ) $userSurname = substr( $userSurname, 0, 1 ) . '.';
				$userFullName = $userName . ' ' . $userSurname;
				// generate content for ugc gallery
				$imgUrl = DEV_WEBSITE_URL . DIR_UPLOADS . $img['ugc_photo_name'];
				$result .= '<li>';
					$result .= '<div class="pic"><img src="'. $imgUrl . '" alt="" /><span></span></div>';
					$result .= '<a class="aButton view">View</a>';
					// check if a user can vote for an image
					$img_ugc_sid = getImgUgcSidAndCampaignSid( $img['ugc_photo_name'], 'img' );
					if ( checkVotingAbility( $campaign_id, $fb_user_id, $img_ugc_sid ) === true ) {
						$result .= '<a class="aButton vote">Vote</a>';
					} else {
						$result .= '<a class="aButton vote clicked">Vote</a>';
					}
					$result .= '<div class="text">';
						$result .= '<span class="title">' . shortName( $img['ugc_title'] ) . '</span>';
						$result .= '<span class="user">' . $userFullName . '</span>';
						$result .= '<span class="desc">' . nl2br( shortName( $img['ugc_description'], 40 ) ) . '</span>';
					$result .= '</div>';
				$result .= '</li>';
			}
		}
		return $result;
	} // prepareUgcGalleryImages()


	// документ UTF-8
?>
Back to Top