-
Notifications
You must be signed in to change notification settings - Fork 8
/
locallib.php
2951 lines (2827 loc) · 114 KB
/
locallib.php
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
use core\notification;
use core\session\exception;
use mod_treasurehunt\model\stage;
// This file is part of Treasurehunt for Moodle
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library of functions used by the treasurehunt module.
*
* This contains functions that are called from within the treasurehunt module only
* Functions that are also called by core Moodle are in {@link lib.php}
*
* @package mod_treasurehunt
* @copyright 2016 onwards Adrian Rodriguez Fernandez <huorwhisp@gmail.com>, Juan Pablo de Castro <jpdecastro@tel.uva.es>
* @copyright 2017 onwards Juan Pablo de Castro <jpdecastro@tel.uva.es>
* @author Adrian Rodriguez <huorwhisp@gmail.com>
* @author Juan Pablo de Castro <jpdecastro@tel.uva.es>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/treasurehunt/lib.php');
require_once($CFG->dirroot . '/mod/treasurehunt/GeoJSON/GeoJSON.class.php');
require_once($CFG->dirroot . '/mod/treasurehunt/renderable.php');
require_once($CFG->dirroot . '/mod/treasurehunt/classes/stage.php');
/* * #@+
* Options determining how the grades from individual attempts are combined to give
* the overall grade for a user or group
*/
define('TREASUREHUNT_GRADEFROMSTAGES', '1');
define('TREASUREHUNT_GRADEFROMTIME', '2');
define('TREASUREHUNT_GRADEFROMPOSITION', '3');
define('TREASUREHUNT_GRADEFROMABSOLUTETIME', '4');
/* * #@- */
/* * #@+
* Options determining lock time and game update time
*/
define('TREASUREHUNT_LOCKTIME', 120);
define('TREASUREHUNT_GAMEUPDATETIME', 20);
define('TREASUREHUNT_PLAYERCLASSIC', 'classic');
define('TREASUREHUNT_PLAYERFANCY', 'fancy');
define('TREASUREHUNT_PLAYERBOOTSTRAP', 'bootstrap');
/* * #@- */
// Load classes needed for GeoJSON library.
spl_autoload_register(array('GeoJSON', 'autoload'));
/**
* Compatibility with Moodle 2.9 notifications.
*
* @param string $message
*/
function treasurehunt_notify_info($message)
{
if (class_exists('\core\notification')) {
\core\notification::info($message);
} else {
global $OUTPUT;
echo $OUTPUT->notification($message, 'notifymessage');
}
}
/**
* Compatibility with Moodle 2.9 notifications
* @param unknown $message
*/
function treasurehunt_notify_error($message)
{
if (class_exists('\core\notification')) {
\core\notification::error($message);
} else {
global $OUTPUT;
echo $OUTPUT->notification($message, 'notifyproblem');
}
}
/**
* Compatibility with Moodle 2.9 notifications
* @param unknown $message
*/
function treasurehunt_notify_warning($message)
{
if (class_exists('\core\notification')) {
\core\notification::warning($message);
} else {
global $OUTPUT;
echo $OUTPUT->notification($message, 'notifyproblem');
}
}
/**
* @param Geometry $geom
*/
function treasurehunt_geometry_centroid(Geometry $geom)
{
$coords = [];
$geomarray = $geom->getCoordinates();
foreach ($geomarray as $polys) {
foreach ($polys as $line) {
foreach ($line as $point) {
$coords[] = $point;
}
}
}
$sumx = 0;
$sumy = 0;
foreach ($coords as $coord) {
$sumx += $coord[0];
$sumy += $coord[1];
}
return new Point($sumx / count($coords), $sumy / count($coords));
}
/**
* Serialize geometries into a WKT string.
*
* @param Geometry $geometry
*
* @return string The WKT string representation of the input geometries
*/
function treasurehunt_geometry_to_wkt($geometry)
{
if (!$geometry) {
return 'GEOMETRY EMPTY';
} else {
$wkt = new WKT();
return $wkt->write($geometry);
}
}
/**
* Read WKT string into geometry objects.
*
* @param string $text A WKT string.
*
* @return Geometry|GeometryCollection.
*/
function treasurehunt_wkt_to_object($text)
{
$wkt = new WKT();
return $wkt->read($text);
}
/**
* Generates a friendly string representation of the date relative to current time.
* It uses i18n strings for building a sentence part:
* - timeago for '23 hours ago'
* - timeagolong for '23 hours ago (february, 23 2020)'
* - timetocome for 'in 2 months 3 days'
* - tiemtocomelong for 'in 3 months 3 days (february, 23 2020)'
* - timeat for 'at febrary the 23th 2020'
* - strftimedatetime for a localized long time-date format.
*
*
* Example with $longdate = 200
*
* |----------------|------------------------------------------------------|
* | elapsed time | formatted |
* |----------------|------------------------------------------------------|
* | t < 2 mins | now |
* | t < mediumdate| 3 days 23 hours ago |
* | t < longdate | 20 days ago (6 February 2020, 5:46 PM) |
* | t > longdate | at 6 February 2020, 5:46 PM |
* |----------------|------------------------------------------------------|
*
* @param int $time utc timestamp to be formatted.
* @param float|null $mediumdate threshold (days) to use the short format without full date.
* @param float|null $longdate threshold (days) to use the longer format with full date.
* @param int|null $cur_tm utc timestamp to compare to. If null current time.
* @return string formatted interval
*/
function treasurehunt_get_nice_date($time, $longdate = 200, $mediumdate = 4, $cur_tm = null)
{
if ($cur_tm === null) {
$cur_tm = time();
}
$dif = $cur_tm - $time;
$days = $dif / DAYSECS;
if ($cur_tm > $time) {
$timestringkey = 'timeago';
} else {
$timestringkey = 'timetocome';
$dif = -$dif;
}
$elapsed = new stdClass();
$elapsed->shortduration = treasurehunt_get_nice_duration($dif);
$elapsed->date = userdate($time, get_string('strftimedatetime', 'core_langconfig'));
if ($dif < 2 * MINSECS) {
$x = get_string('now');
} elseif ($dif >=0 && $dif < ($mediumdate * DAYSECS) && $dif < ($longdate * DAYSECS)) {
$x = get_string($timestringkey, 'treasurehunt', $elapsed);
} elseif ($dif < ($longdate * DAYSECS)) {
$elapsed->shortduration = treasurehunt_get_nice_duration($dif, true, true);
$x = get_string($timestringkey.'long', 'treasurehunt', $elapsed);
} else {
$x = get_string('timeat', 'treasurehunt', $elapsed);
}
return "<span data-timestamp=\"$time\">$x</span>";
}
/**
* Format a human-readable format for a duration in months or days and below.
* calculates from seconds to months.
* trim the details to the two more significant units
* @param int $durationinseconds
* @param boolean $usemonths if false render in days.
* @param boolean $shortprecission if true only the most significative unit.
* @return string
*/
function treasurehunt_get_nice_duration($durationinseconds, $usemonths = true, $shortprecission = false)
{
$durationstring = '';
if ($usemonths) {
$months = floor($durationinseconds / (DAYSECS*30));
$durationinseconds -= $months * (DAYSECS * 30);
}
$days = floor($durationinseconds / DAYSECS);
$durationinseconds -= $days * DAYSECS;
$hours = floor($durationinseconds / HOURSECS);
$durationinseconds -= $hours * HOURSECS;
$minutes = floor($durationinseconds / MINSECS);
$seconds = round($durationinseconds - $minutes * MINSECS);
if ($usemonths && $months > 0) {
$durationstring .= $months . ' ' . get_string('month' . ($months > 1 ? 's' : ''));
$days = true; // Report also days.
$hours = false;
$minutes = false;
$seconds = false;
if ($shortprecission) {
return $durationstring;
}
}
if ($days > 0) {
$durationstring .= ' ' . $days . ' ' . get_string('day' . ($days > 1 ? 's':''));
// Trim details less significant.
$minutes = false;
$days = false;
$seconds = false;
if ($shortprecission) {
return $durationstring;
}
}
if ($hours > 0) {
$durationstring .= ' ' . $hours . ' ' . get_string('hour' . ($hours > 1 ? 's' : ''));
$seconds = false;
if ($shortprecission) {
return $durationstring;
}
}
if ($minutes > 0) {
$durationstring .= ' ' . $minutes . ' ' . get_string('minute' . ($minutes > 1 ? 's' : ''));
if ($shortprecission) {
return $durationstring;
}
}
if ($seconds > 0) {
$durationstring .= ' ' . $seconds . ' s.';
}
if ($durationstring === '') {
$durationstring = '-';
}
return $durationstring;
}
/**
* Deserialize a JSON array in a compatible object with the library GeoJSON.
*
* @param string $array The GeoJSON string.
*
* @return Feature|FeatureCollection The PHP equivalent object.
*/
function treasurehunt_geojson_to_object($array)
{
if ($array === null) {
return null;
}
$geojson = new GeoJSON();
return $geojson->loadArray($array);
}
/**
* Check if a point is inside a multipolygon geometry.
*
* @param MultiPolygon $mpolygon
* @param Point $point
* @return bool
*/
function treasurehunt_check_point_in_multipolygon($mpolygon, $point)
{
$polygons = $mpolygon->getComponents();
foreach ($polygons as $polygon) {
if ($polygon instanceof Polygon) {
$result = $polygon->pointInPolygon($point);
if ($result) {
return true;
}
;
}
}
return false;
}
/**
*
* @param stdClass $data form data.
* @return stdClass
*/
function treasurehunt_build_custommappingconfig($data)
{
$mapconfig = new stdClass();
if (empty($data->customlayername)) {
$mapconfig = null;
} else {
if ($data->customlayertype !== 'nongeographic') {
$bbox = [
floatval($data->custommapminlon),
floatval($data->custommapminlat),
floatval($data->custommapmaxlon),
floatval($data->custommapmaxlat)
];
$mapconfig->bbox = $bbox;
}
if ($data->customlayertype == 'onlybase') {
$mapconfig->layertype = 'base';
$mapconfig->onlybase = true;
$mapconfig->geographic = true;
} elseif ($data->customlayertype == 'nongeographic') {
$mapconfig->layertype = 'base';
$mapconfig->onlybase = true;
$mapconfig->geographic = false;
} else {
$mapconfig->layertype = $data->customlayertype; // Or base or overlay.
$mapconfig->onlybase = false;
$mapconfig->geographic = true;
}
$mapconfig->wmsurl = $data->customlayerwms;
if (!empty($data->customwmsparams)) {
$params = explode('&', $data->customwmsparams);
$parmsobj = new stdClass();
foreach ($params as $param) {
$parts = explode('=', $param);
$parmsobj->{$parts[0]} = $parts[1];
}
$mapconfig->wmsparams = $parmsobj;
} else {
$mapconfig->wmsparams = [];
}
$mapconfig->layername = $data->customlayername;
}
return $mapconfig;
}
/**
*
* @param \stdClass $treasurehunt Treasurehunt record.
* @param context_module $context
* @return NULL|mixed
*/
function treasurehunt_get_custommappingconfig($treasurehunt, $context = null)
{
if (empty($treasurehunt->custommapconfig)) {
return null;
}
$cm = get_coursemodule_from_instance('treasurehunt', $treasurehunt->id);
$context = context_module::instance($cm->id);
$custommapconfig = json_decode($treasurehunt->custommapconfig);
if ($custommapconfig->geographic === true) {
$custommapconfig->bbox = array_map(function ($item) {
return floatval($item);
}, $custommapconfig->bbox);
} else {
$custommapconfig->bbox = [null, -50, null, 50];
}
$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'mod_treasurehunt', 'custombackground', 0, 'sortorder DESC, id ASC', false, 0, 0, 1);
$file = reset($files);
if ($file) {
$path = '/' . $context->id . '/mod_treasurehunt/custombackground/0/' . $file->get_filename();
$moodleurl = new moodle_url('/pluginfile.php' . $path);
$custommapconfig->custombackgroundurl = $moodleurl->out();
} else {
$custommapconfig->custombackgroundurl = null;
}
if (trim($custommapconfig->wmsurl) === "") {
$custommapconfig->wmsurl = null;
}
return $custommapconfig;
}
/**
* @return array int => lang string the options for calculating the treasure hunt grade
* from the individual attempt grades.
*/
function treasurehunt_get_grading_options()
{
return array(
TREASUREHUNT_GRADEFROMSTAGES => get_string('gradefromstages', 'treasurehunt'),
TREASUREHUNT_GRADEFROMTIME => get_string('gradefromtime', 'treasurehunt'),
TREASUREHUNT_GRADEFROMABSOLUTETIME => get_string('gradefromabsolutetime', 'treasurehunt'),
TREASUREHUNT_GRADEFROMPOSITION => get_string('gradefromposition', 'treasurehunt'),
);
}
/**
* Creates a default road with a default stage to the treasurehunt if empty
* @param stdClass $treasurehunt
*/
function treasurehunt_create_default_items($treasurehunt)
{
$roads = treasurehunt_get_total_roads($treasurehunt->id);
$context = context_module::instance($treasurehunt->coursemodule);
if ($roads == 0) {
$road = new stdClass();
$road->name = get_string('road', 'treasurehunt');
treasurehunt_add_update_road($treasurehunt, $road, $context);
}
// Adds a default stage to the road.
$stage = new stage(get_string('stage', 'treasurehunt'), '');
$stage->roadid = $road->id;
$stage->cluetextformat = FORMAT_HTML; // Updated later.
$stage->cluetexttrust = 0; // Updated later.
$stage->questiontext = ''; // Updated later.
$stage->questiontextformat = FORMAT_HTML; // Updated later.
$stage->questiontexttrust = 0; // Updated later.
treasurehunt_add_new_stage($stage, $road);
}
/**
* @param stage $stage
* @param road $road
*/
function treasurehunt_add_new_stage($stage, $road)
{
$stage->id = treasurehunt_insert_stage_form($stage);
return $stage;
}
/**
* Adds a stage to a road by updating treasurehunt_stages table.
* If the stage has no geometry then set the road as invalid.
*
* @param stdClass|stage $stage The extended stage object as used by edit_stage.php or stage
* @return int The id of the new stage.
*/
function treasurehunt_insert_stage_form($stage)
{
global $DB;
$stage->timemodified = time();
// The position of the stage in the road is the next to the last introduced.
$position = $DB->get_record_sql('SELECT count(id) + 1 as position FROM '
. '{treasurehunt_stages} WHERE roadid = (?)', array($stage->roadid));
$stage->position = $position->position;
$id = $DB->insert_record("treasurehunt_stages", $stage);
if (empty($stage->geom)) {
// As the stage has no geometry, the road is set as invalid.
treasurehunt_set_valid_road($stage->roadid, false);
}
return $id;
}
/**
* Updates the position and/or geometry of a stage in a road by updating
* treasurehunt_stages table. Then, check if road is valid.
*
* @see treasurehunt_set_valid_road()
* @param Feature $feature The feature with the id, position, road and geometry of the stage.
* @param stdClass $context The context object.
*/
function treasurehunt_update_geometry_and_position_of_stage(Feature $feature, $context)
{
global $DB;
$stage = new stdClass();
$stage->position = $feature->getProperty('stageposition');
$stage->roadid = $feature->getProperty('roadid');
/** @var Multipolygon $geometry */
$geometry = $feature->getGeometry();
$stage->geom = treasurehunt_geometry_to_wkt($geometry);
$stage->timemodified = time();
$stage->id = $feature->getId();
$parms = array('id' => $stage->id);
$entry = $DB->get_record('treasurehunt_stages', $parms, 'id,position', MUST_EXIST);
// It can not be change the position of stage once the road is blocked.
if (treasurehunt_check_road_is_blocked($stage->roadid) && ($stage->position != $entry->position)) {
print_error('notchangeorderstage', 'treasurehunt');
}
// It can not be save an existing stage without geometry.
if (count($geometry->getComponents()) === 0) {
print_error('saveemptyridle', 'treasurehunt');
}
$DB->update_record('treasurehunt_stages', $stage);
// Check if road is valid.
treasurehunt_set_valid_road($stage->roadid);
$stage = $DB->get_record('treasurehunt_stages', $parms);
// Trigger update stage event.
$eventparams = array(
'context' => $context,
'objectid' => $stage->id,
'other' => $stage->name,
);
$event = \mod_treasurehunt\event\stage_updated::create($eventparams);
$event->add_record_snapshot('treasurehunt_stages', $stage);
$event->trigger();
}
/**
* Delete a treasure hunt stage in a road and all fields associated. Then,
* repositions the other stages in the road and checks if road is valid.
*
* @param int $id The stage id.
* @param stdClass $context The context object.
*/
function treasurehunt_delete_stage($id, $context)
{
global $DB;
$stageresult = $DB->get_record('treasurehunt_stages', array('id' => $id), '*', MUST_EXIST);
// It can not be delete a stage of a started road.
if (treasurehunt_check_road_is_blocked($stageresult->roadid)) {
print_error('notdeletestage', 'treasurehunt');
}
$DB->delete_records('treasurehunt_stages', array('id' => $id));
$DB->delete_records('treasurehunt_attempts', array('stageid' => $id));
$sql = 'UPDATE {treasurehunt_stages} '
. 'SET position = position - 1 WHERE roadid = (?) AND position > (?)';
$params = array($stageresult->roadid, $stageresult->position);
$DB->execute($sql, $params);
// Check if road is valid.
treasurehunt_set_valid_road($stageresult->roadid);
// Trigger deleted stage event.
$eventparams = array(
'context' => $context,
'objectid' => $id,
'other' => $stageresult->name,
);
$event = \mod_treasurehunt\event\stage_deleted::create($eventparams);
$event->add_record_snapshot('treasurehunt_stages', $stageresult);
$event->trigger();
}
/**
* Delete a treasure hunt road and all fields associated.
*
* @param int $roadid The road id.
* @param object $treasurehunt The treasure hunt object.
* @param stdClass $context The context object.
*/
function treasurehunt_delete_road($roadid, $treasurehunt, $context)
{
global $DB;
$params = array($roadid);
$stages = $DB->get_records_sql(
'SELECT id FROM {treasurehunt_stages} WHERE roadid = ?',
$params
);
foreach ($stages as $stage) {
$DB->delete_records_select('treasurehunt_attempts', 'stageid = ?', array($stage->id));
$DB->delete_records_select('treasurehunt_answers', 'stageid = ?', array($stage->id));
}
$DB->delete_records_select('treasurehunt_stages', 'roadid = ?', $params);
$road = $DB->get_record('treasurehunt_roads', array('id' => $roadid));
$DB->delete_records('treasurehunt_roads', array('id' => $roadid));
treasurehunt_update_grades($treasurehunt);
// Trigger deleted road event.
$eventparams = array(
'context' => $context,
'objectid' => $roadid,
);
$event = \mod_treasurehunt\event\road_deleted::create($eventparams);
$event->add_record_snapshot('treasurehunt_roads', $road);
$event->trigger();
}
/**
* Count the total number of roads belonging to an instance of treasurehunt.
*
* @param int $treasurehuntid The identifier of treasure hunt to check.
* @return int The number of roads in the instance.
*/
function treasurehunt_get_total_roads($treasurehuntid)
{
global $DB;
$number = $DB->count_records('treasurehunt_roads', array('treasurehuntid' => $treasurehuntid));
return $number;
}
/**
* Count the total number of stages belonging to road.
*
* @param int $roadid The identifier of road to check.
* @return int The number of stages in the road.
*/
function treasurehunt_get_total_stages($roadid)
{
global $DB;
$number = $DB->count_records('treasurehunt_stages', array('roadid' => $roadid));
return $number;
}
/**
* Check if a user or group has completed the assigned road of treasure hunt.
* If the group identifier provided is not 0, the group is checked, else the user is checked.
*
* @param int $userid The user id.
* @param int $groupid The group id.
* @param int $roadid The road id.
* @return bool True if user or group has finished the road, else false.
*/
function treasurehunt_check_if_user_has_finished($userid, $groupid, $roadid)
{
global $DB;
if ($groupid) {
$grouptype = 'a.groupid=(?)';
$params = array($roadid, $groupid);
} else {
$grouptype = 'a.groupid=0 AND a.userid=(?)';
$params = array($roadid, $userid);
}
$sql = "SELECT MAX(a.timecreated) as finished FROM "
. "{treasurehunt_attempts} a INNER JOIN {treasurehunt_stages} r "
. "ON r.id = a.stageid WHERE a.success=1 AND r.position=(SELECT "
. "max(ri.position) FROM {treasurehunt_stages} ri where "
. "ri.roadid=r.roadid) AND r.roadid = ? "
. "AND (a.type='location' OR a.type='qr') "
. "AND $grouptype";
$finished = $DB->get_record_sql($sql, $params);
if (isset($finished->finished)) {
return true;
} else {
return false;
}
}
/**
* Updates the value of validity of a road.
*
* @see treasurehunt_is_valid_road()
* @param int $roadid The road id.
* @param bool $valid If not set, check actual state of the road.
*/
function treasurehunt_set_valid_road($roadid, $valid = null)
{
global $DB;
$road = new stdClass();
$road->id = $roadid;
$road->timemodified = time();
if (is_null($valid)) {
$road->validated = treasurehunt_is_valid_road($roadid);
} else {
$road->validated = $valid;
}
$DB->update_record("treasurehunt_roads", $road);
}
/**
* Check if a road is blocked.
*
* @param int $roadid The road id.
* @return int Return 1 if road is blocked, else 0.
*/
function treasurehunt_check_road_is_blocked($roadid)
{
global $DB;
$sql = "SELECT at.success "
. "FROM {treasurehunt_attempts} at INNER JOIN {treasurehunt_stages} ri "
. "ON ri.id = at.stageid INNER JOIN {treasurehunt_roads} r "
. "ON ri.roadid=r.id WHERE r.id=?";
$params = array($roadid);
return $DB->record_exists_sql($sql, $params);
}
/**
* Get all roads and stages in GeoJSON format from an instance of treasurehunt.
*
* @param int $treasurehuntid The identifier of treasure hunt.
* @param stdClass $context The context object.
* @return array All the roads with stages in GeoJSON format.
*/
function treasurehunt_get_all_roads_and_stages($treasurehuntid, $context)
{
$stagesresult = treasurehunt_get_stages($treasurehuntid, $context);
$roads = treasurehunt_get_roads($treasurehuntid);
foreach ($roads as $road) {
$stagesinroad = array();
foreach ($stagesresult as $key => $stage) {
if ($stage->roadid == $road->id) {
$stagesinroad[] = $stage;
unset($stagesresult[$key]);
}
}
$road->stages = treasurehunt_features_to_geojson($stagesinroad, $context, $treasurehuntid);
}
return $roads;
}
/**
* Get all stages in a treasurehunt instance.
* @param int $treasurehuntid instace id.
* @global moodle_database $DB
*/
function treasurehunt_get_stages($treasurehuntid, $context)
{
global $DB;
// Get all stages from the instance of treasure hunt.
$stagessql = "SELECT stage.id, "
. "stage.name, stage.cluetext, roadid, position,"
. "geom as geometry FROM {treasurehunt_stages} stage"
. " inner join {treasurehunt_roads} roads on stage.roadid = roads.id"
. " WHERE treasurehuntid = ? ORDER BY position DESC";
$stagesresult = $DB->get_records_sql($stagessql, array($treasurehuntid));
foreach ($stagesresult as $stage) {
treasurehunt_format_texts($stage, $context);
}
return $stagesresult;
}
/**
* Get all roads in a treasurehunt instance.
* @param int $treasurehuntid instace id.
* @global moodle_database $DB
*/
function treasurehunt_get_roads($treasurehuntid)
{
global $DB;
// Get all roads from the instance of treasure hunt.
$roadssql = "SELECT id, name, CASE WHEN (SELECT COUNT(at.id) "
. "FROM {treasurehunt_attempts} at INNER JOIN {treasurehunt_stages} ri "
. "ON ri.id = at.stageid INNER JOIN {treasurehunt_roads} r "
. "ON ri.roadid=r.id WHERE r.id= road.id) > 0 THEN 1 ELSE 0 "
. "END AS blocked FROM {treasurehunt_roads} road where treasurehuntid = ?";
$roads = $DB->get_records_sql($roadssql, array($treasurehuntid));
return $roads;
}
/**
* Create or renew the user edition lock in an instance of treasurehunt.
*
* @param int $treasurehuntid The identifier of treasure hunt.
* @param int $userid The identifier of user who block the instance.
* @return int The lock id.
*/
function treasurehunt_renew_edition_lock($treasurehuntid, $userid)
{
global $DB;
$table = 'treasurehunt_locks';
$params = array('treasurehuntid' => $treasurehuntid, 'userid' => $userid);
$time = time() + treasurehunt_get_setting_lock_time();
$lock = $DB->get_record($table, $params);
if (!empty($lock)) {
$DB->update_record($table, array('id' => $lock->id, 'lockedtill' => $time));
return $lock->id;
} else {
treasurehunt_delete_old_locks($treasurehuntid);
return $DB->insert_record($table, array('treasurehuntid' => $treasurehuntid, 'userid' => $userid, 'lockedtill' => $time));
}
}
/**
* Get the value of the setting lock time.
*
* @return int Lock time.
*/
function treasurehunt_get_setting_lock_time()
{
if (($locktimeediting = get_config('mod_treasurehunt', 'locktimeediting')) > 5) {
return $locktimeediting;
} else {
return TREASUREHUNT_LOCKTIME;
}
}
/**
* Get the value of the setting game update time.
*
* @return int Game update time.
*/
function treasurehunt_get_setting_game_update_time()
{
if (($gameupdatetime = get_config('mod_treasurehunt', 'gameupdatetime')) > 0) {
return $gameupdatetime;
} else {
return TREASUREHUNT_GAMEUPDATETIME;
}
}
/**
* Check whether access to editing an instance of treasure hunt is locked to a specific user.
*
* @param int $treasurehuntid The identifier of treasure hunt.
* @param int $userid The identifier of user who want to know if the edition is locked.
* @return int Return 1 if the edition of the instance is locked, else 0.
*/
function treasurehunt_is_edition_loked($treasurehuntid, $userid)
{
global $DB;
$select = "treasurehuntid = ? AND lockedtill > ? AND userid != ?";
$params = array($treasurehuntid, time(), $userid);
return $DB->record_exists_select('treasurehunt_locks', $select, $params);
}
/**
* Check if a locking session still exists.
*
* @param int $lockid The identifier of lock to check.
* @return int Return 1 if lock exists, else 0.
*/
function treasurehunt_edition_lock_id_is_valid($lockid)
{
global $DB;
return $DB->record_exists_select('treasurehunt_locks', "id = ?", array($lockid));
}
/**
* Get the name of the user who is editing the instance of treasure hunt.
*
* @param int $treasurehuntid The identifier of treasure hunt.
* @return string
*/
function treasurehunt_get_username_blocking_edition($treasurehuntid)
{
global $DB;
$table = 'treasurehunt_locks';
$params = array('treasurehuntid' => $treasurehuntid);
$result = $DB->get_record($table, $params);
return treasurehunt_get_user_fullname_from_id($result->userid);
}
/**
* Removes all locks belonging to a concrete instance of treasure hunt whose time has been exceeded.
*
* @param int $treasurehuntid The identifier of treasure hunt.
*/
function treasurehunt_delete_old_locks($treasurehuntid)
{
global $DB;
$DB->delete_records_select('treasurehunt_locks', "lockedtill < ? AND treasurehuntid = ? ", array(time(), $treasurehuntid));
}
/**
* Get the play mode to the stage of a user or group.
* If the group identifier provided is not 0, the group is checked, else the user is checked.
*
* @param int $userid The identifier of user.
* @param int $groupid The identifier of group.
* @param int $roadid The identifier of the road of user or group.
* @param stdClass $treasurehunt The treasurehunt instance.
* @return int 1 for play without moving and 0 for the other.
*/
function treasurehunt_get_play_mode($userid, $groupid, $roadid, $treasurehunt)
{
global $DB;
if ($treasurehunt->playwithoutmoving) {
return 1;
}
if ($groupid) {
$grouptype = 'a.groupid=(?)';
$params = array($groupid, $roadid);
} else {
$grouptype = 'a.groupid=0 AND a.userid=(?)';
$params = array($userid, $roadid);
}
$sql = "SELECT r.playstagewithoutmoving FROM {treasurehunt_stages} r "
. "WHERE r.position = (SELECT COALESCE(MAX(ri.position) +1,1) FROM {treasurehunt_stages} ri "
. "INNER JOIN {treasurehunt_attempts} a ON ri.id= a.stageid WHERE "
. "a.success = 1 AND ri.roadid = r.roadid AND $grouptype) AND r.roadid = ?";
$playmode = $DB->get_record_sql($sql, $params);
return $playmode->playstagewithoutmoving;
}
/**
* Checks if the point sent by the user or the group is within the geometry of the corresponding stage.
* Also checks the qrtext param.
* If the group identifier provided is not 0, the group is checked, else the user is checked.
*
* @param int $userid The identifier of user.
* @param int $groupid The identifier of group.
* @param int $roadid The identifier of the road of user or group.
* @param Point $point The identifier of the road of user or group.
* @param stdClass $context The context object.
* @param stdClass $treasurehunt The treasurehunt instance.
* @param int $nostages The total number of stages in the road.
* @return stdClass The control parameters.
*/
function treasurehunt_check_user_location($userid, $groupid, $roadid, $point, $qrtext, $context, $treasurehunt, $nostages)
{
global $DB;
$return = new stdClass();
$locationgeom = null;
$return->update = '';
$return->roadfinished = false;
$return->success = false;
// Last attempt data with correct geometry to know if it has resolved geometry and the stage is overcome.
$currentstage = treasurehunt_get_last_successful_attempt($userid, $groupid, $roadid, $context);
if (!$currentstage || $currentstage->success) {
$return->newattempt = true;
if ($currentstage) {
$nextnostage = $currentstage->position + 1;
} else {
$nextnostage = 1;
}
$nextstage = $DB->get_record('treasurehunt_stages', array('position' => $nextnostage, 'roadid' => $roadid), '*', MUST_EXIST);
// Check qrtext or location
$nextstagegeom = treasurehunt_wkt_to_object($nextstage->geom);
$inside = $point == null ? false : treasurehunt_check_point_in_multipolygon($nextstagegeom, $point);
$qrguessed = $qrtext == '' ? false : $nextstage->qrtext === $qrtext;
// If point is within stage geometry or qrguessed.
if ($inside || $qrguessed) {
$questionsolved = ($nextstage->questiontext === '' ? true : false);
$activitysolved = (treasurehunt_check_activity_completion($nextstage->activitytoend) == 0 ? true : false);
if ($questionsolved && $activitysolved) {
$success = true;
} else {
$success = false;
}
$penalty = false;
$return->msg = $return->update = get_string('successlocation', 'treasurehunt');
$return->newstage = true;
} else {
$penalty = true;
$questionsolved = false;
$activitysolved = false;
$success = false;
$return->msg = $return->update = get_string('faillocation', 'treasurehunt');
$return->newstage = false;
}
// Get a reasonable location for reporting.
if ($inside) {
$locationgeom = $point;
} elseif (isset($qrtext)) { // This is a QR scan.
if ($qrguessed) {
$locationgeom = treasurehunt_geometry_centroid($nextstagegeom);
} else {
// Get last known location in the tracking.
$locationgeom = treasurehunt_get_last_location($treasurehunt, $userid);
if ($locationgeom === null) { // If not, report an approximation.
if ($currentstage == false) {
// If this is previous of the first stage, it is safe to report the initial point.
$locationgeom = treasurehunt_geometry_centroid($nextstagegeom);
} else {
// Report the location of current stage (already discovered).
$locationgeom = treasurehunt_wkt_to_object($currentstage->location);
}
}
}
} else {
$locationgeom = $point;
}
// Create the attempt.
$attempt = new stdClass();
$attempt->stageid = $nextstage->id;
$attempt->timecreated = time();
$attempt->userid = $userid;
$attempt->groupid = $groupid;
$attempt->success = $success;
$attempt->type = isset($qrtext) ? 'qr' : 'location';
$attempt->activitysolved = $activitysolved;
$attempt->questionsolved = $questionsolved;
$attempt->geometrysolved = $inside || $qrguessed;
$attempt->location = treasurehunt_geometry_to_wkt($locationgeom);
$attempt->penalty = $penalty;
treasurehunt_insert_attempt($attempt, $context);
// If the attempt succeeds the location and there is an activity to overcome, it is checked if it is exceeded.
if ($attempt->geometrysolved && !$activitysolved) {
if ($usercompletion = treasurehunt_check_completion_activity($nextstage->activitytoend, $userid, $groupid, $context)) {
$attempt->type = 'activity';
$attempt->activitysolved = 1;
$attempt->userid = $usercompletion;
// To follow a chronological order.
$attempt->timecreated += 1;
if ($questionsolved) {
$attempt->success = 1;
}
treasurehunt_insert_attempt($attempt, $context);
// If it has already exceeded the location attempt is inserted.
if ($questionsolved) {
$attempt->type = isset($qrtext) ? 'qr' : 'location';
// To follow a chronological order.
$attempt->timecreated += 1;
treasurehunt_insert_attempt($attempt, $context);
}
$return->update = get_string('activitytoendovercome', 'treasurehunt', treasurehunt_get_activity_to_end_link($nextstage->activitytoend));
}