summaryrefslogtreecommitdiffstats
path: root/includes/datas.php
blob: c64edd6dfed55ac908bd1935223a9373aef8793d (plain)
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
<?PHP
// For interaction with the SQL database.
//

include_once('sqlEmbedded.php');
include_once('constants.php');

//FirePHP stuff - TODO: Delete
//require_once('includes/FirePHPCore/FirePHP.class.php');
//FirePHP stuff - TODO: Delete

//Returns text refering to any notifications.
function getNotified($userID) {


	$r = '';

	$sql = "SELECT `ID`, `type`, `level`
	FROM `achievements`
	WHERE `notified` = false
	AND userID = '$userID'
	LIMIT 25";
	
	$resultA = mysql_query($sql);
	if (mysql_num_rows($resultA) <= 0) 
		return false;
	
	// --------- We found an achievement they don't know they got!
	while (list($aID, $aType, $aLevel) = mysql_fetch_row($resultA)) {
		
		if ($r != '')
			$r .= '<br /><hr />';
		
		$aTypeNames[1] = "Path Career Level $aLevel!";
		$aTypeNames[2] = "Mazes Career Level $aLevel!";
		$aTypeNames[3] = "Maze Mastery Level $aLevel!";
		$aTypeNames[4] = "Champion Level $aLevel!";
		$aTypeNames[32] = 'Tutorial Complete!';
		
		$aTypeCurrency[1] = "total moves mazed";
		$aTypeCurrency[2] = "mazes played";
		$aTypeCurrency[3] = "mazes with (tied) top score";
		$aTypeCurrency[4] = "champion points";
	
		$aName = $aTypeNames[$aType];
		$currency = $aTypeCurrency[$aType];
		
		// --------- Any unlocks for this achievement?
		$sql = "SELECT `type`, `name`, `value`
		FROM `unlocks`
		WHERE `achievementID` = '$aID'";
		$result = mysql_query($sql);
		$unlocked = '';
		if (mysql_num_rows($result) >= 1) {
			$unlocked = "You've unlocked: ";
			while (list($uType, $uName, $uValue) = mysql_fetch_row($result)) {
				switch ($uType) {
				case 1:
					$unlocked .= "$uName Wall Color!";
					$unlocked .= "<table><tr><td onclick='changeWallColor(\"$uValue\")' style='background-color:$uValue;' class='grid_td_rocks'></td></tr></table>";
					break;
				case 2:
					$unlocked .= "$uName Emblem!";
					$unlocked .= "<div class='grid_td_rocks' title='' onClick='emblemclick(this,\"$uValue\", \"0\")' style='background: #999 url(../images/marks/$uValue);' >";
					$unlocked .= "<div class='grid_inner grid_td_walls'></div></div>";
					break;
				case 3:
					$unlocked .= "<br /><span style='color:$uValue;'>$uName Username color!</span><br />";
					break;
				}
			}
		}
		// ---------- Prepare response
		
		$r .= "<strong>$aName</strong>";
		if ($unlocked !== '') {
			$r .= "<center>$unlocked";
			//$r .= "<div style='width:300px;height:75px;overflow:auto;'>";
			$r .= "</center>";
		}
		$aAry = getAchievementsArray($aType);
		$nextLevelRequired = $aAry[($aLevel + 1)][0];
		$currentLevelRequired = $aAry[($aLevel)][0];
		
		if ($currency) {
			$currentLevelRequired = number_format($currentLevelRequired);
			$r .= "You have $currentLevelRequired $currency <br />";
		}
		if ($nextLevelRequired >= 1) {
			$nextLevelRequired = number_format($nextLevelRequired);
			$r .= "Next level at $nextLevelRequired <br />";
		}
		
		
		
		
		// Item ID List
		$aIDList[] = "'$aID'";
	}
	$r .= "<br /><a href='achievements?id=$userID'>Go select unlocks now</a>";
	
		// ---------- Mark that we have notified the user
		$aIDListStr = implode(',', $aIDList);
		$sql = "UPDATE `achievements` 
		SET `notified` = 1
		WHERE `ID` IN ($aIDListStr)";
		mysql_query($sql);
	
	return $r;
	// ---------- Done!
}

