mirrored from git://git.moodle.org/moodle.git
/
moodlelib.php
6356 lines (5424 loc) · 194 KB
/
moodlelib.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 // $Id$
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
// //
// This program 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 2 of the License, or //
// (at your option) any later version. //
// //
// This program 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: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
/**
* moodlelib.php - Moodle main library
*
* Main library file of miscellaneous general-purpose Moodle functions.
* Other main libraries:
* - weblib.php - functions that produce web output
* - datalib.php - functions that access the database
* @author Martin Dougiamas
* @version $Id$
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
/// CONSTANTS /////////////////////////////////////////////////////////////
/**
* Used by some scripts to check they are being called by Moodle
*/
define('MOODLE_INTERNAL', true);
/**
* No groups used?
*/
define('NOGROUPS', 0);
/**
* Groups used?
*/
define('SEPARATEGROUPS', 1);
/**
* Groups visible?
*/
define('VISIBLEGROUPS', 2);
/**
* Time constant - the number of seconds in a week
*/
define('WEEKSECS', 604800);
/**
* Time constant - the number of seconds in a day
*/
define('DAYSECS', 86400);
/**
* Time constant - the number of seconds in an hour
*/
define('HOURSECS', 3600);
/**
* Time constant - the number of seconds in a minute
*/
define('MINSECS', 60);
/**
* Time constant - the number of minutes in a day
*/
define('DAYMINS', 1440);
/**
* Time constant - the number of minutes in an hour
*/
define('HOURMINS', 60);
/**
* Parameter constants - if set then the parameter is cleaned of scripts etc
*/
define('PARAM_RAW', 0x0000);
define('PARAM_CLEAN', 0x0001);
define('PARAM_INT', 0x0002);
define('PARAM_INTEGER', 0x0002); // Alias for PARAM_INT
define('PARAM_ALPHA', 0x0004);
define('PARAM_ACTION', 0x0004); // Alias for PARAM_ALPHA
define('PARAM_FORMAT', 0x0004); // Alias for PARAM_ALPHA
define('PARAM_NOTAGS', 0x0008);
define('PARAM_FILE', 0x0010);
define('PARAM_PATH', 0x0020);
define('PARAM_HOST', 0x0040); // FQDN or IPv4 dotted quad
define('PARAM_URL', 0x0080);
define('PARAM_LOCALURL', 0x0180); // NOT orthogonal to the others! Implies PARAM_URL!
define('PARAM_CLEANFILE',0x0200);
define('PARAM_ALPHANUM', 0x0400); //numbers or letters only
define('PARAM_BOOL', 0x0800); //convert to value 1 or 0 using empty()
define('PARAM_CLEANHTML',0x1000); //actual HTML code that you want cleaned and slashes removed
define('PARAM_ALPHAEXT', 0x2000); // PARAM_ALPHA plus the chars in quotes: "/-_" allowed
define('PARAM_SAFEDIR', 0x4000); // safe directory name, suitable for include() and require()
/**
* Definition of page types
*/
define('PAGE_COURSE_VIEW', 'course-view');
/// PARAMETER HANDLING ////////////////////////////////////////////////////
/**
* Returns a particular value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $id = required_param('id');
*
* @param string $varname the name of the parameter variable we want
* @param integer $options a bit field that specifies any cleaning needed
* @return mixed
*/
function required_param($varname, $options=PARAM_CLEAN) {
if (isset($_POST[$varname])) { // POST has precedence
$param = $_POST[$varname];
} else if (isset($_GET[$varname])) {
$param = $_GET[$varname];
} else {
error('A required parameter ('.$varname.') was missing');
}
return clean_param($param, $options);
}
/**
* Returns a particular value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $name = optional_param('name', 'Fred');
*
* @param string $varname the name of the parameter variable we want
* @param mixed $default the default value to return if nothing is found
* @param integer $options a bit field that specifies any cleaning needed
* @return mixed
*/
function optional_param($varname, $default=NULL, $options=PARAM_CLEAN) {
if (isset($_POST[$varname])) { // POST has precedence
$param = $_POST[$varname];
} else if (isset($_GET[$varname])) {
$param = $_GET[$varname];
} else {
return $default;
}
return clean_param($param, $options);
}
/**
* Used by {@link optional_param()} and {@link required_param()} to
* clean the variables and/or cast to specific types, based on
* an options field.
*
* @param mixed $param the variable we are cleaning
* @param integer $options a bit field that specifies the cleaning needed
* @return mixed
*/
function clean_param($param, $options) {
global $CFG;
if (!$options) {
return $param; // Return raw value
}
if ((string)$param == (string)(int)$param) { // It's just an integer
return (int)$param;
}
if ($options & PARAM_CLEAN) {
$param = stripslashes($param); // Needed by kses to work fine
$param = clean_text($param); // Sweep for scripts, etc
$param = addslashes($param); // Restore original request parameter slashes
}
if ($options & PARAM_INT) {
$param = (int)$param; // Convert to integer
}
if ($options & PARAM_ALPHA) { // Remove everything not a-z
$param = eregi_replace('[^a-zA-Z]', '', $param);
}
if ($options & PARAM_ALPHANUM) { // Remove everything not a-zA-Z0-9
$param = eregi_replace('[^A-Za-z0-9]', '', $param);
}
if ($options & PARAM_ALPHAEXT) { // Remove everything not a-zA-Z/_-
$param = eregi_replace('[^a-zA-Z/_-]', '', $param);
}
if ($options & PARAM_BOOL) { // Convert to 1 or 0
$param = empty($param) ? 0 : 1;
}
if ($options & PARAM_NOTAGS) { // Strip all tags completely
$param = strip_tags($param);
}
if ($options & PARAM_SAFEDIR) { // Remove everything not a-zA-Z0-9_-
$param = eregi_replace('[^a-zA-Z0-9_-]', '', $param);
}
if ($options & PARAM_CLEANFILE) { // allow only safe characters
$param = clean_filename($param);
}
if ($options & PARAM_FILE) { // Strip all suspicious characters from filename
$param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
$param = ereg_replace('\.\.+', '', $param);
if($param == '.') {
$param = '';
}
}
if ($options & PARAM_PATH) { // Strip all suspicious characters from file path
$param = str_replace('\\\'', '\'', $param);
$param = str_replace('\\"', '"', $param);
$param = str_replace('\\', '/', $param);
$param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
$param = ereg_replace('\.\.+', '', $param);
$param = ereg_replace('//+', '/', $param);
$param = ereg_replace('/(\./)+', '/', $param);
}
if ($options & PARAM_HOST) { // allow FQDN or IPv4 dotted quad
preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
// match ipv4 dotted quad
if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
// confirm values are ok
if ( $match[0] > 255
|| $match[1] > 255
|| $match[3] > 255
|| $match[4] > 255 ) {
// hmmm, what kind of dotted quad is this?
$param = '';
}
} elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
&& !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
&& !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
) {
// all is ok - $param is respected
} else {
// all is not ok...
$param='';
}
}
if ($options & PARAM_URL) { // allow safe ftp, http, mailto urls
include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
//
// Parameters to validateurlsyntax()
//
// s? scheme is optional
// H? http optional
// S? https optional
// F? ftp optional
// E? mailto optional
// u- user section not allowed
// P- password not allowed
// a? address optional
// I? Numeric IP address optional (can use IP or domain)
// p- port not allowed -- restrict to default port
// f? "file" path section optional
// q? query section optional
// r? fragment (anchor) optional
//
if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p-f?q?r?')) {
// all is ok, param is respected
} else {
$param =''; // not really ok
}
$options ^= PARAM_URL; // Turn off the URL bit so that simple PARAM_URLs don't test true for PARAM_LOCALURL
}
if ($options & PARAM_LOCALURL) {
// assume we passed the PARAM_URL test...
// allow http absolute, root relative and relative URLs within wwwroot
if (!empty($param)) {
if (preg_match(':^/:', $param)) {
// root-relative, ok!
} elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
// absolute, and matches our wwwroot
} else {
// relative - let's make sure there are no tricks
if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
// looks ok.
} else {
$param = '';
}
}
}
}
if ($options & PARAM_CLEANHTML) {
$param = stripslashes($param); // Remove any slashes
$param = clean_text($param); // Sweep for scripts, etc
$param = trim($param); // Sweep for scripts, etc
}
return $param;
}
/**
* For security purposes, this function will check that the currently
* given sesskey (passed as a parameter to the script or this function)
* matches that of the current user.
*
* @param string $sesskey optionally provided sesskey
* @return boolean
*/
function confirm_sesskey($sesskey=NULL) {
global $USER;
if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
return true;
}
if (empty($sesskey)) {
$sesskey = required_param('sesskey'); // Check script parameters
}
if (!isset($USER->sesskey)) {
return false;
}
return ($USER->sesskey === $sesskey);
}
/**
* Improved ensure a variable is set
* Issue a (custom) error message if not
* @param mixed $var the variable
* @param string $error optional additional error message
*/
function assert_var_set( $var, $error='' ) {
if (! isset($var)) {
error( "a required variable is not set - $error" );
}
}
/**
* Ensure that a variable is set
*
* If $var is undefined throw an error, otherwise return $var.
* This function will soon be made obsolete by {@link required_param()}
*
* @param mixed $var the variable which may be unset
* @param mixed $default the value to return if $var is unset
*/
function require_variable($var) {
if (! isset($var)) {
error('A required parameter was missing');
}
}
/**
* Ensure that a variable is set
*
* If $var is undefined set it (by reference), otherwise return $var.
*
* @param mixed $var the variable which may be unset
* @param mixed $default the value to return if $var is unset
*/
function optional_variable(&$var, $default=0) {
if (! isset($var)) {
$var = $default;
}
}
/**
* Set a key in global configuration
*
* Set a key/value pair in both this session's {@link $CFG} global variable
* and in the 'config' database table for future sessions.
*
* Can also be used to update keys for plugin-scoped configs in config_plugin table.
* In that case it doesn't affect $CFG.
*
* @param string $name the key to set
* @param string $value the value to set
* @param string $plugin (optional) the plugin scope
* @uses $CFG
* @return bool
*/
function set_config($name, $value, $plugin=NULL) {
/// No need for get_config because they are usually always available in $CFG
global $CFG;
if (empty($plugin)) {
$CFG->$name = $value; // So it's defined for this invocation at least
if (get_field('config', 'name', 'name', $name)) {
return set_field('config', 'value', $value, 'name', $name);
} else {
$config->name = $name;
$config->value = $value;
return insert_record('config', $config);
}
} else { // plugin scope
if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
return set_field('config_plugins', 'value', $value, 'id', $id);
} else {
$config->plugin = $plugin;
$config->name = $name;
$config->value = $value;
return insert_record('config_plugins', $config);
}
}
}
/**
* Get configuration values from the global config table
* or the config_plugins table.
*
* If called with no parameters it will do the right thing
* generating $CFG safely from the database without overwriting
* existing values.
*
* @param string $plugin
* @param string $name
* @uses $CFG
* @return hash-like object or single value
*
*/
function get_config($plugin=NULL, $name=NULL) {
global $CFG;
if (!empty($name)) { // the user is asking for a specific value
if (!empty($plugin)) {
return get_record('config_plugins', 'plugin' , $plugin, 'name', $name);
} else {
return get_record('config', 'name', $name);
}
}
// the user is after a recordset
if (!empty($plugin)) {
if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
$configs = (array)$configs;
$localcfg = array();
foreach ($configs as $config) {
$localcfg[$config->name] = $config->value;
}
return (object)$localcfg;
} else {
return false;
}
} else {
// this was originally in setup.php
if ($configs = get_records('config')) {
$localcfg = (array)$CFG;
foreach ($configs as $config) {
if (!isset($localcfg[$config->name])) {
$localcfg[$config->name] = $config->value;
} else {
if ($localcfg[$config->name] != $config->value ) {
// complain if the DB has a different
// value than config.php does
error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
}
}
}
$localcfg = (object)$localcfg;
return $localcfg;
} else {
// preserve $CFG if DB returns nothing or error
return $CFG;
}
}
}
/**
* Refresh current $USER session global variable with all their current preferences.
* @uses $USER
*/
function reload_user_preferences() {
global $USER;
if(empty($USER) || empty($USER->id)) {
return false;
}
unset($USER->preference);
if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
foreach ($preferences as $preference) {
$USER->preference[$preference->name] = $preference->value;
}
} else {
//return empty preference array to hold new values
$USER->preference = array();
}
}
/**
* Sets a preference for the current user
* Optionally, can set a preference for a different user object
* @uses $USER
* @todo Add a better description and include usage examples.
* @param string $name The key to set as preference for the specified user
* @param string $value The value to set forthe $name key in the specified user's record
* @param int $userid A moodle user ID
* @todo Add inline links to $USER and user functions in above line.
* @return boolean
*/
function set_user_preference($name, $value, $otheruser=NULL) {
global $USER;
if (empty($otheruser)){
if (!empty($USER) && !empty($USER->id)) {
$userid = $USER->id;
} else {
return false;
}
} else {
$userid = $otheruser;
}
if (empty($name)) {
return false;
}
if ($preference = get_record('user_preferences', 'userid', $userid, 'name', $name)) {
if (set_field('user_preferences', 'value', $value, 'id', $preference->id)) {
if (empty($otheruser) and !empty($USER)) {
$USER->preference[$name] = $value;
}
return true;
} else {
return false;
}
} else {
$preference->userid = $userid;
$preference->name = $name;
$preference->value = (string)$value;
if (insert_record('user_preferences', $preference)) {
if (empty($otheruser) and !empty($USER)) {
$USER->preference[$name] = $value;
}
return true;
} else {
return false;
}
}
}
/**
* Unsets a preference completely by deleting it from the database
* Optionally, can set a preference for a different user id
* @uses $USER
* @param string $name The key to unset as preference for the specified user
* @param int $userid A moodle user ID
* @return boolean
*/
function unset_user_preference($name, $userid=NULL) {
global $USER;
if (empty($userid)){
if(!empty($USER) && !empty($USER->id)) {
$userid = $USER->id;
}
else {
return false;
}
}
//Delete the preference from $USER
if (isset($USER->preference[$name])) {
unset($USER->preference[$name]);
}
//Then from DB
return delete_records('user_preferences', 'userid', $userid, 'name', $name);
}
/**
* Sets a whole array of preferences for the current user
* @param array $prefarray An array of key/value pairs to be set
* @param int $userid A moodle user ID
* @return boolean
*/
function set_user_preferences($prefarray, $userid=NULL) {
global $USER;
if (!is_array($prefarray) or empty($prefarray)) {
return false;
}
if (empty($userid)){
if (!empty($USER) && !empty($USER->id)) {
$userid = NULL; // Continue with the current user below
} else {
return false; // No-one to set!
}
}
$return = true;
foreach ($prefarray as $name => $value) {
// The order is important; if the test for return is done first, then
// if one function call fails all the remaining ones will be "optimized away"
$return = set_user_preference($name, $value, $userid) and $return;
}
return $return;
}
/**
* If no arguments are supplied this function will return
* all of the current user preferences as an array.
* If a name is specified then this function
* attempts to return that particular preference value. If
* none is found, then the optional value $default is returned,
* otherwise NULL.
* @param string $name Name of the key to use in finding a preference value
* @param string $default Value to be returned if the $name key is not set in the user preferences
* @param int $userid A moodle user ID
* @uses $USER
* @return string
*/
function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
global $USER;
if (empty($userid)) { // assume current user
if (empty($USER->preference)) {
return $default; // Default value (or NULL)
}
if (empty($name)) {
return $USER->preference; // Whole array
}
if (!isset($USER->preference[$name])) {
return $default; // Default value (or NULL)
}
return $USER->preference[$name]; // The single value
} else {
$preference = get_records_menu('user_preferences', 'userid', $userid, 'name', 'name,value');
if (empty($name)) {
return $preference;
}
if (!isset($preference[$name])) {
return $default; // Default value (or NULL)
}
return $preference[$name]; // The single value
}
}
/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
/**
* Given date parts in user time produce a GMT timestamp.
*
* @param int $year The year part to create timestamp of.
* @param int $month The month part to create timestamp of.
* @param int $day The day part to create timestamp of.
* @param int $hour The hour part to create timestamp of.
* @param int $minute The minute part to create timestamp of.
* @param int $second The second part to create timestamp of.
* @param float $timezone
* @return int timestamp
* @todo Finish documenting this function
*/
function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) {
$time = mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
} else {
$time = gmmktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
$time = usertime($time, $timezone);
if($applydst) {
$time -= dst_offset_on($time);
}
}
return $time;
}
/**
* Given an amount of time in seconds, returns string
* formatted nicely as months, days, hours etc as needed
*
* @uses MINSECS
* @uses HOURSECS
* @uses DAYSECS
* @param int $totalsecs ?
* @param array $str ?
* @return string
* @todo Finish documenting this function
*/
function format_time($totalsecs, $str=NULL) {
$totalsecs = abs($totalsecs);
if (!$str) { // Create the str structure the slow way
$str->day = get_string('day');
$str->days = get_string('days');
$str->hour = get_string('hour');
$str->hours = get_string('hours');
$str->min = get_string('min');
$str->mins = get_string('mins');
$str->sec = get_string('sec');
$str->secs = get_string('secs');
}
$days = floor($totalsecs/DAYSECS);
$remainder = $totalsecs - ($days*DAYSECS);
$hours = floor($remainder/HOURSECS);
$remainder = $remainder - ($hours*HOURSECS);
$mins = floor($remainder/MINSECS);
$secs = $remainder - ($mins*MINSECS);
$ss = ($secs == 1) ? $str->sec : $str->secs;
$sm = ($mins == 1) ? $str->min : $str->mins;
$sh = ($hours == 1) ? $str->hour : $str->hours;
$sd = ($days == 1) ? $str->day : $str->days;
$odays = '';
$ohours = '';
$omins = '';
$osecs = '';
if ($days) $odays = $days .' '. $sd;
if ($hours) $ohours = $hours .' '. $sh;
if ($mins) $omins = $mins .' '. $sm;
if ($secs) $osecs = $secs .' '. $ss;
if ($days) return $odays .' '. $ohours;
if ($hours) return $ohours .' '. $omins;
if ($mins) return $omins .' '. $osecs;
if ($secs) return $osecs;
return get_string('now');
}
/**
* Returns a formatted string that represents a date in user time
* <b>WARNING: note that the format is for strftime(), not date().</b>
* Because of a bug in most Windows time libraries, we can't use
* the nicer %e, so we have to use %d which has leading zeroes.
* A lot of the fuss in the function is just getting rid of these leading
* zeroes as efficiently as possible.
*
* If parameter fixday = true (default), then take off leading
* zero from %d, else mantain it.
*
* @uses HOURSECS
* @param int $date timestamp in GMT
* @param string $format strftime format
* @param float $timezone
* @param boolean $fixday If true (default) then the leading
* zero from %d is removed. If false then the leading zero is mantained.
* @return string
*/
function userdate($date, $format='', $timezone=99, $fixday = true) {
global $CFG;
static $strftimedaydatetime;
if ($format == '') {
if (empty($strftimedaydatetime)) {
$strftimedaydatetime = get_string('strftimedaydatetime');
}
$format = $strftimedaydatetime;
}
if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
$fixday = false;
} else if ($fixday) {
$formatnoday = str_replace('%d', 'DD', $format);
$fixday = ($formatnoday != $format);
}
$date += dst_offset_on($date);
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) { /// Server time
if ($fixday) {
$datestring = strftime($formatnoday, $date);
$daystring = str_replace(' 0', '', strftime(' %d', $date));
$datestring = str_replace('DD', $daystring, $datestring);
} else {
$datestring = strftime($format, $date);
}
} else {
$date += (int)($timezone * 3600);
if ($fixday) {
$datestring = gmstrftime($formatnoday, $date);
$daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
$datestring = str_replace('DD', $daystring, $datestring);
} else {
$datestring = gmstrftime($format, $date);
}
}
return $datestring;
}
/**
* Given a $time timestamp in GMT (seconds since epoch),
* returns an array that represents the date in user time
*
* @uses HOURSECS
* @param int $time Timestamp in GMT
* @param float $timezone
* @return array An array that represents the date in user time
* @todo Finish documenting this function
*/
function usergetdate($time, $timezone=99) {
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) { // Server time
return getdate($time);
}
// There is no gmgetdate so we use gmdate instead
$time += dst_offset_on($time);
$time += intval((float)$timezone * HOURSECS);
$datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
list(
$getdate['seconds'],
$getdate['minutes'],
$getdate['hours'],
$getdate['mday'],
$getdate['mon'],
$getdate['year'],
$getdate['wday'],
$getdate['yday'],
$getdate['weekday'],
$getdate['month']
) = explode('_', $datestring);
return $getdate;
}
/**
* Given a GMT timestamp (seconds since epoch), offsets it by
* the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
*
* @uses HOURSECS
* @param int $date Timestamp in GMT
* @param float $timezone
* @return int
*/
function usertime($date, $timezone=99) {
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) {
return $date;
}
return $date - (int)($timezone * HOURSECS);
}
/**
* Given a time, return the GMT timestamp of the most recent midnight
* for the current user.
*
* @param int $date Timestamp in GMT
* @param float $timezone ?
* @return ?
*/
function usergetmidnight($date, $timezone=99) {
$timezone = get_user_timezone_offset($timezone);
$userdate = usergetdate($date, $timezone);
// Time of midnight of this user's day, in GMT
return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
}
/**
* Returns a string that prints the user's timezone
*
* @param float $timezone The user's timezone
* @return string
*/
function usertimezone($timezone=99) {
$tz = get_user_timezone($timezone);
if (!is_float($tz)) {
return $tz;
}
if(abs($tz) > 13) { // Server time
return get_string('serverlocaltime');
}
if($tz == intval($tz)) {
// Don't show .0 for whole hours
$tz = intval($tz);
}
if($tz == 0) {
return 'GMT';
}
else if($tz > 0) {
return 'GMT+'.$tz;
}
else {
return 'GMT'.$tz;
}
}
/**
* Returns a float which represents the user's timezone difference from GMT in hours
* Checks various settings and picks the most dominant of those which have a value
*
* @uses $CFG
* @uses $USER
* @param float $tz The user's timezone
* @return int
*/
function get_user_timezone_offset($tz = 99) {
global $USER, $CFG;
$tz = get_user_timezone($tz);
if (is_float($tz)) {
return $tz;
} else {
$tzrecord = get_timezone_record($tz);
if (empty($tzrecord)) {
return 99.0;
}
return (float)$tzrecord->gmtoff / HOURMINS;
}
}
function get_user_timezone($tz = 99) {
global $USER, $CFG;
$timezones = array(
$tz,
isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
isset($USER->timezone) ? $USER->timezone : 99,
isset($CFG->timezone) ? $CFG->timezone : 99,
);
$tz = 99;
while(($tz == '' || $tz == 99) && $next = each($timezones)) {
$tz = $next['value'];
}
return is_numeric($tz) ? (float) $tz : $tz;