/
functions.php
6460 lines (5832 loc) · 217 KB
/
functions.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
/* Most of WebCalendar's functions.
*
* @author Craig Knudsen <cknudsen@cknudsen.com>
* @copyright Craig Knudsen, <cknudsen@cknudsen.com>, http://www.k5n.us/cknudsen
* @license http://www.gnu.org/licenses/gpl.html GNU GPL
* @package WebCalendar
*/
/* Functions start here. All non-function code should be above this.
*
* Note to developers:
* Documentation is generated from the function comments below.
* When adding/updating functions, please follow these conventions.
* Your cooperation in this matter is appreciated. :-)
*
* If you want your documentation to link to the db documentation,
* just make sure you mention the db table name followed by "table"
* on the same line. Here's an example:
* Retrieve preferences from the webcal_user_pref table.
*/
$tzInitSet = false;
/**
* Logs a debug message.
*
* Generally, we try not to leave calls to this function in the code.
* It is used for debugging only.
*
* @param string $msg Text to be logged
*/
function do_debug ( $msg ) {
// log to /tmp/webcal-debug.log
// error_log ( date ( 'Y-m-d H:i:s' ) . "> $msg\n<br />",
// 3, 'd:/php/logs/debug.txt' );
//$fd = fopen ( "/tmp/webcal.log", 'a+b' );
//fwrite ( $fd, date ( 'Y-m-d H:i:s' ) . "> $msg\n" );
//fclose ( $fd );
// 3, '/tmp/webcal-debug.log' );
// error_log ( date ( 'Y-m-d H:i:s' ) . "> $msg\n",
// 2, 'sockieman:2000' );
}
/**
* Looks for URLs in the given text, and makes them into links.
*
* @param string $text Input text
*
* @return string The text altered to have HTML links for any web links.
*/
function activate_urls( $text ) {
return preg_replace( '/[a-z]+:\/\/[^<> \t\r\n]+[a-z0-9\/]/i',
'<a href="\\0">\\0</a>', $text );
}
/**
* Adds something to the activity log for an event.
*
* The information will be saved to the webcal_entry_log table.
*
* @param int $event_id Event ID
* @param string $user Username of user doing this
* @param string $user_cal Username of user whose calendar is affected
* @param string $type Type of activity we are logging:
* - LOG_APPROVE
* - LOG_APPROVE_T
* - LOG_ATTACHMENT
* - LOG_COMMENT
* - LOG_CREATE
* - LOG_CREATE_T
* - LOG_DELETE
* - LOG_DELETE_T
* - LOG_LOGIN_FAILURE
* - LOG_NEWUSER_FULL
* - LOG_NEWUSEREMAIL
* - LOG_NOTIFICATION
* - LOG_REJECT
* - LOG_REJECT_T
* - LOG_REMINDER
* - LOG_UPDATE
* - LOG_UPDATE_T
* - LOG_USER_ADD
* - LOG_USER_DELETE
* - LOG_USER_UPDATE
* @param string $text Text comment to add with activity log entry
*/
function activity_log ( $event_id, $user, $user_cal, $type, $text ) {
$next_id = 1;
if ( empty ( $type ) ) {
echo translate ( 'Error Type not set for activity log!' );
// But don't exit since we may be in mid-transaction.
return;
}
$res = dbi_execute ( 'SELECT MAX( cal_log_id ) FROM webcal_entry_log' );
if ( $res ) {
if ( $row = dbi_fetch_row ( $res ) )
$next_id = $row[0] + 1;
dbi_free_result ( $res );
}
$sql = 'INSERT INTO webcal_entry_log ( cal_log_id, cal_entry_id, cal_login,
cal_user_cal, cal_type, cal_date, cal_time, cal_text )
VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )';
if ( ! dbi_execute ( $sql, [$next_id, $event_id, $user,
( empty ( $user_cal ) ? null : $user_cal ), $type, gmdate ( 'Ymd' ),
gmdate ( 'Gis' ), ( empty ( $text ) ? null : $text )] ) )
db_error ( true, $sql );
}
/**
* Get the corrected timestamp after adding or subtracting ONE_HOUR
* to compensate for DST.
*/
function add_dstfree_time ( $date, $span, $interval = 1 ) {
$ctime = date ( 'G', $date );
$date += $span * $interval;
$dtime = date ( 'G', $date );
if ( $ctime == $dtime )
return $date;
elseif ( $ctime == 23 && $dtime == 0 )
$date -= 3600;
elseif ( ( $ctime == 0 && $dtime == 23 ) || $ctime > $dtime )
$date += 3600;
elseif ( $ctime < $dtime )
$date -= 3600;
return $date;
}
/**
* Return the time in HHMMSS format of input time + duration
*
* @param string $time format "235900"
* @param int $duration number of minutes
*
* @return string The time in HHMMSS format.
*/
function add_duration ( $time, $duration ) {
$time = sprintf ( "%06d", $time );
$minutes =
intval ( $time / 10000 ) * 60 + ( ( $time / 100 ) % 100 ) + $duration;
// If we ran past 240000, then roll back over to 000000.
$minutes %= ( 24 * 60 );
return sprintf ( "%d%02d00", $minutes / 60, $minutes % 60 );
}
/**
* Bump UNIX local timestamp with the given duration.
*
* param int $ts input timestamp
* param int $hour hour duration
* param int $minute minute duration
* param int $second second duration
* param int $month month duration
* param int $day day duration
* param int $year year duration
*
* This function overcomes problems due to daylight saving change dates;
* it is based on the fact that function mktime() accepts out of range data.
*/
function bump_local_timestamp( $ts, $hour = 0, $minute = 0, $second = 0,
$month = 0, $day = 0, $year = 0 ) {
return mktime( date( 'G', $ts ) + $hour, date( 'i', $ts ) + $minute,
date( 's', $ts ) + $second, date( 'n', $ts ) + $month,
date( 'j', $ts ) + $day, date( 'Y', $ts ) + $year );
}
/**
* Builds the HTML for the event label.
*
* @param string $can_access
* @param string $time_only
*
* @return string The HTML for the event label
*/
function build_entry_label ( $event, $popupid,
$can_access, $timestr, $time_only = 'N' ) {
global $eventinfo, $login, $SUMMARY_LENGTH, $UAC_ENABLED, $user;
$ret = '';
// Get reminders display string.
$reminder = getReminders( $event->getId(), true );
$can_access = ( $UAC_ENABLED == 'Y' ? $can_access : 0 );
$not_my_entry = ( ( $login != $user && strlen ( $user ) ) ||
( $login != $event->getLogin() && strlen( $event->getLogin() ) ) );
$sum_length = $SUMMARY_LENGTH;
if( $event->isAllDay() || $event->isUntimed() )
$sum_length += 6;
$tmpAccess = $event->getAccess();
$tmpId = $event->getId();
$tmpLogin = $event->getLogin();
$tmpName = $event->getName();
$tmp_ret = htmlspecialchars ( substr ( $tmpName, 0, $sum_length )
. ( strlen ( $tmpName ) > $sum_length ? '...' : '' ) );
if ( $not_my_entry && $tmpAccess == 'R' && !
( $can_access &PRIVATE_WT ) ) {
if ( $time_only != 'Y' )
$ret = '<span class="parentheses">' . translate ( 'Private' ) . '</span>';
$eventinfo .= build_entry_popup ( $popupid, $tmpLogin,
str_replace ( 'XXX', translate ( 'private' ),
translate ( 'This event is XXX.' ) ), '' );
} else
if ( $not_my_entry && $tmpAccess == 'C' && !
( $can_access &CONF_WT ) ) {
if ( $time_only != 'Y' )
$ret = '(' . translate ( 'Conf.' ) . ')';
$eventinfo .= build_entry_popup ( $popupid, $tmpLogin,
str_replace ( 'XXX', translate ( 'confidential' ),
translate ( 'This event is XXX.' ) ), '' );
} else
if ( $can_access == 0 && $UAC_ENABLED == 'Y' ) {
if ( $time_only != 'Y' )
$ret = $tmp_ret;
$eventinfo .= build_entry_popup ( $popupid, $tmpLogin, '',
$timestr, '', '', $tmpName, '' );
} else {
if ( $time_only != 'Y' )
$ret = $tmp_ret;
$eventinfo .= build_entry_popup ( $popupid, $tmpLogin,
$event->getDescription(), $timestr, site_extras_for_popup( $tmpId ),
$event->getLocation(), $tmpName, $tmpId, $reminder );
}
return $ret;
}
/**
* Calculates which row/slot this time represents.
*
* This is used in day and week views where hours of the time are separeted
* into different cells in a table.
*
* <b>Note:</b> the global variable <var>$TIME_SLOTS</var> is used to determine
* how many time slots there are and how many minutes each is. This variable
* is defined user preferences (or defaulted to admin system settings).
*
* @param string $time Input time in HHMMSS format
* @param bool $round_down Should we change 1100 to 1059?
* (This will make sure a 10AM-100AM appointment just
* shows up in the 10AM slow and not in the 11AM slot
* also.)
*
* @return int The time slot index.
*/
function calc_time_slot ( $time, $round_down = false ) {
global $TIME_SLOTS;
$interval = 1440 / $TIME_SLOTS;
$mins_since_midnight = time_to_minutes ( sprintf ( "%06d", $time ) );
$ret = intval ( $mins_since_midnight / $interval );
if ( $round_down && $ret * $interval == $mins_since_midnight )
$ret--;
if ( $ret > $TIME_SLOTS )
$ret = $TIME_SLOTS;
return $ret;
}
/**
* Checks for conflicts.
*
* Find overlaps between an array of dates and the other dates in the database.
*
* Limits on number of appointments: if enabled in System Settings
* (<var>$LIMIT_APPTS</var> global variable), too many appointments can also
* generate a scheduling conflict.
*
* @todo Update this to handle exceptions to repeating events.
*
* @param array $dates Array of dates in Timestamp format that is
* checked for overlaps.
* @param int $duration Event duration in minutes
* @param int $eventstart GMT starttime timestamp
* @param array $participants Array of users whose calendars are to be checked
* @param string $login The current user name
* @param int $id Current event id (this keeps overlaps from
* wrongly checking an event against itself)
*
* @return Empty string for no conflicts or return the HTML of the
* conflicts when one or more are found.
*/
function check_for_conflicts ( $dates, $duration, $eventstart,
$participants, $login, $id ) {
global $LIMIT_APPTS, $LIMIT_APPTS_NUMBER, $repeated_events,
$single_user, $single_user_login, $jumpdate;
$datecnt = count ( $dates );
if ( ! $datecnt )
return false;
$conflicts = '';
$count = 0;
$evtcnt = $found = $query_params = [];
$partcnt = count ( $participants );
$hour = gmdate ( 'H', $eventstart );
$minute = gmdate ( 'i', $eventstart );
$allDayStr = translate ( 'All day event' );
$confidentialStr = translate ( 'Confidential' );
$exceedsStr = translate ( 'exceeds limit of XXX events per day' );
$onStr = translate ( 'on' );
$privateStr = translate ( 'Private' );
$sql = 'SELECT DISTINCT( weu.cal_login ), we.cal_time, we.cal_duration,
we.cal_name, we.cal_id, we.cal_access, weu.cal_status, we.cal_date
FROM webcal_entry we, webcal_entry_user weu WHERE we.cal_id = weu.cal_id AND ( ';
for ( $i = 0; $i < $datecnt; $i++ ) {
$sql .= ( $i != 0 ? ' OR ' : '' ) . 'we.cal_date = '
. gmdate ( 'Ymd', $dates[$i] );
}
$sql .= ' ) AND we.cal_time >= 0 AND weu.cal_status IN ( \'A\',\'W\' ) AND ( ';
if ( $single_user == 'Y' )
$participants[0] = $single_user_login;
else
if ( strlen ( $participants[0] ) == 0 )
// Likely called from a form with 1 user.
$participants[0] = $login;
for ( $i = 0; $i < $partcnt; $i++ ) {
$sql .= ( $i > 0 ? ' OR ' : '' ) . 'weu.cal_login = ?';
$query_params[] = $participants[$i];
}
// Make sure we don't get something past the end date of the event we're saving.
$res = dbi_execute ( $sql . ' )', $query_params );
if ( $res ) {
$duration1 = sprintf ( "%d", $duration );
$time1 = sprintf ( "%d%02d00", $hour, $minute );
while ( $row = dbi_fetch_row ( $res ) ) {
// Add to an array to see if it has been found already for the next part.
$found[$count++] = $row[4];
// See if events overlaps one another.
if ( $row[4] != $id ) {
$cntkey = $row[0] . '-' . $row[7];
$duration2 = $row[2];
$time2 = sprintf ( "%06d", $row[1] );
if ( empty ( $evtcnt[$cntkey] ) )
$evtcnt[$cntkey] = 0;
else
$evtcnt[$cntkey]++;
$over_limit = ( $LIMIT_APPTS == 'Y' && $LIMIT_APPTS_NUMBER > 0 &&
$evtcnt[$cntkey] >= $LIMIT_APPTS_NUMBER ? 1 : 0 );
if ( $over_limit ||
times_overlap ( $time1, $duration1, $time2, $duration2 ) ) {
$conflicts .= '
<li>';
if ( $single_user != 'Y' ) {
user_load_variables ( $row[0], 'conflict_' );
$conflicts .= $GLOBALS['conflict_fullname'] . ': ';
}
$conflicts .= ( $row[5] == 'C' && $row[0] != $login && !
$is_assistant && ! $is_nonuser_admin
// Assistants can see confidential stuff.
? '(' . $confidentialStr . ')'
: ( $row[5] == 'R' && $row[0] != $login
? '( ' . $privateStr . ')'
: '<a href="view_entry.php?id=' . $row[4]
. ( $row[0] != $login ? '&user=' . $row[0] : '' )
. '">' . $row[3] . '</a>' ) )
. ( $duration2 == 1440 && $time2 == 0
? ' (' . $allDayStr . ')'
: ' (' . display_time ( $row[7] . $time2 )
. ( $duration2 > 0
? '-' . display_time ( $row[7]
. add_duration ( $time2, $duration2 ) ) : '' ) . ')' )
. ' ' . $onStr . ' '
. date_to_str ( date ( 'Ymd', date_to_epoch ( $row[7]
. sprintf ( "%06d", $row[1] ) ) ) )
. ( $over_limit ? ' (' . str_replace ( 'XXX', $LIMIT_APPTS_NUMBER,
$exceedsStr ) . ')' : '' ) . '</li>';
}
}
}
dbi_free_result ( $res );
} else
db_error ( true );
for ( $q = 0; $q < $partcnt; $q++ ) {
// Read repeated events only once for a participant for performance reasons.
$jumpdate = gmdate ( 'Ymd', $dates[count ( $dates )-1] );
$repeated_events = query_events ( $participants[$q], true,
// This date filter is not necessary for functional reasons, but it
// eliminates some of the events that couldn't possibly match. This could
// be made much more complex to put more of the searching work onto the
// database server, or it could be dropped all together to put the
// searching work onto the client.
'AND ( we.cal_date <= ' . $jumpdate
. ' AND ( wer.cal_end IS NULL OR wer.cal_end >= '
. gmdate ( 'Ymd', $dates[0] ) . ' ) )' );
for ( $i = 0; $i < $datecnt; $i++ ) {
$dateYmd = gmdate ( 'Ymd', $dates[$i] );
$list = get_repeating_entries ( $participants[$q], $dateYmd );
for ( $j = 0, $listcnt = count ( $list ); $j < $listcnt; $j++ ) {
// OK we've narrowed it down to a day, now I just gotta check the time...
// I hope this is right...
$row = $list[$j];
if( $row->getID() != $id && ! in_array($row->getID(), $found )
&& ( $row->getExtForID() == '' || $row->getExtForID() != $id ) ) {
$time2 = sprintf( "%06d", $row->getTime() );
$duration2 = $row->getDuration();
if ( times_overlap ( $time1, $duration1, $time2, $duration2 ) ) {
$conflicts .= '
<li>';
if ( $single_user != 'Y' ) {
user_load_variables( $row->getLogin(), 'conflict_' );
$conflicts .= $GLOBALS['conflict_fullname'] . ': ';
}
$conflicts .= ( $row->getAccess() == 'C'
&& $row->getLogin() != $login && ! $is_assistant
&& ! $is_nonuser_admin
// Assistants can see confidential stuff.
? '(' . $confidentialStr . ')'
: ( $row->getAccess() == 'R' && $row->getLogin() != $login
? '(' . $privateStr . ')'
: '<a href="view_entry.php?id=' . $row->getID()
. ( ! empty ( $user ) && $user != $login
? '&user=' . $user : '' )
. '">' . $row->getName() . '</a>' ) )
. ' (' . display_time( $row->getDate() . $time2 )
. ( $duration2 > 0
? '-' . display_time( $row->getDate()
. add_duration ( $time2, $duration2 ) ) : '' )
. ')' . ' ' . $onStr . ' ' . date_to_str ( $dateYmd ) . '</li>';
}
}
}
}
}
return $conflicts;
}
/**
* Replaces unsafe characters with HTML encoded equivalents.
*
* @param string $value Input text
*
* @return string The cleaned text.
*/
function clean_html ( $value ) {
$value = htmlspecialchars ( $value, ENT_QUOTES );
$value = strtr ( $value, [
'(' => '(',
')' => ')'] );
return $value;
}
/**
* Removes non-digits from the specified text.
*
* @param string $data Input text
*
* @return string The converted text.
*/
function clean_int ( $data ) {
return preg_replace ( '/\D/', '', $data );
}
/**
* Removes whitespace from the specified text.
*
* @param string $data Input text
*
* @return string The converted text.
*/
function clean_whitespace ( $data ) {
return preg_replace ( '/\s/', '', $data );
}
/**
* Removes non-word characters from the specified text.
*
* @param string $data Input text
*
* @return string The converted text.
*/
function clean_word ( $data ) {
return preg_replace ( '/\W/', '', $data );
}
/**
* Combines the repeating and nonrepeating event arrays and sorts them
*
* The returned events will be sorted by time of day.
*
* @param array $ev Array of events
* @param array $rep Array of repeating events
*
* @return array Array of Events.
*/
function combine_and_sort_events ( $ev, $rep ) {
$ids = [];
// Repeating events show up in $ev and $rep.
// Record their ids and don't add them to the combined array.
foreach ( $rep as $obj ) {
$ids[] = $obj->getID();
}
foreach ( $ev as $obj ) {
if( ! in_array( $obj->getID(), $ids ) )
$rep[] = $obj;
}
usort ( $rep, 'sort_events' );
return $rep;
}
/**
* Draws a daily outlook style availability grid showing events that are
* approved and awaiting approval.
*
* @param string $date Date to show the grid for
* @param array $participants Which users should be included in the grid
* @param string $popup Not used
*
* @return string HTML to display matrix.
*/
function daily_matrix ( $date, $participants, $popup = '' ) {
global $CELLBG, $ENTRY_SLOTS, $events, $repeated_events, $TABLEBG, $THBG,
$THFG, $thismonth, $thisyear, $TIME_FORMAT, $TODAYCELLBG, $user_fullname,
$WORK_DAY_END_HOUR, $WORK_DAY_START_HOUR;
$allAttendeesStr = translate ( 'All Attendees' );
$busy = translate ( 'Busy' );
$cnt = count ( $participants );
$dateTS = date_to_epoch ( $date );
$first_hour = $WORK_DAY_START_HOUR;
$increment = intval ( 1440 /
( $ENTRY_SLOTS > 288 ? 288 : ( $ENTRY_SLOTS < 72 ? 72 : $ENTRY_SLOTS ) ) );
$last_hour = $WORK_DAY_END_HOUR;
$master = [];
$MouseOut = $MouseOver = $str = '';
$participant_pct = '20%'; //Use percentage.
$tentative = translate ( 'Tentative' );
$titleStr = ' title="' . translate ( 'Schedule an appointment for XXX.' ) . '">';
$viewMsg = translate ( 'View this entry' );
$hours = $last_hour - $first_hour;
$interval = intval ( 60 / $increment );
$cell_pct = intval ( 80 / ( $hours * $interval ) );
$style_width = ( $cell_pct > 0 ? 'style="width:' . $cell_pct . '%;"' : '' );
$thismonth = date ( 'm', $dateTS );
$thisyear = date ( 'Y', $dateTS );
$cols = ( ( $hours * $interval ) + 1 );
$ret = <<<EOT
<br />
<table class="aligncenter matrixd" style="width:'80%';"
>
<tr>
<td class="matrix" colspan="{$cols}"></td>
</tr>
<tr>
<th style="width:{$participant_pct};">
EOT;
$ret .= translate ( 'Participants' ) . '</th>';
$tentative = translate ( 'Tentative' );
$titleStr = ' title="' . translate ( 'Schedule an appointment for XXX.' ) . '">';
$viewMsg = translate ( 'View this entry' );
$hours = $last_hour - $first_hour;
$interval = intval ( 60 / $increment );
$cell_pct = intval ( 80 / ( $hours * $interval ) );
$cols = ( ( $hours * $interval ) + 1 );
$style_width = ( $cell_pct > 0 ? 'style="width:' . $cell_pct . '%;"' : '' );
$thismonth = date ( 'm', $dateTS );
$thisyear = date ( 'Y', $dateTS );
// Build a master array containing all events for $participants.
for ( $i = 0; $i < $cnt; $i++ ) {
/* Pre-Load the repeated events for quckier access. */
$repeated_events = read_repeated_events ( $participants[$i], $dateTS,
$dateTS, '' );
/* Pre-load the non-repeating events for quicker access. */
$events = read_events ( $participants[$i], $dateTS, $dateTS );
// Combine events for this date into a single array for easy processing.
$ALL = array_merge (
get_repeating_entries ( $participants[$i], $date ),
get_entries ( $date )
);
foreach ( $ALL as $E ) {
if( $E->getTime() == 0 ) {
$duration = 60 * $hours;
$time = $first_hour . '0000';
} else {
$duration = $E->getDuration();
$time = date( 'His', $E->getDateTimeTS() );
}
$hour = substr ( $time, 0, 2 );
$mins = substr ( $time, 2, 2 );
// Convert cal_time to slot.
$slot = $hour + substr ( $mins, 0, 1 );
// Convert cal_duration to bars.
$bars = $duration / $increment;
// Never replace 'A' with 'W'.
for ( $q = 0; $bars > $q; $q++ ) {
$slot = sprintf ( "%02.2f", $slot );
if ( strlen ( $slot ) == 4 )
$slot = '0' . $slot; // Add leading zeros.
$slot = $slot . ''; // Convert to a string.
if ( empty ( $master['_all_'][$slot] ) ||
( $master['_all_'][$slot]['stat'] != 'A' ) )
$master['_all_'][$slot]['stat'] = $E->getStatus();
if ( empty ( $master[$participants[$i]][$slot] ) ||
( $master[$participants[$i]][$slot]['stat'] != 'A' ) ) {
$master[$participants[$i]][$slot]['stat'] = $E->getStatus();
$master[$participants[$i]][$slot]['ID'] = $E->getID();
}
$slot = $slot + ( $increment * .01 );
if ( $slot - ( int )$slot >= .59 )
$slot = ( int )$slot + 1;
}
}
}
for( $i = $first_hour; $i < $last_hour; $i++ ) {
$hour = $i;
if ( $TIME_FORMAT == '12' ) {
$hour %= 12;
if ( $hour == 0 )
$hour = 12;
$hourfmt = '%d';
} else
$hourfmt = '%02d';
$halfway = intval ( ( $interval / 2 ) -1 );
for( $j = 0; $j < $interval; $j++ ) {
$inc_x_j = $increment * $j;
$str .= '
<td id="C' . ( $j + 1 ) . '" class="dailymatrix" ';
$tmpTitle = 'onmousedown="schedule_event( ' . $i . ','
. sprintf ( "%02d", $inc_x_j ) . ' );"' . $MouseOver . $MouseOut
. str_replace ( 'XXX', sprintf ( $hourfmt, $hour ) . ':' .
( $inc_x_j <= 9 ? '0' : '' ) . $inc_x_j, $titleStr );
switch ( $j ) {
case $halfway:
$k = ( $hour <= 9 ? '0' : substr ( $hour, 0, 1 ) );
$str .= 'style="width:' . $cell_pct . '%; text-align:right;" '
. $tmpTitle . $k . '</td>';
break;
case $halfway + 1:
$k = ( $hour <= 9 ? substr ( $hour, 0, 1 ) : substr ( $hour, 1, 2 ) );
$str .= 'style="width:' . $cell_pct . '%; text-align:left;" '
. $tmpTitle . $k . '</td>';
break;
default:
$str .= $style_width . $tmpTitle . ' </td>';
}
}
}
$ret .= $str . '
</tr>
<tr>
<td class="matrix" colspan="' . $cols . '"></td>
</tr>';
// Add user _all_ to beginning of $participants array.
array_unshift ( $participants, '_all_' );
// Javascript for cells.
// Display each participant.
for ( $i = 0; $i <= $cnt; $i++ ) {
if ( $participants[$i] != '_all_' ) {
// Load full name of user.
user_load_variables ( $participants[$i], 'user_' );
// Exchange space for to keep from breaking.
$user_nospace = preg_replace ( '/\s/', ' ', $user_fullname );
} else
$user_nospace = preg_replace ( '/\s/', ' ', $allAttendeesStr );
$ret .= '
<tr>
<th class="weekday" style="width:' . $participant_pct . ';">'
. $user_nospace . '</th>';
$col = 1;
// Check each timebar.
for ( $j = $first_hour; $j < $last_hour; $j++ ) {
for ( $k = 0; $k < $interval; $k++ ) {
$r = sprintf ( "%02d", $j ) . '.'
. sprintf ( "%02d", ( $increment * $k ) ) . '';
$space = ' ';
if ( empty ( $master[$participants[$i]][$r] ) ) {
// Ignore this..
} else
if ( empty ( $master[$participants[$i]][$r]['ID'] ) )
// This is the first line for 'all' users. No event here.
$space = '
<span class="matrix"><img src="images/pix.gif" alt="" /></span>';
else {
$tmpMast = $master[$participants[$i]][$r]['stat'];
if ( strpos ( 'AW', $tmpMast ) !== false )
$space = '
<a class="matrix" href="view_entry.php?id='
. $master[$participants[$i]][$r]['ID']
. '&friendly=1"><img src="images/pix' . ( $tmpMast = 'A' ? '' : 'b' )
. '.gif" title="' . $viewMsg . '" alt="' . $viewMsg . '" /></a>';
}
$ret .= '
<td class="matrixappts' . ( $k == '0' ? ' matrixledge' : '' ) . '" '
. $style_width . ( $space == ' ' ? ' '
. 'onmousedown="schedule_event( ' . $j . ','
. sprintf ( "%02d", ( $increment * $k ) ) . ' );"'
. " $MouseOver $MouseOut" : '' ) . '>' . $space . '</td>';
$col++;
}
}
$ret .= '</tr>';
} // End foreach participant.
return $ret . <<<EOT
</table><br />
<table class="aligncenter">
<tr>
<td class="matrixlegend"><img src="images/pix.gif" title="{$busy}"
alt="{$busy}" />{$busy} <img src="images/pixb.gif"
title="{$tentative}" alt="{$tentative}" />{$tentative}</td>
</tr>
</table>
EOT;
}
/**
* Date selection via DHTML.
* This will create two HTML elements:
* - a form element of type hidden that will hold the date value in
* YYYYMMDD format
* - a span element that will display the nicely formatted date to the user
* The CSS ids will be the datename parameter with '_fmt' and '_YMD'
* appended.
*/
function datesel_Print($datename, $ymdValue = '')
{
if (empty($ymdValue))
$ymdValue = date('Y-m-d');
if (strpos($ymdValue, '-') == false && strlen($ymdValue) == 8) {
// Convert YYYYMMDD into YYYY-MM-DD
$ymdValue = date("Y-m-d", strtotime($ymdValue));
}
return '<input type="date" name="' . $datename .
'_YMD" id="' . $datename . '_YMD" class="form-control" value="' .
$ymdValue . '">';
}
/**
* Generate HTML for a date selection for use in a form.
*
* @param string $prefix Prefix to use in front of form element names
* @param string $date Currently selected date (in YYYYMMDD format)
* @param bool $trigger Add onchange event trigger that
* calls javascript function $prefix_datechanged()
* @param int $num_years Number of years to display
*
* @return string HTML for the selection box.
*/
function date_selection($prefix, $date, $trigger = false, $num_years = 20)
{
if (empty($date)) {
$ymdValue = date('Y-m-d');
} else {
$ymdValue = date('Y-m-d', strtotime($date));
}
$trigger_str = (empty($trigger) ? '' : $prefix . 'datechanged();');
$onchange = (empty($trigger_str) ? '' : 'onchange="$trigger_str"');
return '<input type="date" name="' . $prefix .
'_YMD" id="' . $prefix . '_YMD" class="form-control" value="' .
$ymdValue . '" ' . $onchange . '>';
}
/**
* Converts a date to a timestamp.
*
* @param string $d Date in YYYYMMDD or YYYYMMDDHHIISS format
* @param bool $gmt Whether to use GMT or LOCAL
*
* @return int Timestamp representing, in UTC or LOCAL time.
*/
function date_to_epoch( $d, $gmt = true ) {
if ( $d == 0 )
return 0;
$dH = $di = $ds = 0;
if ( strlen ( $d ) == 13 ) { // Hour value is single digit.
$dH = substr ( $d, 8, 1 );
$di = substr ( $d, 9, 2 );
$ds = substr ( $d, 11, 2 );
}
if ( strlen ( $d ) == 14 ) {
$dH = substr ( $d, 8, 2 );
$di = substr ( $d, 10, 2 );
$ds = substr ( $d, 12, 2 );
}
if ( $gmt )
return gmmktime ( $dH, $di, $ds,
substr ( $d, 4, 2 ),
substr ( $d, 6, 2 ),
substr ( $d, 0, 4 ) );
else
return mktime ( $dH, $di, $ds,
substr ( $d, 4, 2 ),
substr ( $d, 6, 2 ),
substr ( $d, 0, 4 ) );
}
/**
* Converts a date in YYYYMMDD format into "Friday, December 31, 1999",
* "Friday, 12-31-1999" or whatever format the user prefers.
*
* @param string $indate Date in YYYYMMDD format
* @param string $format Format to use for date
* (default is "__month__ __dd__, __yyyy__")
* @param bool $show_weekday Should the day of week also be included?
* @param bool $short_months Should the abbreviated month names be used
* instead of the full month names?
* @param bool $forceTranslate Check to see if there is a translation for
* the specified data format. If there is, then use
* the translated format from the language file, but
* only if $DATE_FORMAT is language-defined.
*
* @return string Date in the specified format.
*
* @global string Preferred date format
*/
function date_to_str ( $indate, $format = '', $show_weekday = true,
$short_months = false, $forceTranslate = false ) {
global $DATE_FORMAT;
if ( strlen ( $indate ) == 0 )
$indate = date ( 'Ymd' );
// If they have not set a preference yet...
if ( $DATE_FORMAT === '' || $DATE_FORMAT === 'LANGUAGE_DEFINED' )
$DATE_FORMAT = translate ( '__month__ __dd__, __yyyy__' );
elseif ( $forceTranslate && $format !== '' && translation_exists ( $format ) )
$format = translate ( $format );
if ( empty ( $format ) )
$format = $DATE_FORMAT;
$y = intval ( $indate / 10000 );
$m = intval ( $indate / 100 ) % 100;
$d = $indate % 100;
$wday = strftime ( "%w", mktime ( 0, 0, 0, $m, $d, $y ) );
if ( $short_months ) {
$month = month_name ( $m - 1, 'M' );
$weekday = weekday_name ( $wday, 'D' );
} else {
$month = month_name ( $m - 1 );
$weekday = weekday_name ( $wday );
}
$ret = str_replace ( '__dd__', $d, $format );
$ret = str_replace ( '__j__', intval ( $d ), $ret );
$ret = str_replace ( '__mm__', $m, $ret );
$ret = str_replace ( '__mon__', $month, $ret );
$ret = str_replace ( '__month__', $month, $ret );
$ret = str_replace ( '__n__', sprintf ( "%02d", $m ), $ret );
$ret = str_replace ( '__yy__', sprintf ( "%02d", $y % 100 ), $ret );
return ( $show_weekday
? weekday_name ( strftime ( '%w', mktime ( 0, 0, 0, $m, $d, $y ) ),
( $short_months ? 'D' : '' ) ) . ', '
: '' ) . str_replace ( '__yyyy__', $y, $ret );
}
/**
* Extracts a user's name from a session id.
*
* This prevents users from begin able to edit their cookies.txt file and set
* the username in plain text.
*
* @param string $instr A hex-encoded string. "Hello" would be "678ea786a5".
*
* @return string The decoded string.
*
* @global array Array of offsets
*
* @see encode_string
*/
function decode_string ( $instr ) {
global $offsets;
$cntOffsets = count ( $offsets );
$orig = '';
for ( $i = 0, $cnt = strlen ( $instr ); $i < $cnt; $i += 2 ) {
$orig .= chr (
( hextoint ( substr ( $instr, $i, 1 ) ) * 16 +
hextoint ( substr ( $instr, $i + 1, 1 ) ) - $offsets[
( $i / 2 ) % $cntOffsets ] + 256 ) % 256 );
}
return $orig;
}
/**
* Display a text for a single activity log entry.
*
* @param string $cal_type the log entry type
* @param string $cal_text addiitonal text to display
*
* @return string HTML for one log entry.
*/
function display_activity_log( $cal_type, $cal_text = '', $break = '<br /> ' ) {
if ( $cal_type == LOG_APPROVE )
$ret = translate ( 'Event approved' );
elseif ( $cal_type == LOG_APPROVE_J )
$ret = translate ( 'Journal approved' );
elseif ( $cal_type == LOG_APPROVE_T )
$ret = translate ( 'Task approved' );
elseif ( $cal_type == LOG_ATTACHMENT )
$ret = translate ( 'Attachment' );
elseif ( $cal_type == LOG_COMMENT )
$ret = translate ( 'Comment' );
elseif ( $cal_type == LOG_CREATE )
$ret = translate ( 'Event created' );
elseif ( $cal_type == LOG_CREATE_J )
$ret = translate ( 'Journal created' );
elseif ( $cal_type == LOG_CREATE_T )
$ret = translate ( 'Task created' );
elseif ( $cal_type == LOG_DELETE )
$ret = translate ( 'Event deleted' );
elseif ( $cal_type == LOG_DELETE_J )
$ret = translate ( 'Journal deleted' );
elseif ( $cal_type == LOG_DELETE_T )
$ret = translate ( 'Task deleted' );
elseif ( $cal_type == LOG_LOGIN_FAILURE )
$ret = translate ( 'Invalid login' );
elseif ( $cal_type == LOG_NEWUSER_EMAIL )
$ret = translate ( 'New user via email (self registration)' );
elseif ( $cal_type == LOG_NEWUSER_FULL )
$ret = translate ( 'New user (self registration)' );
elseif ( $cal_type == LOG_NOTIFICATION )
$ret = translate ( 'Notification sent' );
elseif ( $cal_type == LOG_REJECT )
$ret = translate ( 'Event rejected' );
elseif ( $cal_type == LOG_REJECT_J )
$ret = translate ( 'Journal rejected' );
elseif ( $cal_type == LOG_REJECT_T )
$ret = translate ( 'Task rejected' );
elseif ( $cal_type == LOG_REMINDER )
$ret = translate ( 'Reminder sent' );
elseif ( $cal_type == LOG_UPDATE )
$ret = translate ( 'Event updated' );
elseif ( $cal_type == LOG_UPDATE_J )
$ret = translate ( 'Journal updated' );
elseif ( $cal_type == LOG_UPDATE_T )
$ret = translate ( 'Task updated' );
elseif ( $cal_type == LOG_USER_ADD )
$ret = translate ( 'Add User' );
elseif ( $cal_type == LOG_USER_DELETE )
$ret = translate ( 'Delete User' );
elseif ( $cal_type == LOG_USER_UPDATE )
$ret = translate ( 'Edit User' );
else
$ret = '???';
//fix any broken special characters
$cal_text = preg_replace( "/&(#[0-9]+|[a-z]+);/i", "&$1;",
htmlentities( $cal_text ) );
return $ret
. ( empty ( $cal_text ) ? '' : $break . $cal_text );
}
/**
* Display the <<Admin link on pages if menus are not enabled
*
* @param bool $break If true, include break if empty
*
* @return string HTML for Admin Home link
* @global string (Y/N) Is the Top Menu Enabled
*/
function display_admin_link($break = true) {
global $MENU_ENABLED;