//Returns true when an achievement is applied.
// Usage example: applyCareerAchievement($userID);
// TODO: DEPRECIATED
function applyCareerPathAchievements($userID) {
	$sql = "SELECT totalMoves
	FROM `users`
	WHERE ID = '$userID'";
	$result = mysql_query($sql);
	
	// --------- User hasn't played yet.
	if (mysql_num_rows($result) != 1)
		return false;
	
	list($uTotalMoves) = mysql_fetch_row($result);

	// ------- Select the highest level they've achieved.
	$sql = "SELECT `level`
	FROM `achievements`
	WHERE `userID` = '$userID'
	AND `type` = 1
	ORDER BY `level` DESC
	LIMIT 1";
	$result = mysql_query($sql);
	// --------- No achievements yet?
	if (mysql_num_rows($result) == 1)
		list($aLevel) = mysql_fetch_row($result);
	else
		$aLevel = 0;
	
	$cp = getCareerPathArray();

	//Is there a next level for this?
	$aNextLevel = $aLevel + 1;
	if (!isset($cp[$aNextLevel]))
		return false;
	list($required, $unlockType, $unlockValue, $unlockName) = $cp[$aNextLevel];
	
	if ($uTotalMoves < $required)
		return false;

	$sql = "INSERT INTO `achievements`
	(`userID`, `type`, `level`)
	VALUES ('$userID', 1, '$aNextLevel')";
	mysql_query($sql);
	$aID = mysql_insert_id();
	
	// ------- User gets unlock.  (unlocks plural is possible here)
	$sql = "INSERT INTO `unlocks`
	(`userID`, `achievementID`, `type`, `subtype`, `name`, `value`)
	VALUES ('$userID', '$aID', '$unlockType', NULL, '$unlockName', '$unlockValue')";
	mysql_query($sql);
	return true;
}

//Almost a duplicate of applyCareerPathAchievements
// TODO: DEPRECIATED
function applyCareerMazesAchievements($userID) {
	$sql = "SELECT 
	COUNT(*) as totalSolutions
	FROM `solutions`
	WHERE userID = '$userID'";
	$result = mysql_query($sql);
	
	// --------- User hasn't played yet.
	if (mysql_num_rows($result) != 1)
		return false;
	
	list($uTotalSolutions) = mysql_fetch_row($result);

	// ------- Select the highest level they've achieved.
	$sql = "SELECT `level`
	FROM `achievements`
	WHERE `userID` = '$userID'
	AND `type` = 2
	ORDER BY `level` DESC
	LIMIT 1";
	$result = mysql_query($sql);
	// --------- No achievements yet?
	if (mysql_num_rows($result) == 1)
		list($aLevel) = mysql_fetch_row($result);
	else
		$aLevel = 0;
	
	$cm = getCareerMazesArray();

	//Is there a next level for this?
	$aNextLevel = $aLevel + 1;
	if (!isset($cm[$aNextLevel]))
		return false;
	list($required, $unlockType, $unlockValue, $unlockName) = $cm[$aNextLevel];
	
	if ($uTotalSolutions < $required)
		return false;

	$sql = "INSERT INTO `achievements`
	(`userID`, `type`, `level`)
	VALUES ('$userID', 2, '$aNextLevel')";
	mysql_query($sql);
	$aID = mysql_insert_id();
	
	// ------- User gets unlock.  (unlocks plural is possible here)
	$sql = "INSERT INTO `unlocks`
	(`userID`, `achievementID`, `type`, `subtype`, `name`, `value`)
	VALUES ('$userID', '$aID', '$unlockType', NULL, '$unlockName', '$unlockValue')";
	mysql_query($sql);
	return true;
}

/**
 * Called when a user completes a challenge
 * @param type $userID User who did the challenge
 * @param type $mapID Map to check for challenges
 * @param type $solution The final placement of towers, as a string of .-separated x,y pairs.
 *                       Begins and ends with "." as well
 * @param type $moves The total number of moves in the solution, for all paths
 * @param type $paths An array of path-objects, each as returned by routePath().
 */
function getCompletedChallenges($userID, $mapID, $solution, $moves, $paths) {
	//mapID 5 is the tutorial, and is treated specially
	
	//TODO: Fix / depreciate this. Re-adapt tutorial
	// Temporary Hack to complete the tutorial...
	// if($mapID <= 10) {
		if ($mapID == 5 && $moves == 75) {
			onCompletedTutorial($userID);
		}
		// return;
	// }
	
	$challengeResultset = loadChallengesForMap($mapID, $userID);
	$challengesCompleted = array();
	while($challenge = mysql_fetch_array($challengeResultset))
	{
		//Skip checking challenges which have already been completed
		if($challenge["dateSolved"] !== NULL)
		{
			$challengesCompleted[] = $challenge["challengeID"];
		}
		else if(hasChallengeBeenCompleted($challenge, $solution, $moves, $paths))
		{
			setChallengeCompleted($challenge, $solution, $userID, $moves);
			$challengesCompleted[] = $challenge["challengeID"];
		}
	}
	
	return $challengesCompleted;
}

