Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/site/app/controllers/tutorius_api_controller.php
blob: 290c727fde5e60bec477279d5916f42130c72120 (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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
<?php
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is addons.mozilla.org site.
 *
 * The Initial Developer of the Original Code is
 * The Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   l.m.orchard <lorchard@mozilla.com> (Original Author)
 *   Frederic Wenzel <fwenzel@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
vendor('sphinx/addonsSearch');

uses('sanitize');

/**
 * Controller implementing addon sharing API
 * see: https://wiki.mozilla.org/User:LesOrchard/BandwagonAPI
 */
class TutoriusApiController extends AppController
{
    var $name = 'TutoriusApi';

	/** 
	* Current API version
	* Could eventually be used if we have to support different
	* API versions with different functionalities
	*/
    var $newest_api_version = 0.1;

    var $beforeFilter = array();

	/**
	* Here we specify the Models this controller requires
	*/
    var $uses = array(
        'Addon', 'Appversion', 'Review', 'TestResult', 'Addonlog', 'AddonCollection', 'Addontype', 'ApiAuthToken',
        'Application', 'Collection', 'File', 'Platform', 'Category', 'Translation', 
        'UpdateCount', 'Version', 'User'
    );
    var $components = array(
        'Amo', 'Developers', 'Email', 'Image', 'Pagination', 'Search', 'Session',
        'Versioncompare', 'Validation'
    );
    var $helpers = array(
        'Html', 'Link', 'Time', 'Localization'
    );

	/* 
	* HTML statuses used by some functions
	*/
    const STATUS_OK                 = '200 OK';
    const STATUS_CREATED            = '201 Created';
    const STATUS_NOT_MODIFIED       = '304 Not Modified';
    const STATUS_UNAUTHORIZED       = '401 Unauthorized';
    const STATUS_METHOD_NOT_ALLOWED = '405 Method Not Allowed';
    const STATUS_ERROR              = '500 Internal Server Error';

    var $cache_lifetime = 0; // 0 seconds

    function forceCache() {
        header('Cache-Control: public, max-age=' . $this->cache_lifetime);
        header('Vary: X-API-Auth');
        header('Last-Modified: ' . gmdate("D, j M Y H:i:s", $this->last_modified) . " GMT");
        header('Expires: ' . gmdate("D, j M Y H:i:s", $this->last_modified + $this->cache_lifetime) . " GMT");
    }

	/**
	* This is executed for every request to the API and
	* it is called before the requested function
	*/
    function beforeFilter() {
        Configure::write('Session.checkAgent', false);

        $this->last_modified = time();

        $this->layout = 'rest';

        if (!$this->isWriteHttpMethod()) {
            // Only force shadow DB on reads.
            $this->forceShadowDb();
        }

        $this->Collection->caching = false;
        $this->AddonCollection->caching = false;
        $this->User->caching = false;
        $this->ApiAuthToken->caching = false;

        $this->SimpleAuth->enabled = false;
        $this->SimpleAcl->enabled = false;

		/*
		* Here we extract the API version provided in the request URL.
		* We could eventually support different API versions.
        */
		$url = $_SERVER['REQUEST_URI'];

        $matches = array();
        if (preg_match('/TutoriusApi\/([\d\.]*)\//', $url, $matches)) {
            $this->api_version = $matches[1];
            if (!is_numeric($this->api_version)) {
                $this->api_version = $this->newest_api_version;
            }
        } else {
           // nothing supplied, assume latest version
            $this->api_version = $this->newest_api_version;
        }

        /* 
		* Establish a base URL for this request.
        */
		$this->base_url = ( empty($_SERVER['HTTPS']) ? 'http' : 'https' ) .
            '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        if ( ($qpos = strpos($this->base_url, '?')) !== FALSE) {
            // Toss out any query parameters.
            $this->base_url = substr($this->base_url, 0, $qpos);
        }
        $this->_sendToView('base_url', $this->base_url);
        
		// Now try to get the current authenticated user
        $this->auth_user = $this->_getAuthUser();
        $this->_sendToView('auth_user', $this->auth_user);
    }

	/**********************************************
	/*************** INDEX (Default) *************
	/*********************************************/

	/**
	* This is the main function for this controller
	* its role is to list all available functions via the API
	*/
	function index() {
		
		
	}
	
	/**********************************************
	/******************** SEARCH ******************
	/*********************************************/
	
	/*
	* Search addons by keywords. The category, maximum number of results per page
	* and 'sort by' criterias can also be specified
	* 
	* @param string $terms terms to search for
	* @param int $category limit search results to specified category. 'all' is
	* the default.
	* @param int $page page number to fetch
	* @param int $limit maximum number of results per page
	* @param string $sortBy Specify how results should be sorted
	*
	*/
	function search($terms, $category='all', $page=1, $limit=20, $sortBy='name') {
	    $args = func_get_args();
	    return $this->dispatchHttpMethod(array(
	        'GET' => 'search_GET'
	    ), $args);
	}	
	
	
	/*
	* Invoked when the search function is called using HTTP GET.
	*
	*/
	function search_GET($context, $terms, $category='all', $page=1, $limit=20, $sortBy='name') {
		extract($context);

		global $valid_status, $app_shortnames;

		// The search options array we'll fill with search criterias
        $search_options = array();
		
		// Other tables linked with the addons table we want to fetch
        $associations = array(
            'all_categories', 'all_tags', 'authors', 'compatible_apps',
            'contrib_details', 'files', 'latest_version', 'list_details'
        );

        /*
		* We don't support collections search for now, but it
		* is possible to search in collections eventually.
		*/ 
        if ($category == 'collections') {
            // special case for collections
            return;
        }

		if ($category == 'all')
			$category = 0;

		$search_options['category'] = $category;
		
        $search_options['type'] = ADDON_TUTORIUS;

        /**
		 * Different sort orders are supported. Default is by entry order
		 * in the DB.
		 */
        $sort = ""; // Default

        $sort_orders = array('newest', 'name', 'averagerating', 'weeklydownloads');

        if (isset($sortBy) && 
        in_array($sortBy, $sort_orders) ) { 
            $search_options['sort'] = $sortBy;
        }

        /**
         * Prepare for search. 
         */
        $as          = new AddonsSearch($this->Addon);
        $_result_ids = array();
        $total       = 0;

		/**
		 * Execute the search with the specified terms and search
		 * Options / criterias
		 */
        if ($terms) {
            try {
                list($_result_ids, $total) = $as->query($terms, $search_options);
            }
            catch (AddonsSearchException $e) {
                header("HTTP/1.1 503 Service Unavailable", true, 503);
                $this->publish('error', "Search is temporarily unavailable.");
            }
        }

        /**
         * slice the results to get the page specified by the user
		 * With the appropriate number of results
         */
        $offset = ($page-1)*$limit;
        $_result_ids = array_slice($_result_ids, $offset, $limit);

        if (!empty($_result_ids)) {
			$this->_getTutorials($_result_ids);
        } else {
            $results = array();
        }

		$this->_sendToView('app_names', $this->Application->getIDList());
		$this->_sendToView('guids', array_flip($this->Application->getGUIDList()));
		
		$this->render('tutorials');
	}
	
	
	/*
	* Returns a list of tutorials without any keywords constraints.
	* 
	* @param int $category limit search results to specified category. 'all' is
	* the default.
	* @param int $page page number to fetch
	* @param int $limit maximum number of results per page
	* @param string $sortBy Specify how results should be sorted
	*
	*/
	function tutorials($category='all', $page=1, $limit=10, $sort_by='') {
		
		$args = func_get_args();
	    return $this->dispatchHttpMethod(array(
	        'GET' => 'tutorials_GET'
	    ), $args);
	
	}
	
	function gee() {
		$app_names = $this->Application->getIDList();
        $guids = array_flip($this->Application->getGUIDList());

		print_r($app_names);
		print_r($guids);
	}
	
	/**
	 * This function is called then "tutorials" is called using a HTTP GET
	 */
	function tutorials_GET($context, $category='all', $page=1, $limit=10, $sort_by='') {
		extract($context);

		$addontype = ADDON_TUTORIUS;
		
		$app_names = $this->Application->getIDList();
        $guids = array_flip($this->Application->getGUIDList());
		
		/**
		 * By default, we're getting all categories
		 */
		$this_category = array();
		
		if ($category != 'all') {
			$this->Category->unbindFully();
            $this_category = $this->Category->findById($category);
		}

		$allowed_sort_by = array('name', 'updated', 'newest', 'popular', 'rated');
		
		switch ($sort_by) {
        	case 'popular':
	        case 'updated':
	        case 'newest':
	        case 'rated':
	            $sort_dir = 'desc';
	            break;
	        case 'name':
	        default:
	            $sort_dir = 'asc';
	            break;
        }

		$displaystatuses = array(STATUS_PUBLIC);
		
		$tutorials = $this->Addon->getAddonsByCategory(null, $displaystatuses,
            $addontype, $category, $sort_by, $sort_dir, $limit, $page, '', true);

		$ids = array();

		/** Build an array with all found ids so we can get
		 * more information about these tutorials
		 */
		foreach($tutorials as $tutorial) {
			$ids[sizeof($ids)] = $tutorial['Addon']['id'];
		}
		
		$this->_getTutorials($ids);

		$this->_sendToView('addons', $tutorials);
		$this->_sendToView('app_names', $app_names);
		$this->_sendToView('guids', $guids);
		
	}
	
	
	/**********************************************
	/*************** AUTHENTICATION *************
	/*********************************************/
	
	/**
	* Authenticate a user and then
	* return an authentication key so the user doesn't have to authenticate
	* with its username/password on every request
	*
	*/
    function auth() {
        $args = func_get_args();
        return $this->dispatchHttpMethod(array(
            'POST' => 'auth_POST',
			'DELETE' => 'auth_DELETE'
        ), $args);
    }

    /**
     * This function is called when "auth()" is called using a HTTP POST. 
	 * Generate a new auth token for the authenticated user.
     */
    function auth_POST($context) {
	    extract($context);
	
		/** 
		 * Create the User array and map it with the POST variables
		 * that contains the username (email) and password
		 */
		$user = $this->getParams(array(
            'username' => '',
			'password' => '',
        ));
	
		
		/**
		 * Start the authentication process by verifying the supplied
		 * credentials against the Database information
		 */
        if (null == $this->auth_user &&
                !empty($user['username']) &&
                !empty($user['password'])) {
            // Try validating the user by HTTP Basic auth username and password.
            $someone = $this->User->findByEmail($user['username']);
            if (!empty($someone['User']['id']) && $someone['User']['confirmationcode'] != '') {
                // User not yet verified.
                $auth_user = null;
            } else if ($this->User->checkPassword($someone['User'], $user['password'])) {
                $this->auth_user = $someone['User'];
                $this->auth_user['Group'] = $someone['Group'];
            }
        }

		/**
		 * If authentification was successful, _checkLoggedIn() will
		 * return true. Otherwise, an access denied message will 
		 * be displayed.
		 */
		$this->_checkLoggedIn();
        $token_value = $this->ApiAuthToken->generateTokenValue();

		/** 
		 * All good, now we can save the newly created token
		 * To the database.
		 */
        $data = array(
            'ApiAuthToken' => array(
                'token' => $token_value,
                'user_id' => $this->auth_user['id']
            )
        );

        $this->Amo->clean($data);

		/** 
		 * If the save is not successful, we'll return an error message.
		 * Otherwise, we'll return the token information
		 */
        if (!$this->ApiAuthToken->save($data)) {
            return $this->renderStatus(
                self::STATUS_ERROR, 'error',
                array('reason' => 'Failed to generate the login token')
            );
        }

        $token_url = $this->base_url . '/' . $token_value;

        return $this->renderStatus(
            self::STATUS_CREATED, 'auth_token', array(
                'value' => $token_value,
                'url'   => $token_url
            ), $token_url
        );
    }

	/**
     * Delete an existing token, rendering it unusable in the future. (eg. for
     * logout)
     */
    function auth_DELETE($context) {
        extract($context);

        $rv = $this->ApiAuthToken->deleteByUserIdAndToken(
            $this->auth_user['id'], $this->auth_user['token']
        );

        if ($rv) {
            return $this->renderStatus(
	            self::STATUS_OK, 'success', array(
	                'details' => 'The user was successfully logged out'
	            )
	        );
        } else {
            return $this->renderStatus(
                self::STATUS_ERROR, 'error',
                array('reason' => 'Unknown token ' . $this->auth_user['token'] . ' for user ' . $this->auth_user['id'])
            );
        }
    }


	/**********************************************
	/************** USER REGISTRATION *************
	/*********************************************/
	
	/**
	 * Register a new user (auto-approved)
	 */
	function registerNewUser() {
		
		$args = func_get_args();
        return $this->dispatchHttpMethod(array(
            'POST' => 'registerNewUser_POST'
        ), $args);
		
	}
	
	/**
	* This creates an account via a POST request
	*
	*/
	function registerNewUser_POST($context) {
		extract($context);
				
		/**
		 * Create the User array and map it with the POST variables
		 */
		$data['User'] = $this->getParams(array(
            'nickname' => '',
			'password' => '',
            'email'    => '',
        ));

        /** 
		 * No confirmation code. We want to simplify the process for now.
		 * User is auto-approved.
		 */
        $data['User']['confirmationcode'] = '';
        
        $this->User->data = $data;
        $this->Amo->clean($this->User->data);

        // hash password
        $this->User->data['User']['password'] = $this->User->createPassword($this->User->data['User']['password']);
        
        // no empty pw
        if ($data['User']['password'] == '')
            $this->User->invalidate('password');

        /**
         * The email address specified has to be unique
         */
        $allemail = $this->User->findAll("email='{$this->User->data['User']['email']}'");
        if (!empty($allemail)) {
            $this->User->invalidate('email');
			return $this->_renderError(
				array(
					'reason' => 'Email already in use',
					'details' => 'You cannot create another user with the same email'
				)
			);
        }

        /**
         * Just like the email address, the nickname has to be unique
         */
        if (!$data['User']['nickname'] == '') {
            $allnicks = $this->User->findAll("nickname='{$this->User->data['User']['nickname']}'");
            if (!empty($allnicks)) {
                $this->User->invalidate('nickname');
				return $this->_renderError(
					array(
						'reason' => 'nickname already in use',
						'details' => 'cannot create a new user because the selected nickname is already in use.'
					)
				);
			}
        }
        
        /**
         * Oops, unable to save the user. Return and XML error.
         */
        if (!$this->User->save()) {
			return $this->_renderError(
				array(
					'reason' => 'There was an error while creating the account'
				)
			);
        }
	}
	
	/**********************************************
	/*************** PUBLISH PROCESS **************
	/*********************************************/
	
	/**
	 * Publish a new tutorial. Supported requests are
	 * POST (create) and PUT (update)
	 */
	function publish($id = 0) {
		
		$args = array(0 => $id);
        return $this->dispatchHttpMethod(array(
            'POST' => 'publish_POST',
			'DELETE' => 'publish_DELETE'
        ), $args);
		
	}
	
	/**
	* Publish a new tutorial when the "publish" method is invoked
	* using HTTP POST
	*
	*/
	function publish_POST($context, $id) {
		extract($context);
		
		/**
		 * You need to be logged in to publish a tutorial
		 */
		$this->_checkLoggedIn();

		/**
		 * If a tutorial ID is specified (existing tutorial), we simply
		 * re-publish a previously un-published tutorial
		 */
		if ($id != 0) {
			$tutorial = $this->Addon->findById($id, array('id', 'addontype_id', 'nominationmessage', 'status', 'higheststatus'), null, -1);

			$this->_sendToView('tutorial', $tutorial);

			$this->Addon->id = $id;

			$addonData = array('inactive' => 0);

	        $this->Addon->save($addonData);
	
	  		return;
		}
		
        $addon = array();

		/** 
		 * Create the params array and map it with the POST variables
		 */
		$params = $this->getParams(array(
            'name' => '',
			'summary' => '',
			'guid' => '',
            'homepage'    => '',
            'version'    => '',
			'cat1'	=>	'',
			'cat2'	=>	'',
			'cat3'	=>	'' 
        ));

		/**
		 * Only 3 categories are supported by REMORA.
		 */
		$categories = array(
			APP_TUTORIUS => array(
				1	=>	$params['cat1'],
				2	=>	$params['cat2'],
				3	=>	$params['cat3']
			)
		);

    	/**
    	 * Make sure a file was uploaded. Return
    	 */ 		
    	if (empty($_FILES['file']['name'])) {
        	return $this->_renderError(
				array(
					'reason' => 'No file was provided'
					)
				);
    	}

        $addon['Addon']['addontype_id'] = ADDON_TUTORIUS;

        /**
         * Validate the uploaded file for some basic errors
		 * and return an error if unable to validate.
         */ 
        $validate = $this->Developers->validateFile($_FILES['file'], $addon);
        if (is_string($validate)) {
	
            return $this->_renderError(
				array(
					'reason' => $validate
				)
			);
			
        }
        else {
         
            $addon['File']['details'] = $validate;
            $addon['File']['db'] = array(
                'platform_id' => !empty($this->data['File']['platform_id']) ? $this->data['File']['platform_id'] : array(PLATFORM_ALL),
                'size' => $validate['size'],
                'filename' => $validate['filename'],
                'hash' => $validate['hash'],
                'status' => STATUS_PUBLIC,
                'datestatuschanged' => $this->Amo->getNOW()
            );

        }

		/**
		 * Delete from the test results cache duplicates
		 */
        $filename = $validate['filename'];
        $this->Amo->clean($filename);
        $this->Addon->execute("DELETE FROM `test_results_cache` WHERE `key` = '{$filename}'");

		/**
		 * Fill the Addon array with the information supplied
		 * by the user
		 */
        $addon['Addon']['guid'] = $params['guid'];
        $addon['Addon']['name'] = $params['name'];
        $addon['Addon']['summary'] = $params['summary'];
        $addon['Addon']['homepage'] = $params['homepage'];
		$addon['Addon']['status'] = STATUS_PUBLIC;
		$addon['Addon']['higheststatus'] = STATUS_PUBLIC;
        $addon['Version']['version'] = $params['version'];

        /** 
		 * Validate target applications. This is a 'hack' for now as the
		 * tutorials received don't specify which version of Tutorius they
		 * are built for. Also, the Tutorius application GUID is hardcoded
		 */
		$application['{c0385ef9-1828-4340-961a-e769a9f0a986}'] = array(
			'minVersion' => 0.1,
			'maxVersion' => 0.1
		);

        $validate = $this->Validation->validateTargetApplications($application);

        if (is_string($validate)) {

            return $this->_renderError(
				array(
					'reason' => 'No valid application was found for this tutorial'
					)
			);
			
        }
        else {
            $addon['appversions'] = $validate;
        }

        // Unbind add-ons
        $this->Addon->unbindFully();
		
		/**
		 * Check if the GUID supplied with the tutorial doesn't already exists.
		 */
		if ($existing = $this->Addon->findAll(array('Addon.guid' => $addon['Addon']['guid']), array('guid'))) {
			return $this->_renderError(
				array(
					'reason' => 'This add-on already exists in the database.'
					)
			);
		}

        $addon['error'] = 0;
        $addon['Addon']['id'] = $this->data['Addon']['id'];
        $addon['Version']['id'] = $this->data['Version']['id'];
        $addon['License'] = $this->data['License'];

        $data = serialize($addon);
        $this->Amo->clean($data);

        $filename = $addon['File']['db']['filename'];
        $this->Amo->clean($filename);

		/**
		 * Put the tutorial in cache for now.
		 */
        $this->TestResult->execute("INSERT INTO `test_results_cache` (`date`, `key`, `test_case_id`, `value`) VALUES (NOW(), '{$filename}', -1, '{$data}')");
 
		/**
		* Now, let's publish the tutorial with public status
		*/
		$this->_registerTutorial($filename, $categories);
		
	}
	
	/*
	* Unpublish a tutorial, doesn't actually delete it from the filesystem
	*
	* @param string $id id of the tutorial to unpublish
	*
	*/
	function publish_DELETE($context, $id) {
		extract($context);

        if ($id == 0) {
			return $this->_renderError(
				array(
					'reason' => "Please specify a tutorial to unpublish"
					)
			);	
        }

        $addon = $this->Addon->findById($id, array('id', 'addontype_id', 'nominationmessage', 'status', 'higheststatus'), null, -1);

		$this->_sendToView('addon', $addon);
		
		$this->Addon->id = $id;
		
		$addonData = array('inactive' => 1);
		
        $this->Addon->save($addonData);

		$this->render('unpublish');
		
	}
	
	function update($id) {
		
		$args = func_get_args();
        return $this->dispatchHttpMethod(array(
            'POST' => 'update_POST'
        ), $args);

	}
	
	
	/*
	* Update an existing tutorial
	*
	*/
	function update_POST($context, $id) {
		extract($context);

		$this->_checkLoggedIn();

		// This will store all data to be saved
        $addon = array();

		// Create the User array and map it with the POST variables
		$params = $this->getParams(array(
            'name' => '',
			'summary' => '',
            'homepage'    => '',
            'version'    => '',
			'cat1'	=>	'',
			'cat2'	=>	'',
			'cat3'	=>	'' 
        ));


    	// Make sure a file was uploaded
    	if (empty($_FILES['file']['name'])) {
        	return $this->_renderError(
				array(
					'reason' => 'No file was provided'
					)
				);
    	}

        // We just received a Tutorial
        $addon['Addon']['addontype_id'] = ADDON_TUTORIUS;

        // Validate file upload for basic errors and get some info
        $validate = $this->Developers->validateFile($_FILES['file'], $addon);
        if (is_string($validate)) {
            // If a string is returned, there was an error
            return $this->_renderError(
				array(
					'reason' => $validate
				)
			);
        }
        else {
            // If an array is returned, there were no errors
            $addon['File']['details'] = $validate;
            $addon['File']['db'] = array(
                'platform_id' => !empty($this->data['File']['platform_id']) ? $this->data['File']['platform_id'] : array(PLATFORM_ALL),
                'size' => $validate['size'],
                'filename' => $validate['filename'],
                'hash' => $validate['hash'],
                'status' => STATUS_PUBLIC,
                'datestatuschanged' => $this->Amo->getNOW()
            );
        }

        // Clear duplicates
        $filename = $validate['filename'];
        $this->Amo->clean($filename);
        $this->Addon->execute("DELETE FROM `test_results_cache` WHERE `key` = '{$filename}'");

        $addon['Addon']['guid'] = md5(uniqid());
        $addon['Addon']['name'] = $params['name'];
        $addon['Addon']['summary'] = $params['summary'];
        $addon['Addon']['homepage'] = $params['homepage'];
		$addon['Addon']['status'] = STATUS_PUBLIC;
		$addon['Addon']['higheststatus'] = STATUS_PUBLIC;
        $addon['Version']['version'] = $params['version'];

        // Validate target applications
		// Again, same as publish
		$application['{c0385ef9-1828-4340-961a-e769a9f0a986}'] = array(
			'minVersion' => 0.1,
			'maxVersion' => 0.1
		);

        $validate = $this->Validation->validateTargetApplications($application);

        if (is_string($validate)) {
            // If a string is returned, there was an error
            return $this->_renderError(
				array(
					'reason' => 'No valid application was found for this tutorial'
				)
			);
        }
        else {
            // If an array is returned, there were no errors
            $addon['appversions'] = $validate;
        }

        // Unbind add-ons
        $this->Addon->unbindFully();

		// Make sure GUID doesn't exist already
		if ($existing = $this->Addon->findAll(array('Addon.guid' => $addon['Addon']['guid']), array('guid'))) {
			return $this->_renderError(
				array(
					'reason' => sprintf(___('This add-on ID (%1$s) already exists in the database. If this is your add-on, you can <a 		href="%2$s">upload a new version</a>.'), $addon['Addon']['guid'], $this->url("/developers/versions/add/{$existing[0]['Addon']['id']}"))
					)
			);
		}

        $addon['error'] = 0;

        // Save some additional data for later
        $addon['Addon']['id'] = $id;
        $addon['Version']['id'] = $this->data['Version']['id'];
        $addon['License'] = $this->data['License'];

        // Save this data for insertion if/when things pass
        $data = serialize($addon);
        $this->Amo->clean($data);

        $filename = $addon['File']['db']['filename'];
        $this->Amo->clean($filename);

        $this->TestResult->execute("INSERT INTO `test_results_cache` (`date`, `key`, `test_case_id`, `value`) VALUES (NOW(), '{$filename}', -1, '{$data}')");

		// Now, let's update the tutorial with public status
		$this->_updateTutorial($filename);
		
	}
	
	/**
	* Once everything is validated, publish the tutorial
	*
	*/
	function _registerTutorial($filename = '', $categories) {

        /**
         * Grab the data from the cache and unserialize it
         */
        $this->Amo->clean($filename);
        $data = $this->Addon->query("SELECT value FROM `test_results_cache` WHERE `key` = '{$filename}' AND `test_case_id` = -1");
        $data = $data[0]['test_results_cache']['value'];
        $this->Amo->unclean($data);
        $data = unserialize($data);

        /**
         * We're now ready to save the tutorial
         */
        $this->Addon->id = 0;
        $this->Addon->save($data['Addon']);
        $data['Addon']['id'] = $this->Addon->getLastInsertId();

		if ( !$data['Addon']['id'] ) {
			return $this->_renderError(
				array(
					'reason' => 'Could not save the addon.' . print_r($data)
				)
			);
		}

        /**
         * Add the logged in user as author
         */ 
        $this->Addon->saveAuthor($data['Addon']['id'], $this->auth_user['id']);

        $this->Addon->saveField('dev_agreement', 1);

        /**
         * Add Version number for this tutorial
         */ 
        $this->Version->id = 0;
        $data['Version']['addon_id'] = $data['Addon']['id'];
        $this->Version->save($data['Version']);
        $data['Version']['id'] = $this->Version->getLastInsertId();

        /**
         * Save appversions
         */ 
        if (!empty($data['appversions'])) {
            foreach ($data['appversions'] as $appversion) {
                $this->Version->addCompatibleApp($data['Version']['id'], $appversion['application_id'], $appversion['min'], $appversion['max']);
            }
        }

        /**
         * Move the file from the temp directory to the official
		 * tutorials directory and publish this file information to
		 * the DB.
         */
        $data['File']['db']['version_id'] = $data['Version']['id'];
        $platforms = $data['File']['db']['platform_id'];
        
		foreach ($platforms as $platform_id) {
            $this->File->id = 0;
            $data['File']['db']['platform_id'] = $platform_id;
            $validate = $this->Developers->moveFile($data);
            if (is_string($validate)) {
                
                return $this->_renderError(
					array(
						'reason' => $validate
					)
				);
				
            }

            $data['File']['db']['filename'] = $validate['filename'];
            $this->File->save($data['File']['db']);
            $file_id = $this->File->id;
        }

        /**
         * Remove the temps file that was stored on the file system
         */
        $tempFile = $data['File']['details']['path'];
        if (file_exists($tempFile)) {
            unlink($tempFile);
        }

		$addon_id = $data['Addon']['id'];
		
		/** 
		 * now get the newly created tutorial, associate it with
		 * categories and return it
		 */
		$this->_getTutorials(array($addon_id));
        if (isset($this->viewVars['addonsdata'][$addon_id])) {
	
			if (!empty($categories)) {
				
	            $this->Category->saveCategories($addon_id, $categories);

	            // flush cached add-on objects
	            if (QUERY_CACHE) $this->Addon->Cache->markListForFlush("addon:{$addon_id}");
			}
	
			//publish tutorial data to the view
            $this->_sendToView('tutorial', $this->viewVars['addonsdata'][$addon_id]);

	        // get real app names
	        $app_names = $this->Application->getIDList();
	        $this->_sendToView('app_names', $app_names);
	        $guids = array_flip($this->Application->getGUIDList());
	        $this->_sendToView('guids', $guids);
	        $this->_sendToView('api_version', $this->api_version);

        } else {
	
            $error = ___('Add-on not found!');
            $this->_sendToView('error', $error);

            return;

        }

    }


	function _updateTutorial($filename) {
		
		// Grab the data from our cache, and then de-serialize it
        $this->Amo->clean($filename);
        $data = $this->Addon->query("SELECT `value` FROM `test_results_cache` WHERE `key` = '{$filename}' AND `test_case_id` = -1");
        $data = $data[0]['test_results_cache']['value'];
        $this->Amo->unclean($data);
        $data = unserialize($data);

        $addon_id = $data['Addon']['id'];
        $version_id = $data['Version']['id'];

        $addon = $this->Addon->findById($addon_id);

        $this->Addon->save(array('Addon' => array('id' => $addon_id,
                                                  'dev_agreement' => 1)));
        // Add Version
        $this->Version->id = 0;
        $data['Version']['addon_id'] = $addon_id;
        $this->Version->save($data['Version']);
        $version_id = $this->Version->getLastInsertId();

        // If add-on is public, cancel any pending files
        if ($addon['Addon']['status'] == STATUS_PUBLIC) {
            $this->Addon->execute("UPDATE files SET status = ".STATUS_SANDBOX." WHERE files.version_id IN (SELECT id FROM versions WHERE versions.addon_id={$addon_id}) AND files.status = ".STATUS_PENDING);
        }

        // Save appversions
        if (!empty($data['appversions'])) {
            foreach ($data['appversions'] as $appversion) {
                $this->Version->addCompatibleApp($version_id, $appversion['application_id'], $appversion['min'], $appversion['max']);
            }
        }

        // Add Files
        $data['File']['db']['version_id'] = $version_id;
        $platforms = $data['File']['db']['platform_id'];

        // Make tutorial public
        $data['File']['db']['status'] = STATUS_PUBLIC;

        foreach ($platforms as $platform_id) {
            $this->File->id = 0;
            $data['File']['db']['platform_id'] = $platform_id;
            $validate = $this->Developers->moveFile($data);
            if (is_string($validate)) {
                return $this->_renderError(
					array(
						'reason' => 'Could not move file'
						)
				);
            }
            $data['File']['db']['filename'] = $validate['filename'];

            $this->File->save($data['File']['db']);
            $file_id = $this->File->id;

        }

        // Remove temp file
        $tempFile = $data['File']['details']['path'];
        if (file_exists($tempFile)) {
            unlink($tempFile);
        }
	}
 
	
	/**********************************************
	/**************** REVIEW PROCESS **************
	/*********************************************/
	
	function review($id) {
		
		$args = func_get_args();
        return $this->dispatchHttpMethod(array(
            'POST' => 'review_POST'
        ), $args);

	}

	/**
	* This function allow rating on activities for the authenticated user.
	*
	*/
	function review_POST($context, $id) {
		extract($context);
		
		/**
		 * The user has to be logged in to review a tutorial
		 */
		$this->_checkLoggedIn();
		
		/**
		 * First, search for the addon we want to rate
		 */ 
		$this->_getTutorials(array($id));
		
		/**
		 * Check if the tutorial we are looking for exist
		 * the viewVars is set via _getTutorials function
		 */ 
		if (isset($this->viewVars['addonsdata'][$id])) {
			
			/**
			 * The addon we want to rate is found
			 */ 
			$addon = $this->viewVars['addonsdata'][$id];
            $this->_sendToView('addon', $addon);

			/**
			 * 	Check if the current user owns this Addon.
			 *	A user can't review his own add-on.
			 */ 
			$isauthor = $this->_checkOwnership($id);
			
		    if($isauthor) {
				return $this->_renderError(
					array(
						'reason' => 'You cannot review your own tutorial'
					)
				);
		    }

			/**
			 * No error, start the review process
			 */
			$this->_saveOrUpdateReview($addon);

        } else {
	
            return $this->_renderError(
				array('reason' => 'Tutorial not found')
			);
        }
		
	}
	
	/**********************************************
	/****************** CATEGORIES ****************
	/*********************************************/
	
	/**
	 * Get all the categories in the store
	 */
	function categories() {
		
		$args = func_get_args();
        return $this->dispatchHttpMethod(array(
            'GET' => 'categories_GET'
        ), $args);

	}
	
	/**
	* Retrieves the available categories for Tutorius
	* Called using HTTP GET
	*/
	function categories_GET() {

        $categoryDescriptions = array();
        $sortedCategories = array();

        $addon_type = ADDON_TUTORIUS;
		$application = APP_TUTORIUS;
		
		$categories_db = $this->Category->findAll("Category.addontype_id={$addon_type} AND Category.application_id={$application}");

        $categories = array();
        if (!empty($categories_db)) {
			$index = 0;
            foreach ($categories_db as $category) {
	 			$categories[$index]['id'] = $category['Category']['id'];
				$categories[$index]['name'] = $category['Translation']['name']['string'];
				$categories[$index]['description'] = $category['Translation']['description']['string'];
				$index++;
            }
            asort($categories);
        }

        $this->_sendToView('categories', $categories);
        
	}
	
	
	/**********************************************
	/*************** HELPER FUNCTIONS *************
	/*********************************************/
	
	/**
	* This function execute the review process for a particular tutorial
	* 
	* @param $addon The addon we want to review
	*
	* @return Renders the appropriate view
	*/
	function _saveOrUpdateReview($addon) {
		global $valid_status;
		
		/**
		 * Create the Review array and map it with the POST variables
		 */ 
		$data['Review'] = $this->getParams(array(
            'rating' => '',
			'title' => '',
            'body'    => '',
			'id'	=> 0,
        ));
		
		// Add the new review or edit an existing review
        if (isset($data['Review'])) {
            $old_title = $data['Review']['title'];
            $old_body =  $data['Review']['body'];
            $this->Amo->clean($data['Review']);

            // validate rating
            if ($data['Review']['rating'] < 0 || $data['Review']['rating'] > 5) {
                $this->Review->invalidate('rating');
                return;
            }

			// Fill in basic details for the review
            $data['Review']['version_id'] = $this->Version->getVersionByAddonId($addon['Addon']['id'], $valid_status); // add version id to data array
            $data['Review']['user_id'] = $this->auth_user['id'];
            $data['Review']['editorreview'] = 0; // auto-approve review

            // if id is set for the review, check if it's valid
            if ($data['Review']['id'] !== 0) {
                $oldreview = $this->Review->find("Version.addon_id = {$addon['Addon']['id']} AND Review.user_id = {$this->auth_user['id']}");
                if (!isset($oldreview['Review']['id']) || $oldreview['Review']['id'] === $data['Review']['id'])
                    $this->Review->invalidate('id');
            }

			// Save information in DB
            if ($this->Review->save($data)) {
                //Log addon action for new reviews
                if (empty($data['Review']['id'])) {
                    //$this->Addonlog->logAddReview($this, $addon['Addon']['id'], $this->Review->getLastInsertID());
                }

                $this->Review->updateBayesianRating(array($addon['Addon']['id']));
				$this->_sendToView('success', true);
				
				// We return the saved review to the View
				$reviews = $this->Review->getReviews(array($this->Review->getLastInsertID()));
				$thisReview = $reviews[0];
				
				$this->_sendToView('review', $thisReview);
				
                return;

            } else {
                $data['Review']['title'] = $old_title;
                $data['Review']['body'] = $old_body;

                return $this->_renderError(
					array('reason' => 'There was an error while saving the review')
				);
            }
        }
		
	}


    /**
     * API specific publish
     * Uses XML encoding and is UTF-8 safe
     * @param mixed the data array (or string) to be html-encoded (by reference)
     * @param bool clean the array keys as well?
     * @return void
    */
    function _sendToView($viewvar, $value, $sanitizeme = true) {
        if ($sanitizeme) {
            if (is_array($value)) {
                $this->_sanitizeArrayForXML($value);
            } else {
                $tmp = array($value);
                $this->_sanitizeArrayForXML($tmp);
                $value = $tmp[0];
            }
        }
        $this->set($viewvar, $value);
    }

    /**
     * API specific sanitize
     * xml-encode an array, recursively
     * UTF-8 safe
     *
     * @param mixed the data array to be encoded
     * @param bool clean the array keys as well?
     * @return void
     */
    var $sanitize_patterns = array(
        "/\&/u", "/</u", "/>/u",
        '/"/u', "/'/u",
        '/[\cA-\cL]/u',
        '/[\cN-\cZ]/u',
     );
    var $sanitize_replacements = array(
        "&amp;", "&lt;", "&gt;",
        "&quot;", "&#39;",
        "",
        ""
    );
    var $sanitize_field_exceptions = array(
        'id'=>1, 'guid'=>1, 'addontype_id'=>1, 'status'=>1, 'higheststatus'=>1,
        'icontype'=>1, 'version_id'=>1, 'platform_id'=>1, 'size'=>1, 'hash'=>1,
        'codereview'=>1, 'password'=>1, 'emailhidden'=>1, 'sandboxshown'=>1,
        'averagerating'=>1, 'textdir'=>1, 'locale'=>1, 'locale_html'=>1,
        'created'=>1, 'modified'=>1, 'datestatuschanged'=>1
    );

    function _sanitizeArrayForXML(&$data, $cleankeys = false) {

        if (empty($data)) return;

        foreach ($data as $key => $value) {
            if (isset($this->sanitize_field_exceptions[$key])) {
                // @todo This if() statement is a temporary solution until we come up with
                // a better way of excluding fields from being sanitized.
                continue;
            } else if (empty($value)) {
                continue;
            } else if (is_array($value)) {
                $this->_sanitizeArrayForXML($data[$key], $cleankeys);
            } else {
                $data[$key] = preg_replace(
                    $this->sanitize_patterns,
                    $this->sanitize_replacements,
                    $data[$key]
                );
            }
        }

        // change the keys if necessary
        if ($cleankeys) {
            $keys = array_keys($data);
            $this->_sanitizeArrayForXML($keys, false);
            $data = array_combine($keys, array_values($data));
        }

    }

    /**
     * Render an HTTP status along with optional template and location.
     *
     * @param string HTTP status
     * @param string (optional) Name of a view to render
     * @param array  (optional) Vars to be published to the template
     * @param string (optional) URL for Location: header
     */
    function renderStatus($status, $view=null, $ns=null, $location=null) {
        $this->layout = ($view == 'empty') ? '' : 'rest';
        header('HTTP/1.1 ' . $status);
        if (!empty($ns)) foreach ($ns as $k=>$v)
            $this->_sendToView($k, $v);
        if (null !== $location)
            header('Location: '.$location);
        if (null !== $view)
            return $this->render($view);
    }

    /**
     * Dispatch to the appropriate handler based on HTTP method and a map of
     * handlers.
     */
    function dispatchHttpMethod($map, $args=NULL, $context=null) {

        if (null == $args) $args = array();
        if (null == $context) $context = array();

        $method = $this->getHttpMethod();

        if ('OPTIONS' == $method) {
            header('Allow: ' . join(', ', array_keys($map)));
            $this->_sendToView('methods', array_keys($map));
            return $this->render('options');
        }

        if (!isset($map[$method])) {
            return $this->renderStatus(
                self::STATUS_METHOD_NOT_ALLOWED, 'error',
                array('reason' => $method . '_not_allowed')
            );
        }

        return call_user_func_array(
            array($this, $map[$method]),
            array_merge(array($context), $args)
        );
    }

    /**
     * Grab named keys from POST parameters.  Missing parameters will be
     * set as null.
     *
     * @param array list of named parameters.
     */
    function getParams($list) {
        $params = array();
        $raw = array();
        if ($this->getHttpMethod() != 'PUT') {
            $raw = array_merge($_GET, $_POST);
        } else {
            $raw = array();
            if (!empty($_SERVER['CONTENT_LENGTH'])) {
                // HACK: $_POST isn't populated by PUT
                $data = file_get_contents('php://input');
                mb_parse_str($data, $raw);
            }
            $raw = array_merge($_GET, $raw);
        }
        foreach ($list as $name=>$default) {
            $params[$name] = isset($raw[$name]) ?
                $raw[$name] : $default;
        }
        return $params;
    }

    /**
     * Figure out the current HTTP method, with overrides accepted in a _method
     * parameter (GET/POST) or in an X_HTTP_METHOD_OVERRIDE header ala Google
     */
    function getHttpMethod() {
        if (!empty($_POST['_method']))
            return strtoupper($_POST['method']);
        if (!empty($_GET['_method']))
            return strtoupper($_GET['method']);
        if (!empty($_SERVER['X_HTTP_METHOD_OVERRIDE']))
            return strtoupper($_SERVER['X_HTTP_METHOD_OVERRIDE']);
        if (!empty($_SERVER['REQUEST_METHOD']))
            return strtoupper($_SERVER['REQUEST_METHOD']);
    }

    /**
     * Return whether the current HTTP method is a request to write in some
     * way.
     */
    function isWriteHttpMethod() {
        return in_array($this->getHttpMethod(), array('POST', 'DELETE', 'PUT'));
    }

    /**
     * If an if-modified-since header was provided, return a 304 if the
     * collection indeed has not been modified since the given time.
     */
    function isNotModifiedSince() {
        $since = @$_SERVER['HTTP_IF_MODIFIED_SINCE'];
        if ('GET' == $this->getHttpMethod() && $since) {
            if ($this->last_modified <= strtotime($since)) {
                return $this->renderStatus(
                    self::STATUS_NOT_MODIFIED, 'empty'
                );
            }
        }
    }

    /**
     * Standalone string sanitize for XML
     *
     * @param string
     * @return string
     */
    function sanitizeForXML($value) {
        return preg_replace(
            $this->sanitize_patterns,
            $this->sanitize_replacements,
            $value
        );
    }


	/**
	* Check if the current authenticated user has ownership
	* of the specified addon id
	*/
	function _checkOwnership($id) {
		
		$user_id = $this->auth_user['id'];
		
		//Check if user is an admin
        if ($this->SimpleAcl->actionAllowed('Admin', 'EditAnyAddon', $this->auth_user)) {
            return false;
        }
		
		// Query
		$results = $this->Addon->query("SELECT * FROM addons_users WHERE addon_id={$id} AND user_id={$user_id}");
		
		//check if user is an author of the add-on
		if ($results)
	    	return true;
	    else
	    	return false;
	}


	/** 
	* Get Addon details
	*
	* @param ids: Array containing ids of the addons we want
	*/
	function _getTutorials($ids) {

       $addonsdata = array();
       foreach ($ids as $id) {
        $_conditions = array(
            'Addon.id' => $id,
            'Addon.inactive' => 0,
            'Addon.addontype_id' => array(ADDON_TUTORIUS)
            );

        // get basic addon data
        // same criteria as used by the amo display action
        $this->Addon->bindOnly('User', 'Version', 'Tag', 'AddonCategory');
        $addon_data = $this->Addon->find($_conditions, null , null , 1);

        if (empty($addon_data)) {
            // this covers the case where we turned up something in the requested set that
            // was invalid for whatever reason.
            continue;
        }

        // get addon type
        $this_addon_type = $this->Addontype->findById($addon_data['Addon']['addontype_id']);
        $addon_data['Addon_type'] = $this_addon_type;

        $install_version
            = $this->Version->getVersionByAddonId($addon_data['Addon']['id'],
                                                  STATUS_PUBLIC);

        // find the addon version to report to user
        foreach ($addon_data['Version'] as $v) {
          if ($v['id'] == $install_version) {
            $addon_data['install_version'] = $v['version'];
            break;
          }
        }

        // get filename for install
        $fileinfo = $this->File->findAllByVersion_id(
            $install_version, null, null, null, null, 0);

        if (!is_array($fileinfo) || count($fileinfo)==0) {
            // don't return addons that don't have a valid
            // file associated with them
            continue;
        }

        // get compatible apps
        $compatible_apps = $this->Version->getCompatibleApps($install_version);
        $addon_data['Compatible_apps'] = $compatible_apps;


        // get compatible platforms

        foreach($fileinfo as &$file) {
            $this->Platform->unbindFully();
            $this_plat = $this->Platform->findById($file['Platform']['id']);
            $file['Platform']['apiname'] = $this_plat['Translation']['name']['string'];
            $platforms[] = $this_plat;
        }

        if ($this->api_version > 0 ) {
           // return an array of compatible os names
           // right now logic is still wrong, but this enables
           // xml changes and logic will be fixed later
           if (empty($platforms)) {
               $addon_data['all_compatible_os'] = array();
            } else {
                $addon_data['all_compatible_os'] = $platforms;
           }


        }

        // pull highlighted preview thumbnail url
        $addon_data['Thumbnail'] = $this->Image->getHighlightedPreviewURL($id);

        // the icon
        $addon_data['Icon'] = $this->Image->getAddonIconURL($id);

        $addon_data['fileinfo'] = $fileinfo;

        // add data to array
        $addonsdata[$id] = $addon_data;
       }

       $this->set('addonsdata' , $addonsdata);
	
    }

    /**
     * Return the current authenticated user, or return null and set 401
     * Unauthorized headers.
     *
     * @return mixed Authenticated user details.
     */
    function _getAuthUser() {
        $auth_user = null;

        // Check an auth header token
        if (null == $auth_user && !empty($_SERVER['HTTP_X_API_AUTH'])) {
            // Try accepting an API auth token in a header.
            $token = $_SERVER['HTTP_X_API_AUTH'];
            $auth_user = $this->ApiAuthToken->getUserForAuthToken($token);
 			$auth_user['token'] = $token;
        }

        return $auth_user;
    }

	/**
	* Returns a access denied "401 Unauthorized"
	* error when the user is not authenticated
	*/
	function _access_denied() {
		
		header('HTTP/1.1 401 Unauthorized');
        header('WWW-Authenticate: Basic realm="Tutorius API"');
        $this->_sendToView('reason', 'unauthorized');
        $this->_sendToView('href', $this->base_url . 'auth');
        $this->render('error');
        exit();
	}
	
	/**
	* This function check if the user is authenticated.
	* 
	*/
	function _checkLoggedIn( $admin = false ) {
		
		if (!$this->auth_user || ($admin && $this->SimpleAcl->actionAllowed('Admin', '%', $this->auth_user)))
			$this->_access_denied();
	}
	
	/**
     * Render the error view with an error message and details
     *
     */
    function _renderError($ns) {
        $this->layout = ('error' == 'empty') ? '' : 'rest';
        if (!empty($ns)) foreach ($ns as $k=>$v)
            $this->_sendToView($k, $v);

            return $this->render('error');
    }
}