-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
1456 lines (1144 loc) · 50 KB
/
Copy pathapi.php
File metadata and controls
1456 lines (1144 loc) · 50 KB
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
application/x-httpd-php api.php ( PHP script text )
<?php
/*
These information are used to connect to the database that manages the
stack maps.
*/
$DB_HOST = "localhost";
$DB_PORT = "3306";
$DB_USER = "zhenfwwh_stack-map-admin";
$DB_PASSWORD = "stack-map-admin";
$DB_NAME = "zhenfwwh_stack_maps";
// How long the user can be idle before access is revoked, in seconds.
$TOKEN_VALID_DURATION = 86400;
// The script execution starts here.
if (!isset( $_POST['request']) || empty($_POST['request'])) {
error("Invalid request.");
}
// Switching to a particular request.
$endpoints = array('login', 'create_library', 'create_floor',
'get_library_list', 'get_library', 'get_book_location', 'update_library',
'update_floor', 'update_floor_meta', 'delete_library', 'delete_floor');
$endpoint = $_POST['request'];
if (function_exists($endpoint) && in_array($endpoint, $endpoints, true)) {
$endpoint();
} else {
error("Invalid request.");
}
/**
This fetches username and password information from the form, then runs
custom credential checks. If successful, it creates a new token in the
database and returns it to the client.
Custom credential checks routed to third party should be executed here.
POST parameters:
'username': Username entered by the client.
'password': Password entered by the client.
Response format:
'success': Whether login was successful.
'error': The error message, if not successful.
'token': The token for this login, if successful. This is used as
quick credential checks for subsequent db modifications.
*/
function login() {
global $TOKEN_VALID_DURATION;
// Parse parameters.
$username = $_POST['username'];
$password = $_POST['password'];
// Open db connection.
$con = connect();
// Performs validation here. By default we have a username and password
// in the database. Replace with third party authentication if required.
$sql = 'SELECT * FROM user WHERE username = ? AND password = ?';
$result = get_data($con, $sql, 'ss', $username, $password);
if (count($result) != 1) {
error('login: Invalid login credentials.');
}
// If access is granted, we generate a unique token.
$token = '';
$token_check = true;
while ($token_check) {
$token = bin2hex(openssl_random_pseudo_bytes(32));
$sql = 'SELECT * FROM token WHERE token_body = ?';
$result = get_data($con, $sql, 's', $token);
$token_check = count($result) != 0;
}
// Store this token to the database along with a validity duration.
$expire_date = time() + $TOKEN_VALID_DURATION;
$sql = 'INSERT INTO token (token_body, expire_date) VALUES (?, ?)';
run_query($con, $sql, 'si', $token, $expire_date);
// Close db connection.
$con->close();
// Send response.
$response['success'] = TRUE;
$response['token'] = $token;
echo json_encode($response);
}
/**
This creates a library in the database and returns a success flag along
with the created library id.
POST parameters:
'token': Access token given from login.
'library_name': Name of the new library. This must be different from
existing names in the database.
Response format:
'success': Whether creation was successful.
'error': The error message, if not successful.
'id': The library_id of the newly created Library record in
the database.
*/
function create_library() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$name = $_POST['name'];
// Check if the name is already taken.
$sql = 'SELECT library_id FROM library WHERE library_name = ?';
if (count(get_data($con, $sql, 's', $name)) > 0) {
error("create_library: Library name is already taken.");
}
// Add the new library.
$sql = 'INSERT INTO library (library_name) VALUES (?)';
run_query($con, $sql, 's', $name);
// Fetch the newly created library id.
$sql = 'SELECT library_id FROM library ORDER BY library_id DESC LIMIT 1';
$result = get_data($con, $sql, '');
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
$response['id'] = $result[0]->library_id;
echo json_encode($response);
}
/**
This creates a floor in the database and returns a success flag along with
the created floor id. The newly created floor is empty.
POST parameters:
'token': Access token given from login.
'floor_name': Name of the new floor.
'floor_order': Order of the new floor. Essentially a number that serves to
order the floors. See database design document for details
on how this works.
'library_id': Id of the library in which the floor will be created in.
Response format:
'success': Whether creation was successful.
'error': The error message, if not successful.
'id': The floor_id of the newly created Floor record in the
database.
*/
function create_floor() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$floor_name = $_POST['floor_name'];
$floor_order = $_POST['floor_order'];
$library_id = $_POST['library_id'];
// Verify the library is valid.
$sql = 'SELECT library_id FROM library WHERE library_id = ?';
if (count(get_data($con, $sql, 'i', $library_id)) != 1) {
error('create_floor: Given library is not found.');
}
// Add the new floor.
$sql = 'INSERT INTO floor (floor_name, floor_order, library)
VALUES (?, ?, ?)';
run_query($con, $sql, 'sdi', $floor_name, $floor_order, $library_id);
// Fetch the newly created floor id.
$sql = 'SELECT floor_id FROM floor ORDER BY floor_id DESC LIMIT 1';
$result = get_data($con, $sql, '');
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
$response['id'] = $result[0]->floor_id;
echo json_encode($response);
}
/**
This fetches the current list of libraries from the database. Note that no
floor information is returned. Details of specific floor plans within a
library can be retrieved via get_library().
POST parameters:
None
Response format:
'success': Whether retrieval was successful.
'error': The error message, if not successful.
'data': An array of Libraries without floors property. Refer to the
JSON data format for more information.
*/
function get_library_list() {
// Fech library list.
$con = connect();
$sql = 'SELECT library_id, library_name FROM library';
$result = get_data($con, $sql, '');
// Close database connection.
$con->close();
// Send response.
$response['success'] = TRUE;
$response['data'] = $result;
echo json_encode($response);
}
/**
This fetches all information from a library, including details on its
floors' geometry and aisle data.
POST parameters:
'library_id': Id of the library to fetch information on.
Response format:
'success': Whether retrieval was successful.
'error': The error message, if not successful.
'data': A Library object. Refer to the JSON data format for more
information.
*/
function get_library() {
// Parse parameter.
$library_id = $_POST['library_id'];
// Verify the library is valid.
$con = connect();
$sql = 'SELECT * FROM library WHERE library_id = ?';
$result = get_data($con, $sql, 'i', $library_id);
if (count($result) != 1) {
error('get_library: Given library is not found.');
}
$library = $result[0];
// Fetch all floors for this library.
$sql = 'SELECT floor_id FROM floor WHERE library = ?';
$library['floors'] = get_data($con, $sql, 'i', $library_id);
for ($i = 0; $i < count($library['floors']); $i++) {
$fid = $library['floors'][$i]['floor_id'];
$library['floors'][$i] = get_floor($con, $fid);
}
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
$response['data'] = $library;
echo json_encode($response);
}
/**
This takes a book's call number and its located library and tries to locate
the exact aisle containing the book. It also provides the floor plan data
for that floor so a map can be drawn from it.
If multiple floors appear to contain the same book's call number, multiple
floors will be returned. It is up to the caller to decide on what to do
with the data.
The book's call number is stored as a string in the database, and it is in
this function that we interpret that string and compare it with the given
call number. This means that this is the function to modify if we want to
use another call number system or fine tune how the call numbers should be
parsed.
For different sizes, we use a simple suffix system to determine whether we
are in the same size. A call number will have zero or more '+' at the end,
which we can use to compare to the 'collection' property of the call range.
POST parameters:
'library_name': Name of the library to find the book from.
'call_number': The book's call number in a string representation. For
the format of this number in the current implementation,
refer to documentation on call number.
Response format:
'success': Whether retrieval was successful.
'error': The error message, if not successful.
'floors': A numeric array of Floor object. Refer to the JSON data
format for more information.
'aisles': A numeric array of associative arrays each containing
two elements, an 'aisle_id' and a 'side'. The former is
the id of the aisle containing the given call number.
The latter is present only if the aisle is double sided,
in which case 'side' identifies which side the book is
on. 0 indicates the book is on the left, 1 indicates the
book is on the right. Left and right are relative to the
local space of the stack (where we disregard its
rotation). At 0 rotation, a double sided aisle should
have short `width` and long height, with two rectangles:
one on the left and the other on the right.
*/
function get_book_location() {
// Parse parameters.
$call_number = $_POST['call_number'];
$library_name = $_POST['library_name'];
$collection = '';
if (preg_match('(\++$)', $call_number, $matches)) {
$collection = $matches[0];
}
// Verify the library is valid.
$con = connect();
$sql = 'SELECT * FROM library WHERE library_name = ?';
$result = get_data($con, $sql, 's', $library_name);
if (count($result) != 1) {
error('get_book_location: Given library is not found.');
}
$library = $result[0];
// Fetch all call number ranges in this library. collection = ? AND
$sql = 'SELECT *
FROM call_range
JOIN aisle ON call_range.aisle = aisle.aisle_id
WHERE
aisle IN
(SELECT aisle_id
FROM aisle
WHERE floor IN
(SELECT floor_id
FROM floor
WHERE library = ?
)
)';
$call_ranges = get_data($con, $sql, 'i', $library['library_id']);
$aisles = array();
$floor_ids = array();
// Parse each call number range to see if the given one falls within it.
foreach ($call_ranges as $call_range) {
$range_start = $call_range['call_start'];
$range_end = $call_range['call_end'];
if (compare_call_numbers($range_start, $call_number) <= 0 &&
compare_call_numbers($call_number, $range_end) < 0) {
// Call number is within this range.
$aisle_element['aisle_id'] = $call_range['aisle'];
if ($call_range['side'] !== NULL) {
$aisle_element['side'] = $call_range['side'];
}
// Add fid to the list of floors to fetch
$fid = $call_range['floor'];
if (!in_array($fid, $floor_ids)) {
$floor_ids[] = $fid;
}
// Add aisle element to array.
$aisles[] = $aisle_element;
}
}
if (count($aisles) == 0) {
error("get_book_location: The book is not found in this library.");
}
// Now fetch each floor.
$floors = array();
foreach ($floor_ids as $fid) {
$floors[] = get_floor($con, $fid);
}
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
$response['floors'] = $floors;
$response['aisles'] = $aisles;
echo json_encode($response);
}
/**
This updates a library's name. Note each library must have a unique name.
POST parameters:
'token': Access token given from login.
'library_id': Id of the library to perform the change to.
'library_name': New name of the library.
Response format:
'success': Whether retrieval was successful.
'error': The error message, if not successful.
*/
function update_library() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$new_name = $_POST['library_name'];
$library_id = $_POST['library_id'];
// Verify the change is valid.
$sql = 'SELECT * FROM library WHERE library_id = ? OR library_name = ?';
$result = get_data($con, $sql, 'is', $library_id, $new_name);
if (count($result) != 1) {
error('update_library: Given library is not found or name is taken.');
}
// Update library name.
$sql = 'UPDATE library SET library_name = ? WHERE library_id = ?';
$run_query($con, $sql, 'si', $new_name, $library_id);
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
echo json_encode($response);
}
/**
This updates a floor of a library. The floor includes aisles, call number
ranges in aisles, aisle areas, aisles in aisle areas, call number ranges in
aisles in aisle areas, landmarks, and walls.
POST parameters:
'token': Access token given from login.
'floor': Floor object encoded in JSON. Refer to the JSON data format
for more information.
Response format:
'success': Whether update was successful.
'error': The error message, if not successful.
*/
function update_floor() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$floor = json_decode($_POST['floor'], TRUE);
// Perform validation.
validate_floor($floor);
$floor_id = $floor['floor_id'];
// Verify the floor exists.
$sql = 'SELECT floor_id FROM floor WHERE floor_id = ?';
if (count(get_data($con, $sql, 'i', $floor_id)) != 1) {
error('update_floor: Given floor is not found.');
}
// Delete existing objects on the floor.
$sql = 'DELETE FROM wall WHERE floor = ?';
run_query($con, $sql, 'i', $floor_id);
$sql = 'DELETE FROM aisle WHERE floor = ?';
run_query($con, $sql, 'i', $floor_id);
$sql = 'DELETE FROM aisle_area WHERE floor = ?';
run_query($con, $sql, 'i', $floor_id);
$sql = 'DELETE FROM landmark WHERE floor = ?';
run_query($con, $sql, 'i', $floor_id);
// Add walls into the database.
if (array_key_exists('walls', $floor)) {
$sql = 'INSERT INTO wall (start_x, start_y, end_x, end_y, floor)
VALUES (?, ?, ?, ?, ?)';
foreach ($floor['walls'] as $wall) {
run_query($con, $sql, 'ddddi', $wall['start_x'],
$wall['start_y'], $wall['end_x'], $wall['end_y'], $floor_id);
}
}
// Add landmarks into the database.
if (array_key_exists('landmarks', $floor)) {
$sql = 'INSERT INTO landmark (landmark_type, center_x, center_y, width, height, rotation, floor)
VALUES (?, ?, ?, ?, ?, ?, ?)';
foreach ($floor['landmarks'] as $landmark) {
run_query($con, $sql, 'sdddddi', $landmark['landmark_type'],
$landmark['center_x'], $landmark['center_y'],
$landmark['width'], $landmark['height'],
$landmark['rotation'], $floor_id);
}
}
// Add aisles into the database.
if (array_key_exists('aisles', $floor)) {
$sql = 'INSERT INTO aisle (center_x, center_y, width, height, rotation, is_double_sided, floor)
VALUES (?, ?, ?, ?, ?, ?, ?)';
foreach ($floor['aisles'] as $aisle) {
run_query($con, $sql, 'dddddii', $aisle['center_x'],
$aisle['center_y'], $aisle['width'], $aisle['height'],
$aisle['rotation'], intval($aisle['is_double_sided']),
$floor_id);
// Insert call ranges.
if (array_key_exists('call_ranges', $aisle)) {
// Grab the id.
$sql2 = 'SELECT aisle_id FROM aisle ORDER BY aisle_id DESC LIMIT 1';
$aisle_id = get_data($con, $sql2, '')[0]['aisle_id'];
$sql3 = 'INSERT INTO call_range (collection, call_start, call_end, side, aisle)
VALUES (?, ?, ?, ?, ?)';
foreach ($aisle['call_ranges'] as $call_range) {
$side = 0;
if (array_key_exists('side', $call_range)) {
$side = $call_range['side'];
}
run_query($con, $sql3, 'sssii',
$call_range['collection'],
$call_range['call_start'], $call_range['call_end'],
$side, $aisle_id);
}
}
}
}
// Add aisle areas into the database.
if (array_key_exists('aisle_areas', $floor)) {
$sql = 'INSERT INTO aisle_area (center_x, center_y, width, height, rotation, floor)
VALUES (?, ?, ?, ?, ?, ?)';
foreach ($floor['aisle_areas'] as $aisle_area) {
run_query($con, $sql, 'dddddi', $aisle_area['center_x'],
$aisle_area['center_y'], $aisle_area['width'],
$aisle_area['height'], $aisle_area['rotation'], $floor_id);
if (array_key_exists('aisles', $aisle_area)) {
// Grab the id.
$sql2 = 'SELECT aisle_area_id FROM aisle_area ORDER BY aisle_area_id DESC LIMIT 1';
$aisle_area_id = get_data($con, $sql2, '')[0]['aisle_area_id'];
$sql3 = 'INSERT INTO aisle (center_x, center_y, width, height, rotation, is_double_sided, aisle_area, floor)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
foreach ($aisle_area['aisles'] as $aisle) {
run_query($con, $sql3, 'dddddiii', $aisle['center_x'],
$aisle['center_y'], $aisle['width'],
$aisle['height'], $aisle['rotation'],
intval($aisle['is_double_sided']), $aisle_area_id,
$floor_id);
// Insert call ranges.
if (array_key_exists('call_ranges', $aisle)) {
// Grab the id.
$sql4 = 'SELECT aisle_id FROM aisle ORDER BY aisle_id DESC LIMIT 1';
$aisle_id = get_data($con, $sql4, '')[0]['aisle_id'];
$sql5 = 'INSERT INTO call_range (collection, call_start, call_end, side, aisle)
VALUES (?, ?, ?, ?, ?)';
foreach ($aisle['call_ranges'] as $call_range) {
$side = 0;
if (array_key_exists('side', $call_range)) {
$side = $call_range['side'];
}
run_query($con, $sql5, 'sssii',
$call_range['collection'],
$call_range['call_start'],
$call_range['call_end'], $side, $aisle_id);
}
}
}
}
}
}
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
echo json_encode($response);
}
/**
This updates a floor's name and floor order within a library.
POST parameters:
'token': Access token given from login.
'floor_id': Id of the floor to perform the change to.
'floor_name': New name of the floor.
'floor_order': New order of the floor.
Response format:
'success': Whether update was successful.
'error': The error message, if not successful.
*/
function update_floor_meta() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$new_name = $_POST['floor_name'];
$new_order = $_POST['floor_order'];
$floor_id = $_POST['floor_id'];
// Verify the floor is valid.
$sql = 'SELECT * FROM floor WHERE floor_id = ?';
$result = get_data($con, $sql, 'i', $floor_id);
if (count($result) != 1) {
error('update_floor: Given floor is not found.');
}
// Update floor meta information.
$sql = 'UPDATE floor SET floor_name = ?, floor_order = ? WHERE floor_id = ?';
$run_query($con, $sql, 'si', $new_name, $new_order, $floor_id);
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
echo json_encode($response);
}
/**
This deletes a library and all floors associated with it. Deletions are not
recoverable.
POST parameters:
'token': Access token given from login.
'library_id': Id of the library to delete.
Response format:
'success': Whether deletion was successful.
'error': The error message, if not successful.
*/
function delete_library() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$library_id = $_POST['library_id'];
// Verify the floor is valid.
$sql = 'SELECT * FROM library WHERE library_id = ?';
$result = get_data($con, $sql, 'i', $library_id);
if (count($result) != 1) {
error('delete_library: Given library is not found.');
}
// Delete library.
$sql = 'DELETE FROM library WHERE library_id = ?';
$run_query($con, $sql, 'i', $library_id);
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
echo json_encode($response);
}
/**
This deletes a floor and all objects inside it. Deletions are not
recoverable.
POST parameters:
'token': Access token given from login.
'floor_id': Id of the floor to delete.
Response format:
'success': Whether deletion was successful.
'error': The error message, if not successful.
*/
function delete_floor() {
$con = connect();
// Check user credentials.
check_token($con, $_POST['token']);
// Parse parameters.
$floor_id = $_POST['floor_id'];
// Verify the floor is valid.
$sql = 'SELECT * FROM floor WHERE floor_id = ?';
$result = get_data($con, $sql, 'i', $floor_id);
if (count($result) != 1) {
error('update_floor: Given floor is not found.');
}
// Delete floor.
$sql = 'DELETE FROM floor WHERE floor_id = ?';
$run_query($con, $sql, 'i', $floor_id);
// Close database.
$con->close();
// Send response.
$response['success'] = TRUE;
echo json_encode($response);
}
//////////////////////
// HELPER FUNCTIONS //
//////////////////////
/**
Validates floor according to the specified JSON format. May report an error
if anything is not in the right format.
Arguments:
$floor: The floor that requires validation.
Return value:
Nothing if valid, an exception otherwise.
*/
function validate_floor($floor) {
if (array_key_exists('aisles', $floor)) {
// Parse all aisles
foreach ($floor['aisles'] as $aisle) {
validate_aisle($aisle);
}
}
if (array_key_exists('aisle_areas', $floor)) {
// Parse all aisle areas
foreach ($floor['aisle_areas'] as $aisle_area) {
validate_aisle_area($aisle_area);
}
}
if (array_key_exists('landmarks', $floor)) {
// Parse all landmarks
foreach ($floor['landmarks'] as $landmark) {
validate_landmark($landmark);
}
}
if (array_key_exists('walls', $floor)) {
// Parse all walls
foreach ($floor['walls'] as $wall) {
validate_wall($wall);
}
}
if (!array_key_exists('floor_id', $floor) || !is_int($floor['floor_id'])) {
error('validate_floor: incorrect or missing floor_id from floor object.');
}
if (!array_key_exists('floor_order', $floor) || !is_numeric($floor['floor_order'])) {
error('validate_floor: incorrect or missing floor_order from floor object.');
}
}
/**
Validates call number range according to the specified JSON format. Throws
an exception if the call numbers within the range are not in the right
format.
Arguments:
$call_range: The call number range that requires validation.
Return value:
Nothing if valid, exception otherwise.
*/
function validate_call_range($call_range) {
// First check if all keys exist, then check if the resulting call
// numbers are valid.
if (array_key_exists('call_start', $call_range) &&
is_string($call_range['call_start']) &&
array_key_exists('call_end', $call_range) &&
is_string($call_range['call_end']) &&
!(array_key_exists('collection', $call_range) &&
!is_string($call_range['collection'])) &&
!(array_key_exists('side', $call_range) &&
!is_string($call_range['side']) &&
!is_numeric($call_range['side']))) {
// We parse the numbers through convert_call_number. An error will
// be thrown if there are any errors.
$c1 = convert_call_number($call_range['call_start']);
$c2 = convert_call_number($call_range['call_end']);
if (compare_call_numbers($c1, $c2) >= 0) {
error("validate_call_range: call_start ($c1) is bigger or equal to call_end ($c2).");
}
} else {
error('validate_call_range: incorrect or missing keys from call_range object.');
}
}
/**
Validates aisle according to the specified JSON format. May report an error
if any call number within the ranges is not in the right format.
Arguments:
$aisle: The aisle that requires validation.
Return value:
TRUE if valid, FALSE or exception otherwise.
*/
function validate_aisle($aisle) {
// First check if all keys exist, then check if the resulting call
// numbers are valid.
validate_rect($aisle);
if (array_key_exists('is_double_sided', $aisle) &&
is_bool($aisle['is_double_sided'])) {
if (array_key_exists('call_ranges', $aisle)) {
foreach ($aisle['call_ranges'] as $call_range) {
validate_call_range($call_range);
}
}
} else {
error('validate_aisle: incorrect or missing keys from aisle object.');
}
}
/**
Validates aisle area according to the specified JSON format. May report an
error if any call number within the ranges within the aisles is not in the
right format.
Arguments:
$aisle_area: The aisle area that requires validation.
Return value:
TRUE if valid, FALSE or exception otherwise.
*/
function validate_aisle_area($aisle_area) {
// First check if all keys exist, then check if the resulting call
// numbers are valid.
validate_rect($aisle_area);
if (array_key_exists('aisles', $aisle_area)) {
foreach ($aisle_area['aisles'] as $aisle) {
validate_aisle($aisle);
}
}
}
/**
Validates landmark according to the specified JSON format.
Arguments:
$landmark: The landmark that requires validation.
Return value:
TRUE if valid, FALSE otherwise.
*/
function validate_landmark($landmark) {
validate_rect($landmark);
if (!array_key_exists('landmark_type', $landmark) ||
!is_string($landmark['landmark_type'])) {
error('validate_landmark: incorrect or missing keys from landmark object.');
}
}
/**
Validates a wall according to the specified JSON format.
Arguments:
$wall: The wall object that requires validation.
Return value:
TRUE if valid, FALSE otherwise.
*/
function validate_wall($wall) {
if (!(array_key_exists('start_x', $wall) &&
is_numeric($wall['start_x']) &&
array_key_exists('start_y', $wall) &&
is_numeric($wall['start_y']) &&
array_key_exists('end_x', $wall) &&
is_numeric($wall['end_x']) &&
array_key_exists('end_y', $wall) &&
is_numeric($wall['end_y']))) {
error('validate_wall: incorrect or missing keys from wall object.');
}
}
/**
Validates rectangle (which underlies all of our geometry apart from walls)
according to the specified JSON format. This checks whether the given
object has 'center_x', 'center_y', 'width', 'height' and 'rotation' keys
with appropriate types.
Arguments:
$rect: The object that requires validation.
Return value:
TRUE if valid, FALSE otherwise.
*/
function validate_rect($rect) {
if (!(array_key_exists('center_x', $rect) &&
is_numeric($rect['center_x']) &&
array_key_exists('center_y', $rect) &&
is_numeric($rect['center_y']) &&
array_key_exists('width', $rect) &&
is_numeric($rect['width']) &&
array_key_exists('height', $rect) &&
is_numeric($rect['height']) &&
array_key_exists('rotation', $rect) &&
is_numeric($rect['rotation']))) {
error('validate_rect: incorrect or missing keys from rect object.');
}
}
/**
Converts a normal, non-spaced library of congress call number to a spaced
version. If the call number is invalid, this tries to construct a call
number from parts that are valid. However, it expects at least the class to
be valid.
This can also be used to check if a spaced call number is valid. If it is
valid, this acts as the identity function. Otherwise throws an error.
Arguments:
$call_number: The call number to convert, assumed to be in standard
library of congress format. Refer to documentation on call
number for more information.
Return value:
The given call number with spaces added between its parts.
*/
function convert_call_number($call_number) {
/*
Format of input: ClassSubclassCutter1Cutter2, where:
Class consists of LETTERS
Subclass consists of DECIMAL NUMBER with decimal part optional
Cutter1, Cutter2 consist of a DOT, followed by LETTERS, then NUMBERS.
So by using regular expression, we can get:
Class by ^[A-Z]+
Subclass by [0-9]*\.?[0-9]+