/**
 * Called when a user completes the tutorial
 */
function onCompletedTutorial($userID) {
	//have they previously completed the tutorial?
	if(hasCompletedTutorial($userID))
		return false;
	
	// -------- This is the first time they've completed the tutorial!
	$sql = "INSERT INTO `achievements`
	(`userID`, `type`, `level`)
	VALUES ('$userID', 32, '1')";
	mysql_query($sql);
	$aID = mysql_insert_id();

	// ------- User gets unlock.  (unlocks plural is possible here)
	$sql = "INSERT INTO `unlocks`
	(`userID`, `achievementID`, `type`, `subtype`, `name`, `value`)
	VALUES ('$userID', '$aID', '1', 0, 'Blue', '#4444ff')";
	mysql_query($sql);
	
	return true;
}

/**
 * Checks if the given solution meets the requirements for the given challenge
 */
function hasChallengeBeenCompleted($challenge, $solution, $moves, $paths) {
	//$firephp = FirePHP::getInstance(true);
	//Check the maze-length
	if($challenge['goal'] != 0) {
		//Er, "greater than" should really be called "greater than or equal to" :\
		if(($challenge['inequality'] == "greater than" && $moves < $challenge['goal'])
		  || ($challenge['inequality'] == "less than" && $moves >= $challenge['goal'])
		  || ($challenge['inequality'] == "equal" && $moves != $challenge['goal']))
		{
			//$firephp->log("Failed at distance");
			return false;
		}
	}
	
	//Check wall-count restriction
	if($challenge['restrictWallCount'] !== NULL)
	{
		//The number of walls is equal to the number of "," characters in the $solution string
		$temp = count_chars($solution, 1); //$temp needed due to extreme PHP-stupidity
		$numWalls = $temp[ord(",")];
		if($numWalls > $challenge['restrictWallCount']) {
			//$firephp->log("Failed at wall-count");
			return false;
		}
	}
	
	//Check wall-placement restriction
	if($challenge['restrictWallPlacement'] !== NULL)
	{
		$invalidWalls = explode(".", $challenge['restrictWallPlacement']);
		foreach($invalidWalls as $invalidWall)
		{
			$stringToSearchFor = "." . swapXandYCoordinates($invalidWall) . ".";
			if(strpos($solution,$stringToSearchFor) !== false)
			{
				//$firephp->log("Failed at wall-placement: " . $invalidWall);
				//$firephp->log("Solution: " . $solution);
				return false;
			}
		}
	}
	
	//TODO: This portion probably needs to be rewritten due to the weird way paths are saved
	if($challenge['restrictTeleportCount'] !== NULL || $challenge['restrictTeleportsUsed'] !== NULL)
	{
		//Check teleport count
		$usedTeleports = explode(".", getUsedTeleports($paths)); //TODO: Implement
		if($challenge['restrictTeleportCount'] !== NULL)
		{
		   if(count($usedTeleports) !== $challenge['restrictTeleportCount'] &&
				   ($challenge['restrictTeleportCount'] != 0 || $usedTeleports[0] != ""))
			{
			   //$firephp->log("Failed at teleport count");
				return false;
			}
		}
		
		//Check teleports used
		if($challenge['restrictTeleportsUsed'] !== NULL)
		{
			foreach($usedTeleports as $usedTeleport)
			{
				foreach($paths as $path)
				{
					//Check each path to see if it walks over that teleport
					if(strpos($path['path'], $usedTeleport) !== false)
					{
						//$firephp->log("Failed at teleports used");
						return false;
					}
				}
			}
		}
	}
	
	//Check start points
	if($challenge['restrictStartPoint'] !== NULL)
	{
		$usesCorrectStartPoint = false;
		foreach($paths as $path)
		{
			if($path['start'] == $challenge['restrictStartPoint'])
				$usesCorrectStartPoint = true;
		}
		
		if(!$usesCorrectStartPoint)
		{
			//$firephp->log("Failed at start-point");
			return false;
		}
	}
	
	//Check end points
	if($challenge['restrictEndPoint'] !== NULL)
	{
		$usesCorrectEndPoint = false;
		foreach($paths as $path)
		{
			if($path['end'] == $challenge['restrictEndPoint'])
				$usesCorrectEndPoint = true;
		}
		
		if(!$usesCorrectEndPoint)
		{
			//$firephp->log("Failed at endpoint");
			return false;
		}
	}
	
	//All of the restrictions were met, meaning the challenge was completed!
	//$firephp->log("Succeeded!");
	return true;
}

