-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathdirection.class.php
More file actions
1314 lines (1184 loc) · 55 KB
/
Copy pathdirection.class.php
File metadata and controls
1314 lines (1184 loc) · 55 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
<?php
/**
* File for directions
*
* @package eFront
*/
//This file cannot be called directly, only included.
if (str_replace(DIRECTORY_SEPARATOR, "/", __FILE__) == $_SERVER['SCRIPT_FILENAME']) {
exit;
}
/**
* Direction exceptions
*
* This class extends Exception to provide the exceptions related to directions
* @package eFront
* @since 3.5.0
*
*/
class EfrontDirectionException extends Exception
{
/**
* The direction requested does not exist
* @since 3.5.0
*/
const DIRECTION_NOT_EXISTS = 1051;
/**
* The id provided is not valid, for example it is not a number or it is 0
* @since 3.5.0
*/
const INVALID_ID = 1052;
/**
* The category is not empty
* @since 3.5.4
*/
const NOT_EMPTY_CATEGORY = 1052;
/**
* An unspecific error
* @since 3.5.0
*/
const GENERAL_ERROR = 1099;
}
/**
* This class represents a direction in eFront
*
* @package eFront
* @since 3.5.0
*/
class EfrontDirection extends ArrayObject
{
/**
* The maximum length for direction names. After that, the names appear truncated
*/
const MAXIMUM_NAME_LENGTH = 50;
/**
* Instantiate direction
*
* This function is the class constructor, which instantiates the
* EfrontDirection object, based on the direction values
* <br/>Example:
* <code>
* $direction_array = eF_getTableData("directions", "*", "id=4");
* $direction = new EfrontDirection($direction_array[0]);
* </code>
*
* @param array $array The direction values
* @since 3.5.0
* @access public
*/
function __construct($direction) {
if (!is_array($direction)) {
if (!eF_checkParameter($direction, 'id')) {
throw new EfrontLessonException(_INVALIDID.': '.$direction, EfrontDirectionException :: INVALID_ID);
}
$result = eF_getTableData("directions", "*", "id=".$direction);
if (sizeof($result) == 0) {
throw new EfrontLessonException(_CATEGORYDOESNOTEXIST.': '.$direction, EfrontDirectionException :: DIRECTION_NOT_EXISTS);
}
$direction = $result[0];
}
parent :: __construct($direction);
}
/**
* Persist changed values
*
* This function is used to persist the direction values
* <br/>Example:
* <code>
* $direction_array = eF_getTableData("directions", "*", "id=4");
* $direction = new EfrontDirection($direction_array[0]);
* $direction['name'] = 'new name';
* $direction -> persist();
* </code>
*
* @since 3.5.0
* @access public
*/
function persist() {
foreach (new EfrontAttributesOnlyFilterIterator($this -> getIterator()) as $key => $value) {
$fields[$key] = $value;
}
eF_updateTableData("directions", $fields, "id=".$fields['id']);
}
/**
* Delete a direction
* This function is used to delete the current direction
* <br/>Example:
* <code>
* $direction_array = eF_getTableData("directions", "*", "id=4");
* $direction = new EfrontDirection($direction_array[0]);
* $direction -> delete();
* </code>
*
* @since 3.5.0
* @access public
*/
function delete() {
foreach (new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($this)), 'id') as $key => $value) {
eF_deleteTableData("directions", "id=".$value); //Delete Units from database
eF_updateTableData("lessons", array("directions_ID" => 0), "directions_ID=".$value);
eF_updateTableData("courses", array("directions_ID" => 0), "directions_ID=".$value);
}
}
/**
* Get direction's lessons
*
* This function is used to get the lessons that belong
* to this direction.
* <br/>Example:
* <code>
* $lessons = $direction -> getLessons();
* </code>
*
* @param boolean $returnObjects Whether to return EfrontLesson objects or a simple array
* @param boolean $subDirections Whether to return subDirections lessons as well
* @return array An array of lesson ids/names pairs or EfrontLesson objects
* @since 3.5.0
* @access public
*/
function getLessons($returnObjects = false, $subDirections = false) {
if (!$subDirections) {
$result = eF_getTableData("lessons", "id, name", "instance_source = 0 and archive = 0 && directions_ID=".$this['id']);
} else {
$directions = new EfrontDirectionsTree();
$children = $directions -> getNodeChildren($this['id']);
foreach (new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($children)), array('id')) as $value) {
$siblings[] = $value;
}
$result = eF_getTableData("lessons", "id, name", "instance_source = 0 and archive = 0 && directions_ID in (".implode(",", $siblings).")");
}
$lessons = array();
foreach ($result as $value) {
$returnObjects ? $lessons[$value['id']] = new EfrontLesson($value['id']) : $lessons[$value['id']] = $value['name'];
}
return $lessons;
}
/**
* Get direction's courses
*
* This function is used to get the courses that belong
* to this direction.
* <br/>Example:
* <code>
* $courses = $direction -> getCourses();
* </code>
*
* @param boolean $returnObjects Whether to return EfrontCourse objects or a simple array
* @param boolean $subDirections Whether to return subDirections courses as well
* @return array An array of course ids/names pairs or EfrontCourse objects
* @since 3.5.0
* @access public
*/
function getCourses($returnObjects = false, $subDirections = false) {
if (!$subDirections) {
$result = eF_getTableData("courses", "id, name", "archive = 0 && instance_source = 0 && directions_ID=".$this['id']);
} else {
$directionsTree = new EfrontDirectionsTree();
$children = $directionsTree -> getNodeChildren($this['id']);
foreach (new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($children)), array('id')) as $value) {
$siblings[] = $value;
}
$result = eF_getTableData("courses", "id, name", "archive = 0 && instance_source = 0 && directions_ID in (".implode(",", $siblings).")");
}
$courses = array();
foreach ($result as $value) {
$returnObjects ? $courses[$value['id']] = new EfrontCourse($value['id']) : $courses[$value['id']] = $value['name'];
}
return $courses;
}
/**
* Create direction
*
* This function is used to create a new direction
* <br/>Example:
* <code>
* $fields = array('name' => 'new direction');
* EfrontDirection :: createDirection($fields);
* </code>
*
* @param array $fields The new direction's fields
* @return EfrontDirection The new direction
* @since 3.5.0
* @access public
* @static
*/
public static function createDirection($fields = array()) {
!isset($fields['name']) ? $fields['name'] = 'Default direction' : null;
$newId = eF_insertTableData("directions", $fields);
$result = eF_getTableData("directions", "*", "id=".$newId); //We perform an extra step/query for retrieving data, sinve this way we make sure that the array fields will be in correct order (forst id, then name, etc)
$direction = new EfrontDirection($result[0]);
return $direction;
}
/**
* Delete category (statically)
*
* This function is used to delete an existing category.
* This function is the same as EfrontDirection :: delete(),
* except that it is called statically
* <br/>Example:
* <code>
* try {
* EfrontDirection :: delete(32); //32 is the category id
* } catch (Exception $e) {
* echo $e -> getMessage();
* }
* </code>
*
* @param mixed $category The category id or a category object
* @return boolean True if everything is ok
* @since 3.5.0
* @access public
* @static
*/
public static function deleteDirection($category) {
if (!($category instanceof EfrontDirection)) {
$category = new EfrontDirection($category);
}
return $category -> delete();
}
}
/**
* This class represents the directions tree and extends EfrontTree class
* @package eFront
* @since 3.5.0
*/
class EfrontDirectionsTree extends EfrontTree
{
/**
* Initialize tree
*
* This function is used to initialize the directions tree
* <br/>Example:
* <code>
* $directionsTree = new EfrontDirectionsTree();
* </code>
*
* @since 3.5.0
* @access public
*/
function __construct() {
$this -> reset();
}
/**
* Reset/initialize directions tree
*
* This function is used to initialize or reset the directions tree
* <br/>Example:
* <code>
* $directionsTree = new EfrontDirectionsTree();
* $directionsTree -> reset();
* </code>
*
* @since 3.5.0
* @access public
*/
public function reset() {
$directions = eF_getTableData("directions", "*", "", "name");
if (sizeof($directions) == 0) {
$this -> tree = new RecursiveArrayIterator(array());
return;
}
foreach ($directions as $node) { //Assign previous direction ids as keys to the previousNodes array, which will be used for sorting afterwards
$nodes[$node['id']] = new EfrontDirection($node); //We convert arrays to array objects, which is best for manipulating data through iterators
}
$rejected = array();
$tree = $nodes;
$count = 0; //$count is used to prevent infinite loops
while (sizeof($tree) > 1 && $count++ < 1000) { //We will merge all branches under the main tree branch, the 0 node, so its size will become 1
foreach ($nodes as $key => $value) {
if ($value['parent_direction_ID'] == 0 || in_array($value['parent_direction_ID'], array_keys($nodes))) { //If the unit parent is in the $nodes array keys - which are the unit ids- or it is 0, then it is valid
$parentNodes[$value['parent_direction_ID']][] = $value; //Find which nodes have children and assign them to $parentNodes
$tree[$value['parent_direction_ID']][$value['id']] = array(); //We create the "slots" where the node's children will be inserted. This way, the ordering will not be lost
} else {
$rejected = $rejected + array($value['id'] => $value); //Append units with invalid parents to $rejected list
unset($nodes[$key]); //Remove the invalid unit from the units array, as well as from the parentUnits, in case a n entry for it was created earlier
unset($parentNodes[$value['parent_direction_ID']]);
}
}
if (isset($parentNodes)) { //If the unit was rejected, there won't be a $parentNodes array
$leafNodes = array_diff(array_keys($nodes), array_keys($parentNodes)); //Now, it's easy to see which nodes are leaf nodes, just by subtracting $parentNodes from the whole set
foreach ($leafNodes as $leaf) {
$parent_id = $nodes[$leaf]['parent_direction_ID']; //Get the leaf's parent
$tree[$parent_id][$leaf] = $tree[$leaf]; //Append the leaf to its parent's tree branch
unset($tree[$leaf]); //Remove the leaf from the main tree branch
unset($nodes[$leaf]); //Remove the leaf from the nodes set
}
unset($parentNodes); //Reset $parentNodes; new ones will be calculated at the next loop
}
}
if (sizeof($tree) > 0 && !isset($tree[0])) { //This is a special case, where only one node exists in the tree
$tree = array($tree);
}
foreach ($tree as $key => $value) {
if ($key != 0) {
$rejected[$key] = $value;
}
}
if (sizeof($rejected) > 0) { //Append rejected nodes to the end of the tree array, updating their parent/previous information
foreach ($rejected as $key => $value) {
eF_updateTableData("directions", array("parent_direction_ID" => 0), "id=".$key);
$value['parent_direction_ID'] = 0;
$tree[0][] = $value;
}
}
$this -> tree = new RecursiveArrayIterator($tree[0]);
}
/**
* Experimental function for merging lessons and courses to the main tree
*
*/
public function reset2() {
$directions = eF_getTableData("directions", "*", "", "name");
$result = eF_getTableData("lessons", "*");
$lessons = array();
foreach ($result as $value) {
$lessons[$value['directions_ID']][] = new EfrontLesson($value);
}
$result = eF_getTableData("courses", "*");
$courses = array();
foreach ($result as $value) {
$courses[$value['directions_ID']][] = new EfrontCourse($value);
}
if (sizeof($directions) == 0) {
$this -> tree = new RecursiveArrayIterator(array());
return;
}
foreach ($directions as $node) { //Assign previous direction ids as keys to the previousNodes array, which will be used for sorting afterwards
$nodes[$node['id']] = new EfrontDirection($node); //We convert arrays to array objects, which is best for manipulating data through iterators
$nodes[$node['id']]['lessons'] = $lessons[$node['id']];
$nodes[$node['id']]['courses'] = $lessons[$node['id']];
}
$rejected = array();
$tree = $nodes;
$count = 0; //$count is used to prevent infinite loops
while (sizeof($tree) > 1 && $count++ < 1000) { //We will merge all branches under the main tree branch, the 0 node, so its size will become 1
foreach ($nodes as $key => $value) {
if ($value['parent_direction_ID'] == 0 || in_array($value['parent_direction_ID'], array_keys($nodes))) { //If the unit parent is in the $nodes array keys - which are the unit ids- or it is 0, then it is valid
$parentNodes[$value['parent_direction_ID']][] = $value; //Find which nodes have children and assign them to $parentNodes
$tree[$value['parent_direction_ID']][$value['id']] = array(); //We create the "slots" where the node's children will be inserted. This way, the ordering will not be lost
} else {
$rejected = $rejected + array($value['id'] => $value); //Append units with invalid parents to $rejected list
unset($nodes[$key]); //Remove the invalid unit from the units array, as well as from the parentUnits, in case a n entry for it was created earlier
unset($parentNodes[$value['parent_direction_ID']]);
}
}
if (isset($parentNodes)) { //If the unit was rejected, there won't be a $parentNodes array
$leafNodes = array_diff(array_keys($nodes), array_keys($parentNodes)); //Now, it's easy to see which nodes are leaf nodes, just by subtracting $parentNodes from the whole set
foreach ($leafNodes as $leaf) {
$parent_id = $nodes[$leaf]['parent_direction_ID']; //Get the leaf's parent
$tree[$parent_id][$leaf] = $tree[$leaf]; //Append the leaf to its parent's tree branch
unset($tree[$leaf]); //Remove the leaf from the main tree branch
unset($nodes[$leaf]); //Remove the leaf from the nodes set
}
unset($parentNodes); //Reset $parentNodes; new ones will be calculated at the next loop
}
}
if (sizeof($tree) > 0 && !isset($tree[0])) { //This is a special case, where only one node exists in the tree
$tree = array($tree);
}
foreach ($tree as $key => $value) {
if ($key != 0) {
$rejected[$key] = $value;
}
}
if (sizeof($rejected) > 0) { //Append rejected nodes to the end of the tree array, updating their parent/previous information
foreach ($rejected as $key => $value) {
eF_updateTableData("directions", array("parent_direction_ID" => 0), "id=".$key);
$value['parent_direction_ID'] = 0;
$tree[0][] = $value;
}
}
$this -> tree = new RecursiveArrayIterator($tree[0]);
}
/**
* Insert node to the tree
*
* @param mixed $node
* @param mixed $parentNode
* @param mixed $previousNode
* @since 3.5.0
* @access public
*/
public function insertNode($node, $parentNode = false, $previousNode = false) {}
/**
* Remove node from tree
*
* @param mixed $node
* @since 3.5.0
* @access public
*/
public function removeNode($node) {}
/**
* Return an array of lesson ids, corresponding to the lessons of this categories tree
*
* @param array $lessons The lessons list
* @return array The lesson ids list
* @since 3.6.3
* @access public
*/
public function getLessonsList($lessons = array()) {
$lessonsList = array();
$iterator = $this -> initializeIterator(false, $lessons, $courses);
foreach ($iterator as $key => $value) {
foreach($value -> offsetGet('lessons') as $id) {
$lessonsList[] = $id;
}
}
return $lessonsList;
}
/**
* Print an HTML representation of the directions tree
*
* This function is used to print an HTML representation of the HTML tree
* <br/>Example:
* <code>
* $directionsTree -> toHTML(); //Print directions tree
* </code>
* Possible options are:
* - lessons_link //a value of '#user_type#' inside the url will be replaced with the user type
* - courses_link //a value of '#user_type#' inside the url will be replaced with the user typed
* - tooltip
* - search //display the search box (true/false)
* - tree_tools //Whether to display the top div with tree tools, show/hide and search (true/false)
* - url //A url to search ajax functions for. defaults to current url
* - collapse //Whether to start with categories collapsed
* - buy_link //Whether to display "buy" (add to cart) links
*
* @param RecursiveIteratorIterator $iterator An optional custom iterator
* @param array $lessons An array of EfrontLesson Objects
* @param array $courses An array of EfrontCourse Objects
* @param array $userInfo Optional information for the user accessing the tree
* @param array $options display options for the tree
* @return string The HTML version of the tree
* @since 3.5.0
* @access public
*/
public function toHTML($iterator = false, $lessons = false, $courses = false, $userInfo = array(), $options = array()) {
$options = $this -> parseTreeOptions($options);
$parsedLessons = $this -> parseTreeLessons($lessons);
$parsedCourses = $this -> parseTreeCourses($courses);
if (!empty($parsedCourses) || !empty($parsedLessons)) {
$originalLessons = $lessons;
$lessons = $parsedLessons;
$courses = $parsedCourses;
}
$totalEntries = sizeof($parsedLessons)+sizeof($parsedCourses);
$iterator = $this -> initializeIterator($iterator, $lessons, $courses, $options);
$current = $iterator -> current();
$treeStrings = array();
list($display, $display_lessons, $imageString, $classString) = $this -> getTreeDisplaySettings($options, $totalEntries);
$lessonsString = $coursesString = '';
while ($iterator -> valid()) {
$lessonsString = $this -> printCategoryLessons($iterator, $display_lessons, $options, $lessons);
$coursesString = $this -> printCategoryCourses($iterator, $display, $userInfo, $options, $courses, $lessons, $originalLessons);
// if ($lessonsString || $coursesString) {
$treeStrings[] = $this -> printCategoryTitle($iterator, $display, $imageString, $classString);
$treeStrings[] = $lessonsString.$coursesString.
</table>';
// }
$iterator -> next();
}
if (!empty($treeStrings)) {
$treeString =
<div id = "directions_tree">'.implode("", $treeStrings);
if ($options['tree_tools']) {
$treeString = $this -> printTreeTools($options, $totalEntries).$treeString; //This is put at the end, so that $this -> hasLessonsAsStudent is populated
}
$treeString .= "</div>";
return $treeString;
} else {
return '';
}
}
private function parseTreeOptions($options) {
//!isset($options['show_cart']) ? $options['show_cart'] = false : null;
//!isset($options['information']) ? $options['information'] = false : null;
!isset($options['lessons_link']) ? $options['lessons_link'] = false : null;
!isset($options['courses_link']) ? $options['courses_link'] = false : null;
!isset($options['tooltip']) ? $options['tooltip'] = true : null;
!isset($options['search']) ? $options['search'] = false : null;
!isset($options['catalog']) ? $options['catalog'] = false : null;
!isset($options['tree_tools']) ? $options['tree_tools'] = true : null;
!isset($options['url']) ? $options['url'] = $_SERVER['REQUEST_URI'] : null; //Pay attention since REQUEST_URI is empty if accessing index.php with the url http://localhost/
!isset($options['course_lessons']) ? $options['course_lessons'] = true : null;
return $options;
}
private function parseTreeLessons($lessons) {
if ($lessons === false) { //If a lessons list is not specified, get all active lessons
$result = eF_getTableData("lessons", "*", "archive = 0 && active=1", "name"); //Get all lessons at once, thus avoiding looping queries
foreach ($result as $value) {
$lessons[$value['id']] = new EfrontLesson($value); //Create an array of EfrontLesson objects
}
}
$roles = EfrontLessonUser :: getLessonsRoles();
foreach ($lessons as $key => $treeLesson) {
if (isset($treeLesson -> lesson['user_type']) && $treeLesson -> lesson['user_type']) {
$roleInLesson = $treeLesson -> lesson['user_type'];
$roleBasicType = $roles[$roleInLesson]; //Indicates that this is a catalog with user data
if ($roleBasicType == 'student') {
$this -> hasLessonsAsStudent = true;
}
} else {
$roleBasicType = null;
}
if ($_COOKIE['display_all_courses'] == '0' && $roleBasicType == 'student' && ($treeLesson -> lesson['completed'] || (!is_null($treeLesson -> lesson['remaining']) && $treeLesson -> lesson['remaining'] <= 0))) {
unset($lessons[$key]);
} else {
$lessonNames[$key] = $treeLesson -> lesson['name'];
}
}
asort($lessonNames);
foreach ($lessonNames as $key => $foo) {
$temp[$key] = $lessons[$key];
}
$lessons = $temp;
return $lessons;
}
private function parseTreeCourses($courses) {
if ($courses === false) { //If a courses list is not specified, get all active courses
$result = eF_getTableData("courses", "*", "archive = 0 && active=1", "name"); //Get all courses at once, thus avoiding looping queries
foreach ($result as $value) {
$courses[$value['id']] = new EfrontCourse($value); //Create an array of EfrontCourse objects
}
}
$roles = EfrontLessonUser :: getLessonsRoles();
foreach ($courses as $key => $treeCourse) {
if (isset($treeCourse -> course['user_type']) && $treeCourse -> course['user_type']) {
$roleInCourse = $treeCourse -> course['user_type'];
$roleBasicType = $roles[$roleInCourse]; //Indicates that this is a catalog with user data
if ($roleBasicType == 'student') {
$this -> hasLessonsAsStudent = true;
}
} else {
$roleBasicType = null;
}
if ($_COOKIE['display_all_courses'] == '0' && $roleBasicType == 'student' && ($treeCourse -> course['completed'] || (!is_null($treeCourse -> course['remaining']) && $treeCourse -> course['remaining'] <= 0))) {
unset($courses[$key]);
}
}
return $courses;
}
private function initializeIterator($iterator, $lessons, $courses, $options) {
if (!$iterator) {
$iterator = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($this -> tree), RecursiveIteratorIterator :: SELF_FIRST));
}
$iterator = $this -> filterOutEmptyCategories($iterator, $lessons, $courses, $options);
$iterator = new EfrontNodeFilterIterator($iterator, array('hasNodes' => true)); //Filter in only tree nodes that have the 'hasNodes' attribute
$iterator -> rewind();
return $iterator;
}
private function filterOutEmptyCategories($iterator, $lessons, $courses, $options) {
$directionsLessons = array();
foreach ($lessons as $id => $lesson) {
if ($options['catalog'] && !$lesson -> lesson['show_catalog']) { //Remove inactive lessons
unset($lessons[$id]);
} elseif (!$lesson -> lesson['course_only']) { //Lessons in courses will be handled by the course's display method, so remove them from the list
$directionsLessons[$lesson -> lesson['directions_ID']][] = $id; //Create an intermediate array that maps lessons to directions
}
}
$directionsCourses = array();
foreach ($courses as $id => $course) {
$displayCatalogEntry[$course -> course['id']] = $course -> shouldDisplayInCatalog();
if ($options['catalog'] && !$displayCatalogEntry[$course -> course['id']]) { //Remove inactive courses
unset($courses[$id]);
} else {
if ($courses[$id] -> course['instance_source']) {
$instanceSource = new EfrontCourse($courses[$id] -> course['instance_source']);
$directionsCourses[$instanceSource -> course['directions_ID']][] = $id; //Course instances don't have a directions on their own
} else {
$directionsCourses[$course -> course['directions_ID']][] = $id; //Create an intermediate array that maps courses to directions
}
}
}
//We need to calculate which categories will be displayed. We will keep only categories that have lessons or courses and their parents. In order to do so, we traverse the categories tree and set the 'hasNodes' attribute to the nodes that will be kept
foreach ($iterator as $key => $value) {
if (isset($directionsLessons[$value['id']]) || isset($directionsCourses[$value['id']])) {
$count = $iterator -> getDepth();
$value['hasNodes'] = true;
isset($directionsLessons[$value['id']]) ? $value['lessons'] = $directionsLessons[$value['id']] : null; //Assign lessons ids to the direction
isset($directionsCourses[$value['id']]) ? $value['courses'] = $directionsCourses[$value['id']] : null; //Assign courses ids to the direction
while ($count) {
$node = $iterator -> getSubIterator($count--);
$node['hasNodes'] = true; //Mark "keep" all the parents of the node
}
}
}
return $iterator;
}
private function printTreeTools($options, $totalEntries) {
if (!isset($_COOKIE['display_all_courses'])) {
setcookie('display_all_courses', 1);
}
$searchString = '';
if ($options['search']) {
$searchString = '<input type = "text" name = "search_text" value = "'._SEARCH.'" onclick="if(this.value==\''._SEARCH.'\')this.value=\'\';" onblur="if(this.value==\'\')this.value=\''._SEARCH.'\';" class = "searchBox_catalog" onKeyPress = "if (event.keyCode == 13) {filterTree(this, \''.$options['url'].'\')}" />';
}
$treeString =
<div style = "padding-top:12px;padding-bottom:12px" class = "lessons_list">
'.$searchString;
$hideCollapseAll = $hideExpandAll = '';
//if (isset($options['collapse']) && $options['collapse'] || (isset($_COOKIE['collapse_catalog']) && $_COOKIE['collapse_catalog'] && !isset($options['collapse']))) {
if (($options['collapse'] && !isset($_COOKIE['collapse_catalog'])) || ($options['collapse'] && $_COOKIE['collapse_catalog'] == 1) || (isset($_COOKIE['collapse_catalog']) && $_COOKIE['collapse_catalog'])) {
$hideCollapseAll = 'style = "display:none"';
} else {
$hideExpandAll = 'style = "display:none"';
}
if ($totalEntries <= 10) {
$hideCollapseAll = $hideExpandAll = 'style = "display:none"';
}
$treeString .=
<a href = "javascript:void(0)" onclick = "showAll()" id = "catalog_show_all" '.$hideExpandAll.'>'._EXPANDALL.'</a>
<a href = "javascript:void(0)" onclick = "hideAll()" id = "catalog_hide_all" '.$hideCollapseAll.'>'._COLLAPSEALL.'</a>';
if ($options['only_progress_link'] && $this -> hasLessonsAsStudent) {
if ($totalEntries > 10) {
$treeString .= ' | ';
}
$treeString .=
<select onchange = "setCookie(\'display_all_courses\', this.options[this.options.selectedIndex].value);location=location">
<option value = "0">'._MATERIALINPROGRESS.'</option>
<option value = "1" '.($_COOKIE['display_all_courses'] == '1' ? 'selected' : '').'>'._ALLMATERIAL.'</option>
</select>';
}
return $treeString.'</div>';
}
private function printProgressBar($treeLesson, $roleBasicType) {
$treeString = '';
if ($roleBasicType == 'student' && $treeLesson -> lesson['completed']) { //Show the "completed" mark
if ($treeLesson->options['show_percentage'] != 0) {
$treeLesson -> lesson['completed'] ? $icon = 'success' : $icon = 'semi_success';
$treeString .=
<td class = "lessonProgress">
<span class = "progressNumber completedLessonProgress" style = "width:50px;"> </span>
<span class = "progressBar completedLessonProgress" style = "width:50px;text-align:center"><img src = "images/16x16/'.$icon.'.png" alt = "'._LESSONCOMPLETE.'" title = "'._LESSONCOMPLETE.'" /></span>
</td>';
} else {
$treeString .=
<td class = "lessonProgress">
</td>';
}
} elseif ($roleBasicType == 'student') { //Show the progress bar
if ($treeLesson->options['show_percentage'] != 0) {
$treeString .=
<td class = "lessonProgress">
<span class = "progressNumber incompletedLessonProgress" style = "width:50px;">'.$treeLesson -> lesson['overall_progress']['percentage'].'%</span>
<span class = "progressBar incompletedLessonProgress" style = "width:'.($treeLesson -> lesson['overall_progress']['percentage'] / 2).'px;"> </span>
</td>';
} else {
$treeString .=
<td class = "lessonProgress">
</td>';
}
} else {
$treeString .= '<td style = "width:1px;padding-bottom:2px;"></td>';
}
if ($roleBasicType == 'student') {
$this -> hasLessonsAsStudent = true;
}
return $treeString;
}
private function printLessonBuyLink($treeLesson, $options) {
$treeString = '';
if (isset($options['buy_link']) && $options['buy_link'] && (!isset($treeLesson -> lesson['has_lesson']) || !$treeLesson -> lesson['has_lesson']) && (!isset($treeLesson -> lesson['reached_max_users']) || !$treeLesson -> lesson['reached_max_users']) && (!isset($_SESSION['s_type']) || $_SESSION['s_type'] != 'administrator')) {
$action = 'addToCart(this, '.$treeLesson -> lesson['id'].', \'lesson\');';
if (!$GLOBALS['configuration']['enable_cart'] || !EfrontUser::isOptionVisible('payments')) {
if (!$GLOBALS['configuration']['enable_cart']) {
$action .= 'location=redirectLocation';
}
$image = '<img class = "ajaxHandle" src = "images/16x16/add.png" alt = "'._ENROLL.'" title = "'._ENROLL.'" onclick = "'.$action.'">';
} else {
$image = '<img class = "ajaxHandle" src = "images/16x16/shopping_basket_add.png" alt = "'._ADDTOCART.'" title = "'._ADDTOCART.'" onclick = "'.$action.'">';
}
$treeString .=
<span class = "buyLesson">
<span onclick = "'.$action.'">'.$this -> showLessonPrice($treeLesson).'</span>
'.$image.
</span>';
}
return $treeString;
}
private function showLessonPrice($lesson) {
if ($lesson -> lesson['price']) {
$lesson -> lesson['price'] ? $priceString = formatPrice($lesson -> lesson['price'], array($lesson -> options['recurring'], $lesson -> options['recurring_duration']), true) : $priceString = false;
} elseif (!EfrontUser::isOptionVisible('payments')) {
$priceString = '';
} else {
$priceString = _FREELESSON;
}
return $priceString;
}
private function showCoursePrice($course) {
if ($course -> course['price']) {
$course -> course['price'] ? $priceString = formatPrice($course -> course['price'], array($course -> options['recurring'], $course -> options['recurring_duration']), true) : $priceString = false;
} elseif (!EfrontUser::isOptionVisible('payments')) {
$priceString = '';
} else {
$priceString = _FREECOURSE;
}
return $priceString;
}
private function printCourseLinks($treeCourse, $options, $roleBasicType) {
$treeString = '';
$courseLink = $options['courses_link'];
$href = str_replace("#user_type#", $roleBasicType, $courseLink).$treeCourse -> shouldDisplayInCatalog();
if (isset($options['buy_link'])) {
if ($options['buy_link'] && (!isset($treeCourse -> course['has_instances_show_in_catalog']) || !$treeCourse -> course['has_instances_show_in_catalog']) && (!isset($treeCourse -> course['has_course']) || !$treeCourse -> course['has_course']) && (!isset($treeCourse -> course['reached_max_users']) || !$treeCourse -> course['reached_max_users']) && (!isset($_SESSION['s_type']) || $_SESSION['s_type'] != 'administrator')) {
$action = 'addToCart(this, '.$treeCourse -> course['id'].', \'course\');';
if (!$GLOBALS['configuration']['enable_cart'] || !EfrontUser::isOptionVisible('payments')) {
if (!$GLOBALS['configuration']['enable_cart']) {
$action .= 'location=redirectLocation';
}
$image = '<img class = "ajaxHandle" src = "images/16x16/add.png" alt = "'._ENROLL.'" title = "'._ENROLL.'" onclick = "'.$action.'">';
} else {
$image = '<img class = "ajaxHandle" src = "images/16x16/shopping_basket_add.png" alt = "'._ADDTOCART.'" title = "'._ADDTOCART.'" onclick = "'.$action.'">';
}
$treeString .=
<span class = "buyLesson">
<span onclick = "'.$action.'">'.$this -> showCoursePrice($treeCourse).'</span>
'.$image.
</span>';
$hasInstancesClass = 'boldFont';
} else {
$treeString .=
<span class = "buyLesson">
<span onclick = "location=\''.$href.'\'">'._MOREINFO.'</span>
<img class = "ajaxHandle" src = "images/16x16/arrow_right.png" alt = "'._INFORMATION.'" title = "'._INFORMATION.'" onclick = "location=\''.$href.'\'">
</span>';
}
}
if (!isset($treeCourse -> course['from_timestamp']) || $treeCourse -> course['from_timestamp']) { //from_timestamp in user status means that the user's status in the course is not 'pending'
$classNames = array();
if ($options['tooltip'] && EfrontUser::isOptionVisible('tooltip')) {
$treeString .= '<a href = "'.($courseLink ? $href : 'javascript:void(0)').'" class = "'.$hasInstancesClass.' info '.implode(" ", $classNames).'" url = "ask_information.php?courses_ID='.$treeCourse -> course['id'].'">'.$treeCourse -> course['name'].'</a>';
} else {
$courseLink ? $treeString .= '<a href = "'.str_replace("#user_type#", $roleBasicType, $courseLink).$treeCourse -> course['id'].'" class = "'.$hasInstancesClass.'">'.$treeCourse -> course['name'].'</a>' : $treeString .= $treeCourse -> course['name'];
}
} else {
$treeString .= '<a href = "javascript:void(0)" class = "'.$hasInstancesClass.' inactiveLink" title = "'._CONFIRMATIONPEDINGFROMADMIN.'">'.$treeCourse -> course['name'].'</a>';
}
return $treeString;
}
private function printLessonLink($treeLesson, $options, $roleBasicType) {
$treeString = '';
if (!$roleBasicType || $treeLesson -> lesson['active_in_lesson']) { //active_in_lesson (equals from_timestamp in users_to_lessons) in user status means that the user's status in the lesson is not 'pending'
$classNames = array();
$lessonLink = $options['lessons_link'];
if ($roleBasicType == 'student' && (($treeLesson -> lesson['from_timestamp'] && $treeLesson -> lesson['from_timestamp'] > time()) || ($treeLesson -> lesson['to_timestamp'] && $treeLesson -> lesson['to_timestamp'] < time()))) { //here, from_timestamp and to_timestamp refer to the lesson periods
$lessonLink = false;
$classNames[] = 'inactiveLink';
}
if ($options['tooltip'] && EfrontUser::isOptionVisible('tooltip')) {
$treeString .= '<a href = "'.($lessonLink ? str_replace("#user_type#", $roleBasicType, $lessonLink).$treeLesson -> lesson['id'] : 'javascript:void(0)').'" class = "info '.implode(" ", $classNames).'" url = "ask_information.php?lessons_ID='.$treeLesson -> lesson['id'].'">'.$treeLesson -> lesson['name'].'</a>';
} else {
$lessonLink ? $treeString .= '<a href = "'.str_replace("#user_type#", $roleBasicType, $lessonLink).$treeLesson -> lesson['id'].'">'.$treeLesson -> lesson['name'].'</a>' : $treeString .= $treeLesson -> lesson['name'];
}
} else {
$treeString .= '<a href = "javascript:void(0)" class = "inactiveLink" title = "'._CONFIRMATIONPEDINGFROMADMIN.'">'.$treeLesson -> lesson['name'].'</a>';
}
return $treeString;
}
private function printCategoryTitle($iterator, $display, $imageString, $classString) {
$treeString = '';
$current = $iterator -> current();
$children = array(); //The $children array is used so that when collapsing a direction, all its children disappear as well
foreach (new EfrontNodeFilterIterator(new ArrayIterator($this -> getNodeChildren($current), RecursiveIteratorIterator :: SELF_FIRST)) as $key => $value) {
$children[] = $key;
}
$treeString .=
<table class = "directionsTable" id = "direction_'.$current['id'].'" '.($iterator -> getDepth() >= 1 ? $display : '').'>
<tr class = "lessonsList" onclick = "Element.extend(this);showHideDirections($(\'subtree_img'.$current['id'].'\'), \''.implode(",", $children).'\', \''.$current['id'].'\', ($(\'subtree_img'.$current['id'].'\').hasClassName(\'visible\')) ? \'hide\' : \'show\');">
<td class = "listPadding" style = "width:1px"><div style = "width:'.(20 * $iterator -> getDepth()).'px;"> </div></td>
<td class = "listToggle">';
if ($iterator -> getDepth() >= 1) {
$treeString .= '<img id = "subtree_img'.$current['id'].'" class = "visible" src = "images/16x16/navigate_up.png" alt = "'._CLICKTOTOGGLE.'" title = "'._CLICKTOTOGGLE.'" >';
} else {
$treeString .= '<img id = "subtree_img'.$current['id'].'" '.$classString.' src = "images/16x16/navigate_'.$imageString.'.png" alt = "'._CLICKTOTOGGLE.'" title = "'._CLICKTOTOGGLE.'" >';
}
$treeString .= '</td>
<td>
<img src = "images/32x32/categories.png" >
<span style = "display:none" id = "subtree_children_'.$current['id'].'">'.implode(",", $children).'</span>
<span class = "listName">'.$current['name'].'</span></td>
</tr>';
return $treeString;
}
private function getTreeDisplaySettings($options, $totalEntries) {
if ($totalEntries > 10 && (($options['collapse'] && !isset($_COOKIE['collapse_catalog'])) || ($options['collapse'] && $_COOKIE['collapse_catalog'] == 1) || (isset($_COOKIE['collapse_catalog']) && $_COOKIE['collapse_catalog']))) {
$display = 'style = "display:none"';
$display_lessons = 'style = "display:none"';
$imageString = 'down';
$classString = '';
} else {
$display = '';
$display_lessons = '';
$imageString = 'up';
$classString = ' class = "visible" ';
}
return array($display, $display_lessons, $imageString, $classString);
}
private function printCategoryLessons($iterator, $display_lessons, $options, $lessons) {
$roles = EfrontLessonUser :: getLessonsRoles();
$roleNames = EfrontLessonUser :: getLessonsRoles(true);
$treeString = $lessonsString = '';
$current = $iterator -> current();
foreach ($current -> offsetGet('lessons') as $lessonId) {
$treeLesson = $lessons[$lessonId];
if (isset($treeLesson -> lesson['user_type']) && $treeLesson -> lesson['user_type']) {
$roleInLesson = $treeLesson -> lesson['user_type'];
$roleBasicType = $roles[$roleInLesson]; //Indicates that this is a catalog with user data
} else {
$roleBasicType = null;
}
if ($roleBasicType == 'student') {
$this -> hasLessonsAsStudent = true;
}
//if ($_COOKIE['display_all_courses'] == '1' || $roleBasicType != 'student' || (!$treeLesson -> lesson['completed'] && (is_null($treeLesson -> lesson['remaining']) || $treeLesson -> lesson['remaining'] > 0))) {
$lessonsString .= '<tr class = "directionEntry">';
if ($roleBasicType) {
$lessonsString .= $this -> printProgressBar($treeLesson, $roleBasicType);
}
$accessLimitString = '';
if (isset($treeLesson -> lesson['remaining']) && !is_null($treeLesson -> lesson['remaining']) && $roles[$treeLesson -> lesson['user_type']] == 'student') {
$accessLimitString .= eF_convertIntervalToTime($treeLesson -> lesson['remaining'], true).' '.mb_strtolower(_REMAINING);
}
if (isset($treeLesson -> lesson['access_limit']) && $treeLesson -> lesson['access_limit'] && !is_null($treeLesson -> lesson['access_counter']) && $roles[$treeLesson -> lesson['user_type']] == 'student') {
if ($treeLesson -> lesson['access_counter'] >= $treeLesson -> lesson['access_limit']) {
$accessLimitString = _ACCESSEXPIRED;
$treeLesson -> lesson['active_in_lesson'] = false;
} else {
!$accessLimitString OR $accessLimitString .= ', ';
$accessLimitString .= str_replace('%x', $treeLesson -> lesson['access_limit'] - $treeLesson -> lesson['access_counter'], _ACCESSESREMAINING);
}
}
if ($accessLimitString) {
$accessLimitString = '<span class = "infoCell">('.$accessLimitString.')</span>';
}
$lessonsString .= '<td>';
$lessonsString .= $this -> printLessonBuyLink($treeLesson, $options);
$lessonsString .= $this -> printLessonLink($treeLesson, $options, $roleBasicType);
$lessonsString .= (isset($treeLesson -> lesson['different_role']) && $treeLesson -> lesson['different_role'] ? ' <span class = "courseRole">('.$roleNames[$treeLesson -> lesson['user_type']].')</span>' : '').'
'.$accessLimitString.
</td>
</tr>';
//}
}
if (isset($current['lessons']) && sizeof($current['lessons']) > 0 && $lessonsString) {
$treeString .=
<tr id = "subtree'.$current['id'].'" name = "default_visible" '.($iterator -> getDepth() >= 1 ? '' : $display_lessons).'>';
$treeString .= ' <td></td>
<td class = "lessonsList_nocolor"> </td>
<td colspan = "2">
<table width = "100%">'.$lessonsString.
</table>
</td></tr>';
}
return $treeString;
}
private function printCategoryCourses($iterator, $display, $userInfo, $options, $courses, $lessons, $checkLessons) {
$roles = EfrontLessonUser :: getLessonsRoles();
$roleNames = EfrontLessonUser :: getLessonsRoles(true);
$treeString = '';
$current = $iterator -> current();
if (isset($current['courses']) && sizeof($current['courses']) > 0) {
$coursesTreeString = '';
foreach ($current -> offsetGet('courses') as $courseId) {
$treeCourse = $courses[$courseId];
if (isset($treeCourse -> course['user_type']) && $treeCourse -> course['user_type']) {
$roleInCourse = $treeCourse -> course['user_type'];
$roleBasicType = $roles[$roleInCourse]; //Indicates that this is a catalog with user data
if ($roleBasicType == 'student') {
$this -> hasLessonsAsStudent = true;
}
} else {
$roleBasicType = null;
}
// if ($_COOKIE['display_all_courses'] == '1' || $roleBasicType != 'student' || (!$treeCourse -> course['completed'] && (is_null($treeCourse -> course['remaining']) || $treeCourse -> course['remaining'] > 0))) {
if ($options['course_lessons']) {
$meets_depends_on_criteria = true;
if ($treeCourse->course['depends_on']) {
if (!isset($courses[$treeCourse->course['depends_on']])) {
$meets_depends_on_criteria = false;
}
}
$coursesTreeString .= $treeCourse -> toHTML($lessons, $options, $checkLessons, $meets_depends_on_criteria);
} else {
$coursesTreeString .=
<table width = "100%">