/**
 * Returns the datetime of the next weekly map
 */
function getNextWeeklyMapDateTime()
{
	$sql = "SELECT MAX(mapExpireTime) AS mapExpireTime
	FROM mapOfTheDay
	WHERE mapType = " . MapType::Weekly;
	
	$result = mysql_query($sql);
	$row = mysql_fetch_row($result);
	return $row[0];
}

/**
 * Hack, due to positions being stored as x,y in some places and y,x in others
 */
function swapXandYCoordinates($position)
{
	$coords = explode(",", $position);
	return $coords[1] . "," . $coords[0];
}

/**
 * Sets the given challenge as completed by the user in the database
 */
function setChallengeCompleted($challenge, $solution, $userID, $moves) {
	$solution = mysql_escape_string($solution);
	$userID = mysql_escape_string($userID);
	$challengeID = $challenge["challengeID"];
	
	$sql = "INSERT INTO `challengeSolutions`
	(`userID`, `challengeID`, `solution`, `moves`, `dateSolved`)
	VALUES ('$userID', '$challengeID', '$solution', $moves, NOW())";
	mysql_query($sql);
}

function isChallengeMap($mapID) {
	$sql = "SELECT ID
	FROM `challengeMaps`
	WHERE 
		ID = '$mapID';
	";
	$result = mysql_query($sql) or die(mysql_error());
	return (mysql_num_rows($result) != 0);
}

function getUserChallengeTier($userID)
{
	$userID = mysql_escape_string($userID);
	
	$sql = "SELECT challengeTier
	FROM users
	WHERE users.ID = '$userID'";
	
	$result = mysql_query($sql);
	$row = mysql_fetch_row($result);
	return $row[0];
}

function setUserChallengeTier($userID, $challengeTier)
{
	$userID = mysql_escape_string($userID);
	$challengeTier = mysql_escape_string($challengeTier);
	
	$sql = "UPDATE users
	SET challengeTier = '$challengeTier'
	WHERE users.ID = '$userID'";
	
	mysql_query($sql);
}

function applyAchievements($userID, $aType) {

	$amount = getAchievementCurrency($userID, $aType);
	
	$aLevel = getAchievementLevel($userID, $aType);
	
	$aArray = getAchievementsArray($aType);
	
	//Is there a next level for this?
	$aNextLevel = $aLevel + 1;
	if (!isset($aArray[$aNextLevel]))
		return false;
	list($required, $unlockType, $unlockValue, $unlockName, $unlockSubtype) = $aArray[$aNextLevel];
	if ($amount < $required)
		return false;

	$sql = "INSERT INTO `achievements`
	(`userID`, `type`, `level`)
	VALUES ('$userID', $aType, '$aNextLevel')";
	mysql_query($sql);
	$aID = mysql_insert_id();
	
	// ------- User gets unlock.  (TODO: unlocks plural is possible here)
	$sql = "INSERT INTO `unlocks`
	(`userID`, `achievementID`, `type`, `subtype`, `name`, `value`)
	VALUES ('$userID', '$aID', '$unlockType', '$unlockSubtype', '$unlockName', '$unlockValue')";
	mysql_query($sql);
	return true;

}

function getAchievementCurrency($userID, $aType) {

// 1, Total Moves										"Path Career"		//Backdated
// 2, Total Solutions (Total maps played)		"Mazes Career"		//Backdated
// 3, Tie Top-Score on a map						"Maze Mastery"		//Tracked (no backdate)
// 4, Champion Points!
	$r = 0;
	$sql = '';
	//TODO: These can all be combined into a single query...
	switch ($aType) {
		case 1:
			$sql = "SELECT totalMoves AS t
			FROM `users`
			WHERE `ID` = '$userID'";
		break;
		case 2:
			$sql = "SELECT totalMazes as t
			FROM `users`
			WHERE `ID` = '$userID'";
		break;
		case 3:
			$sql = "SELECT totalTies
			FROM `users`
			WHERE `ID` = '$userID'";
		break;
		case 4:
			$sql = "SELECT championPoints
			FROM `users`
			WHERE `ID` = '$userID'";
		break;
	}
	if ($sql == '')
		return false;
	$result = mysql_query($sql) OR die("SQL query failed; $sql");
	if (mysql_num_rows($result) == 1)
		list($r) = mysql_fetch_row($result);

	return $r;
}

function getAchievementLevel($userID, $aType) {
	// ------- Select the highest level they've achieved.
	$r = 0;
	$sql = "SELECT `level`
	FROM `achievements`
	WHERE `userID` = '$userID'
	AND `type` = '$aType'
	ORDER BY `level` DESC
	LIMIT 1";
	$result = mysql_query($sql);
	if (mysql_num_rows($result) == 1)
		list($r) = mysql_fetch_row($result);
	return $r;
}

function getAchievementsArray($type) {
	if ($type == 1)
		return getCareerPathArray();
	if ($type == 2)
		return getCareerMazesArray();
	if ($type == 3)
		return getMazeMasteryArray();	
	if ($type == 4)
		return getChampionPointsArray();
	//Tutorial
	if ($type == 32) {
		$r[1] = array(1, 1, '#4444ff', 'Blue');
		return $r;
	}
	return array();
}

//TYPE 1
function getCareerPathArray() {
	//$cp[0] = array(requiredmoves, type, 'value', 'name');
	
	// Note that the description is followed by " wall color"
	$cp[1] = array(100, 1, '#229922', 'Green');
	$cp[2] = array(1000, 1, '#9922ff', 'Purple');
	$cp[3] = array(5000, 2, 'CircleSmall_W.png', 'Light Small Circle', 0);
	$cp[4] = array(10000, 2, 'DiamondSmall_B.png', 'Dark Small Diamond', 0);
	$cp[5] = array(20000, 3, '#a9b1f6', 'Steel Blue');
	$cp[6] = array(32000, 2, 'DiagonalCover_W.png', 'Light Diagonal Cover', 0);
	$cp[7] = array(50000, 2, 'DiamondLargeDonut_B_I.png', 'Inverted Dark Annulated Diamond', 0);
	$cp[8] = array(75000, 3, '#ffffaa', 'Yellow');
	$cp[9] = array(100000, 3, '#ffbb77', 'Orange');	
	$cp[10] = array(130000, 2, 'OffsetStripesVertical_W.png', 'Light Vertical Stripes', 0);
	$cp[11] = array(165000, 2, 'CircleSmall_B.png', 'Dark Small Circle', 0);
	$cp[12] = array(200000, 3, '#ee77ff', 'Purple');
	$cp[13] = array(250000, 1, '#ffff22', 'Yellow', 1);
	$cp[14] = array(300000, 2, 'DiagonalCover_B_I.png', 'Inverted Dark Diagonal Cover', 0);
	$cp[15] = array(350000, 1, '#333377', 'Navy Blue', 0);
	$cp[16] = array(400000, 2, 'RacingStripes_W.png', 'Light Racing Stripes', 0);

	return $cp;
}

//TYPE 2
function getCareerMazesArray() {
	//$cp[0] = array(requiredmazes, type, 'value', 'name');
	
	$cm[1] = array(5, 1, '#eeeeee', 'Silver', 1);
	$cm[2] = array(15, 1, '#ff9922', 'Orange', 1);
	$cm[3] = array(30, 2, 'DiamondLargeDonut_W.png', 'Light Annulated Diamond', 0);
	$cm[4] = array(50, 1, '#aaaa22', 'Chartreuse');
	$cm[5] = array(85, 2, 'CrossXL_W.png', 'Light Large Present', 0);
	$cm[6] = array(150, 1, '#cc22aa', 'Magenta', 0);
	$cm[7] = array(250, 1, '#ff3344', 'Red');
	$cm[8] = array(375, 1, '#ffdd88', 'Gold', 1);
	$cm[9] = array(550, 2, 'ConvexCover_W.png', 'Light Dome Cover', 0);
	$cm[10] = array(750, 2, 'OffsetStripesVertical_B.png', 'Dark Vertical Stripes', 0);
	$cm[11] = array(1000, 3, '#ff95b0', 'Pink');
	$cm[12] = array(1400, 1, '#ff95b0', 'Pink', 1);
	$cm[13] = array(2000, 2, 'StarsR_W.png', 'Bright Stars', 0);
	$cm[14] = array(2750, 2, 'Stars1_B.png', 'Dark Single Star', 0);
	$cm[15] = array(3500, 2, 'CircleSmall_B_I.png', 'Inverted Dark Small Circle', 0);
	
	return $cm;
}

//TYPE 3
function getMazeMasteryArray() {
	//$cp[0] = array(requiredmazestied, type, 'value', 'name');
	$r[1] = array(1, 2, 'OffsetStripesDiagonal_W.png', 'Light Diagonal Stripes', 0);
	$r[2] = array(5, 2, 'OffsetStripesVertical_B_I.png', 'Inverted Dark Vertical Stripes', 0);
	$r[3] = array(15, 2, 'DiagonalCover_W_I.png', 'Inverted Light Diagonal Cover', 0);
	$r[4] = array(30, 3, '#aafcbb', 'Green');
	$r[5] = array(50, 2, 'DiamondLarge_W.png', 'Light Large Diamond', 0);
	$r[6] = array(75, 2, 'CrossXL_B.png', 'Dark Large Present', 0);
	$r[7] = array(100, 2, 'CircleLargeDonut_W.png', 'Light Annulated Circle', 0);
	$r[8] = array(150, 2, 'CrossXL_W_I.png', 'Inverted Bright Large Present', 0);
	$r[9] = array(225, 2, 'CircleLarge_W_I.png', 'Inverted Bright Large Circle', 0);
	$r[10] = array(300, 2, 'DiamondSmall_B_I.png', 'Inverted Dark Small Diamond', 0);
	$r[11] = array(400, 2, 'CircleLargeDonut_B.png', 'Dark Annulated Circle', 0);
	$r[12] = array(550, 2, 'CrossXL_B_I.png', 'Inverted Dark Large Present', 0);
	
		//$cp[4] = array(10000, 2, 'DiamondSmall_B.png', 'Dark Small Diamond', 0);
	
	return $r;
}

//TYPE 4
function getChampionPointsArray() {
	//$cp[0] = array(requiredpoints, type, 'value', 'name');
	$r[1] = array(100, 2, 'DiagonalCover_B.png', 'Light Diagnol Cover', 0);
	$r[2] = array(250, 1, '#22aaaa', 'Teal');
	$r[3] = array(500, 2, 'OffsetStripesDiagonal_B.png', 'Dark Diagonal Stripes', 0);
	$r[4] = array(1000, 2, 'DiamondLargeDonut_W_I.png', 'Inverted Light Annulated Diamond', 0);
	$r[5] = array(2000, 2, 'StarsR_B.png', 'Dark Stars', 0);
	$r[6] = array(4000, 2, 'OffsetStripesHorizontal_B_I.png', 'Inverted Dark Horizontal Stripes', 0);
	$r[7] = array(8000, 2, 'CrossXLDonut_B_I.png', 'Inverted Dark Large Intersection', 0);
	$r[8] = array(16000, 2, 'DiamondLarge_B.png', 'Dark Large Diamond', 0);
	$r[9] = array(32000, 1, '#22ff22', 'Neon Lime', 1);
	//$r[7] = array(75, 2, 'CircleSmall_W_I.png', 'Inverted Bright Small Circle', 0);
		
	return $r;
}

//Select Members
function getMembers($pageNumber = 1, $pageDivide = 50, $order = 'DESC', $orderBy = 'dateJoined') {

	if ($pageDivide <= 0)
		$pageDivide = 50;
	if ($order !== 'ASC' AND $order !== 'DESC')
		$order = 'DESC';
	$columns = array('dateJoined', 'dateLogin', 'championPoints',
		'totalMazes', 'totalWins', 'totalTies', 'totalMovesThisWeek', 
		'totalMoves', 'display');
	if (!in_array($orderBy, $columns))
		$orderBy = 'dateJoined';
	//These values are now confirmed.
	$sqlOrder = "ORDER BY `$orderBy` $order";
	
	$limitTop = ($pageNumber - 1) * $pageDivide;
	
	$sql = "SELECT COUNT(*) as 'count' FROM `users`";
	$result = mysql_query($sql) or die(mysql_error());
	$row = mysql_fetch_assoc($result);
	$total = $row['count'];
	
	$output['pageCount'] = ceil(($total / $pageDivide));
	
	$pageRequest = 'all';
	if ($pageRequest == 'all') {
		$pageReqStart = 1;
		$pageReqEnd = 1000;
	} elseif (is_int($pageRequest)) {
		$pageReqStart = $pageRequest;
		$pageReqEnd = $pageRequest;
	} else {
		$tmp = explode($pageRequest, "-");
		$pageReqStart = $tmp[0];
		$pageReqEnd = $tmp[1];
	}
	
	$sql = "
	SELECT
		users.ID as ID,
		users.displayName as display,
		users.totalMoves,
		(
			SELECT IFNULL(SUM(moves),0)
			FROM solutions
			INNER JOIN mapOfTheDay ON solutions.mapID = mapOfTheDay.mapID
			WHERE solutions.userID = users.ID
			AND mapOfTheDay.mapExpireTime BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
		) AS totalMovesThisWeek,
		users.championPoints as championPoints,
		users.totalMazes as totalMazes,
		users.totalWins as totalWins,
		users.totalTies as totalTies,
		users.wallColor,
		users.displayColor,
		users.wallEmblem,
		users.datejoined as dateJoined,
		users.dateLogin as dateLogin
	FROM `users`
	$sqlOrder
	LIMIT $limitTop, $pageDivide
	";
	
	$result = mysql_query($sql);
	//$utime = date("g:i A (T)");
	
	$output['updateTime'] = date("g:i A (T)");
	
	$i = $limitTop;
	$foundUser = false;
	while ($row = mysql_fetch_assoc($result)) {
		$i++;

		$userID = $row['ID'];
		if ($_SESSION['userID'] == $userID) {
			$userPosition = $i;
		}

		$row['dateJoined'] = Date("Y-m-d", strtotime($row['dateJoined']));
		$row['dateLogin'] = Date("Y-m-d", strtotime($row['dateLogin']));

		$scoredDate = strtotime($row['cdate']);
		$secondsSinceScored = strtotime("now") - $scoredDate ;

		//Alternate background colors
		$background = '#262631';
		if ($i % 2 == 1)
			$background = '#20202a';
		
		if ($userPosition == $i) {
			$background = '#343c57';
			$foundUser = true;
		}
		
		$output['users'][$i] = $row;
		$output['users'][$i]['secondsSinceScored'] = $secondsSinceScored;
		$output['users'][$i]['background'] = $background;
		$output['users'][$i]['isUser'] = $userPosition == $i;
	} // END WHILE
	
	return $output;
}



//Select Stats/Scores.
function getScores($mapID, $pageNumber = 1, $pageDivide = 10) {
	$top = $pageNumber * $pageDivide;
	$bottom = $top - $pageDivide;
	
	//TODO: !! set to false before uploading.
	$isBlindMap = false;
	
	$pageRequest = 'all';
	
	if ($pageRequest == 'all') {
		$pageReqStart = 1;
		$pageReqEnd = 1000;
	} elseif (is_int($pageRequest)) {
		$pageReqStart = $pageRequest;
		$pageReqEnd = $pageRequest;
	} else {
		$tmp = explode($pageRequest, "-");
		$pageReqStart = $tmp[0];
		$pageReqEnd = $tmp[1];
	}
	
	$userID = $_SESSION['userID'];
	$myBestMoves = 0;
	if ($isBlindMap) {
		$sql = "SELECT `moves` FROM `solutions` WHERE `mapID` = '$mapID' AND `userID` = '$userID'";
		$result = mysql_query($sql) or die(mysql_error());
		$row = mysql_fetch_assoc($result);
		$myBestMoves = $row['moves'];
	}
	
	$requestSolutions = '';
	$currentMap = isCurrentMap($mapID);
	if (!$currentMap) {
		$requestSolutions = 'solutions.solution,';
	}
	
	$sql = "
	SELECT 
		timediff(solutions.dateModified, TIMESTAMP(CURDATE())) as diff,
		users.displayName as display,
		solutions.moves as moves,
		users.ID as ID,
		users.displayColor,
		users.wallColor,
		users.wallEmblem,
		$requestSolutions
		solutions.dateModified as cdate
	FROM 
		`users`
		JOIN `solutions`
			ON users.ID = solutions.userID
	WHERE solutions.mapID = '$mapID'
	ORDER BY solutions.moves DESC, solutions.dateModified ASC, solutions.ID DESC
	";
	// ORDER BY solutions.moves ASC, solutions.dateModified DESC, solutions.ID ASC
	$result = mysql_query($sql);
	//$utime = date("g:i A (T)");
	
	$output['updateTime'] = date("g:i A (T)");
	
	$i = 0;
	$foundUser = false;
	
	while ($row = mysql_fetch_assoc($result)) {
		$i++;

		$moves = $row['moves'];
		
		$requestedUserID = $row['ID'];
		if ($i == 1) {
			$bestMoves = $moves;
			$output['bestMoves'] = $bestMoves;
			$output['bestBy'] = $row['display'];
		}
			
		if ($_SESSION['userID'] == $requestedUserID) {
			$userPosition = $i;
			//$myBestMoves = $moves;
		} else {
			if ($i > $top)
				continue;
			if ($i <= $bottom)
				continue;
		}

		$scoredDate = strtotime($row['cdate']);
		$secondsSinceScored = strtotime("now") - $scoredDate ;

		//Alternate background colors
		$background = '#262631';
		if ($i % 2 == 1)
			$background = '#20202a';
		
		if ($userPosition == $i) {
			$background = '#343c57';
			$foundUser = true;
		}
		
		$medal = 'none';
		if ($moves == $bestMoves)
			$medal = 'silver';
		if ($i == 1)
			$medal = 'gold';
			
		// if is blind map.
		if ($isBlindMap AND $myBestMoves < $moves) $row['moves'] = '???';
		
		$output['users'][$i] = $row;
		$output['users'][$i]['secondsSinceScored'] = $secondsSinceScored;
		$output['users'][$i]['background'] = $background;
		$output['users'][$i]['medal'] = $medal;
		$output['users'][$i]['isUser'] = $userPosition == $i;
	} // END WHILE

	if ($foundUser) {
		$userPage = ceil(($userPosition / $pageDivide));
		$output['userPage'] = $userPage;
		$output['userPosition'] = $userPosition;
	}
	
	$output['pageCount'] = ceil(($i / $pageDivide));
	return $output;
}


/**
 * Returns true if the given user has completed the tutorial, false otherwise
 */
function hasCompletedTutorial($userID) {
	$userID = mysql_escape_string($userID);
	
	$sql = "SELECT `level` FROM `achievements` 
	WHERE `type` = 32 AND `userID` = '$userID'
	LIMIT 1";
	$result = mysql_query($sql);
	return (mysql_num_rows($result) >= 1);
}

/**
 * Returns a MySQL resultset for all challenges for the given mapID
 * @param $mapIdUnsanitized The mapID to load.  Assumed to be unsanitized.
 * @param $userID The userID.  Assumed to be unsanitized
 * @return Returns a MySQL resultset with the columns listed in the code, or NULL if nothing found
 */
function loadChallengesForMap($mapIdUnsanitized, $userIdUnsanitized)
{
	$mapID = mysql_escape_string($mapIdUnsanitized);
	$userID = mysql_escape_string($userIdUnsanitized);
	$sql = "
	SELECT challenges.ID AS challengeID, challenges.inequality, challenges.goal, challenges.hint,
		challenges.restrictWallCount, challenges.restrictWallPlacement, challenges.restrictTeleportCount,
		challenges.restrictTeleportsUsed, challenges.restrictStartPoint, challenges.restrictEndPoint,
		challengeSolutions.dateSolved
	FROM challenges
	LEFT JOIN challengeSolutions ON challenges.ID = challengeSolutions.challengeID AND challengeSolutions.userID = '$userID'
	WHERE challenges.mapID = '$mapID' AND challenges.enabled = 1
	ORDER BY challenges.ordering
	";
	
	$result = mysql_query($sql);
	echo mysql_error();
	if (mysql_num_rows($result) >= 1)
		return $result;
	return NULL;
}

/**
 * Loads a listing of all maps and challenges for display, along with which ones the user has completed
 * @param type $userIdUnsanitized The userID.  Assumed to be unsanitized.
 * @return Returns a MySQL resultset with the columns listed in the code, or NULL if nothing found
 */
function loadChallengeListing($userIdUnsanitized)
{
	$userID = mysql_escape_string($userIdUnsanitized);
	
	$sql = "SELECT challengeMaps.ID AS challengeMapID, challengeMaps.challengeTier, challengeMaps.name AS name,
	challengeSolutions.dateSolved, challengeSolutions.challengeID AS challengeID,
	challengeMaps.challengeSuborder, challenges.ordering, challengeMaps.code as mapCode
	FROM challenges
	INNER JOIN challengeMaps ON challenges.mapID = challengeMaps.ID
	LEFT JOIN challengeSolutions ON challenges.ID = challengeSolutions.challengeID AND challengeSolutions.userID = '$userID'
	WHERE challenges.enabled = 1
	AND challengeMaps.challengeTier <= (SELECT challengeTier FROM users WHERE ID = '$userID' LIMIT 1)
	ORDER BY challengeMaps.challengeTier, challengeMaps.challengeSuborder, challenges.ordering";
	
	$result = mysql_query($sql) OR die(mysql_error()."SQL: $sql");
	if (mysql_num_rows($result) >= 1)
		return $result;
	return NULL;
}

/**
 * Returns the map "code" for the given mapId
 */
function loadChallengeMapCode($mapIdUnsanitized)
{
	$ID = mysql_escape_string($mapIdUnsanitized);
	$sql = "
	SELECT challengeMaps.code as code
	FROM challengeMaps
	WHERE ID = '$ID'
	LIMIT 1
	";
	
	$result = mysql_query($sql);
	if (mysql_num_rows($result) >= 1)
	{
		$temp = mysql_fetch_row($result);
		return $temp[0];
	}
	return NULL;
}
?>