-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.php
More file actions
executable file
·1391 lines (1201 loc) · 51.3 KB
/
format.php
File metadata and controls
executable file
·1391 lines (1201 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//todo ~ deprecate this entire library and start a string library?
error_debug('including format.php', __file__, __line__);
function format_accents_convert($string) {
$string = html_entity_decode($string);
$transliterations = array('á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A', 'ă' => 'a', 'Ă' => 'A', 'â' => 'a', 'Â' => 'A', 'å' => 'a', 'Å' => 'A', 'ã' => 'a', 'Ã' => 'A', 'ą' => 'a', 'Ą' => 'A', 'ā' => 'a', 'Ā' => 'A', 'ä' => 'ae', 'Ä' => 'AE', 'æ' => 'ae', 'Æ' => 'AE', 'ḃ' => 'b', 'Ḃ' => 'B', 'ć' => 'c', 'Ć' => 'C', 'ĉ' => 'c', 'Ĉ' => 'C', 'č' => 'c', 'Č' => 'C', 'ċ' => 'c', 'Ċ' => 'C', 'ç' => 'c', 'Ç' => 'C', 'ď' => 'd', 'Ď' => 'D', 'ḋ' => 'd', 'Ḋ' => 'D', 'đ' => 'd', 'Đ' => 'D', 'ð' => 'dh', 'Ð' => 'Dh', 'é' => 'e', 'É' => 'E', 'è' => 'e', 'È' => 'E', 'ĕ' => 'e', 'Ĕ' => 'E', 'ê' => 'e', 'Ê' => 'E', 'ě' => 'e', 'Ě' => 'E', 'ë' => 'e', 'Ë' => 'E', 'ė' => 'e', 'Ė' => 'E', 'ę' => 'e', 'Ę' => 'E', 'ē' => 'e', 'Ē' => 'E', 'ḟ' => 'f', 'Ḟ' => 'F', 'ƒ' => 'f', 'Ƒ' => 'F', 'ğ' => 'g', 'Ğ' => 'G', 'ĝ' => 'g', 'Ĝ' => 'G', 'ġ' => 'g', 'Ġ' => 'G', 'ģ' => 'g', 'Ģ' => 'G', 'ĥ' => 'h', 'Ĥ' => 'H', 'ħ' => 'h', 'Ħ' => 'H', 'í' => 'i', 'Í' => 'I', 'ì' => 'i', 'Ì' => 'I', 'î' => 'i', 'Î' => 'I', 'ï' => 'i', 'Ï' => 'I', 'ĩ' => 'i', 'Ĩ' => 'I', 'į' => 'i', 'Į' => 'I', 'ī' => 'i', 'Ī' => 'I', 'ĵ' => 'j', 'Ĵ' => 'J', 'ķ' => 'k', 'Ķ' => 'K', 'ĺ' => 'l', 'Ĺ' => 'L', 'ľ' => 'l', 'Ľ' => 'L', 'ļ' => 'l', 'Ļ' => 'L', 'ł' => 'l', 'Ł' => 'L', 'ṁ' => 'm', 'Ṁ' => 'M', 'ń' => 'n', 'Ń' => 'N', 'ň' => 'n', 'Ň' => 'N', 'ñ' => 'n', 'Ñ' => 'N', 'ņ' => 'n', 'Ņ' => 'N', 'ó' => 'o', 'Ó' => 'O', 'ò' => 'o', 'Ò' => 'O', 'ô' => 'o', 'Ô' => 'O', 'ő' => 'o', 'Ő' => 'O', 'õ' => 'o', 'Õ' => 'O', 'ø' => 'oe', 'Ø' => 'OE', 'ō' => 'o', 'Ō' => 'O', 'ơ' => 'o', 'Ơ' => 'O', 'ö' => 'oe', 'Ö' => 'OE', 'ṗ' => 'p', 'Ṗ' => 'P', 'ŕ' => 'r', 'Ŕ' => 'R', 'ř' => 'r', 'Ř' => 'R', 'ŗ' => 'r', 'Ŗ' => 'R', 'ś' => 's', 'Ś' => 'S', 'ŝ' => 's', 'Ŝ' => 'S', 'š' => 's', 'Š' => 'S', 'ṡ' => 's', 'Ṡ' => 'S', 'ş' => 's', 'Ş' => 'S', 'ș' => 's', 'Ș' => 'S', 'ß' => 'SS', 'ť' => 't', 'Ť' => 'T', 'ṫ' => 't', 'Ṫ' => 'T', 'ţ' => 't', 'Ţ' => 'T', 'ț' => 't', 'Ț' => 'T', 'ŧ' => 't', 'Ŧ' => 'T', 'ú' => 'u', 'Ú' => 'U', 'ù' => 'u', 'Ù' => 'U', 'ŭ' => 'u', 'Ŭ' => 'U', 'û' => 'u', 'Û' => 'U', 'ů' => 'u', 'Ů' => 'U', 'ű' => 'u', 'Ű' => 'U', 'ũ' => 'u', 'Ũ' => 'U', 'ų' => 'u', 'Ų' => 'U', 'ū' => 'u', 'Ū' => 'U', 'ư' => 'u', 'Ư' => 'U', 'ü' => 'ue', 'Ü' => 'UE', 'ẃ' => 'w', 'Ẃ' => 'W', 'ẁ' => 'w', 'Ẁ' => 'W', 'ŵ' => 'w', 'Ŵ' => 'W', 'ẅ' => 'w', 'Ẅ' => 'W', 'ý' => 'y', 'Ý' => 'Y', 'ỳ' => 'y', 'Ỳ' => 'Y', 'ŷ' => 'y', 'Ŷ' => 'Y', 'ÿ' => 'y', 'Ÿ' => 'Y', 'ź' => 'z', 'Ź' => 'Z', 'ž' => 'z', 'Ž' => 'Z', 'ż' => 'z', 'Ż' => 'Z', 'þ' => 'th', 'Þ' => 'Th', 'µ' => 'u', 'а' => 'a', 'А' => 'a', 'б' => 'b', 'Б' => 'b', 'в' => 'v', 'В' => 'v', 'г' => 'g', 'Г' => 'g', 'д' => 'd', 'Д' => 'd', 'е' => 'e', 'Е' => 'E', 'ё' => 'e', 'Ё' => 'E', 'ж' => 'zh', 'Ж' => 'zh', 'з' => 'z', 'З' => 'z', 'и' => 'i', 'И' => 'i', 'й' => 'j', 'Й' => 'j', 'к' => 'k', 'К' => 'k', 'л' => 'l', 'Л' => 'l', 'м' => 'm', 'М' => 'm', 'н' => 'n', 'Н' => 'n', 'о' => 'o', 'О' => 'o', 'п' => 'p', 'П' => 'p', 'р' => 'r', 'Р' => 'r', 'с' => 's', 'С' => 's', 'т' => 't', 'Т' => 't', 'у' => 'u', 'У' => 'u', 'ф' => 'f', 'Ф' => 'f', 'х' => 'h', 'Х' => 'h', 'ц' => 'c', 'Ц' => 'c', 'ч' => 'ch', 'Ч' => 'ch', 'ш' => 'sh', 'Ш' => 'sh', 'щ' => 'sch', 'Щ' => 'sch', 'ъ' => '', 'Ъ' => '', 'ы' => 'y', 'Ы' => 'y', 'ь' => '', 'Ь' => '', 'э' => 'e', 'Э' => 'e', 'ю' => 'ju', 'Ю' => 'ju', 'я' => 'ja', 'Я' => 'ja');
return str_replace(array_keys($transliterations), array_values($transliterations), $string);
}
function format_accents_encode($string) {
//not sure if this is necessary anymore with the conversion to utf8
//update: it is, email not supporting utf8
$string = str_replace('“', '“', $string);
$string = str_replace('”', '”', $string);
$string = str_replace('‘', '‘', $string);
$string = str_replace('’', '’', $string);
$string = str_replace('–', '–', $string);
$string = str_replace('—', '—', $string);
$string = str_replace('ä', 'ä', $string);
$string = str_replace('ë', 'ë', $string);
$string = str_replace('ï', 'ï', $string);
$string = str_replace('ö', 'ö', $string);
$string = str_replace('ü', 'ü', $string);
$string = str_replace('á', 'á', $string);
$string = str_replace('é', 'é', $string);
$string = str_replace('í', 'í', $string);
$string = str_replace('ó', 'ó', $string);
$string = str_replace('ú', 'ú', $string);
$string = str_replace('à', 'à', $string);
$string = str_replace('è', 'è', $string);
$string = str_replace('ì', 'ì', $string);
$string = str_replace('ò', 'ò', $string);
$string = str_replace('ù', 'ù', $string);
$string = str_replace('ç', 'ç', $string);
$string = str_replace('ñ', 'ñ', $string);
return $string;
}
function format_accents_remove($string) {
//translate accents
$string = html_entity_decode($string);
$from = 'áàäâçéèëêíìïîóòöôøúùüûñ';
$to = 'aaaaceeeeiiiiooooouuuun';
$string = str_replace('’', "'", $string);
$string = str_replace('‘', "'", $string);
$string = str_replace('&rdsquo;', '"', $string);
$string = str_replace('&ldsquo;', '"', $string);
return strtr(utf8_decode($string), utf8_decode($from), $to);
}
function format_array_text($array, $separator='and') {
if (!is_array($array)) {
//string
return $array;
} elseif (!count($array)) {
//empty array
return '';
} elseif (count($array) == 1) {
return $array[0];
} else {
$last = array_pop($array);
return implode(', ', $array) . ' ' . $separator . ' ' . $last;
}
}
function format_ascii($string) {
//used by draw_link() for email obfuscation
$len = strlen($string);
$return = '';
for ($i = 0; $i < $len; $i++) $return .= '&#' . ord($string[$i]) . ';';
return $return;
}
function format_binary($blob) {
//todo -- db_binary?
global $_josh;
if ($_josh['db']['language'] == 'mssql') {
$return = unpack('H*hex', $blob);
return '0x' . $return['hex'];
} elseif ($_josh['db']['language'] == 'mysql') {
return '"' . addslashes($blob) . '"';
}
}
function format_boolean($value, $options='Yes|No') {
list($yes, $no) = explode('|', $options);
if ($value) return $yes;
return $no;
}
function format_check($variable, $type='int') {
//todo compile a set of cases where we use format_check, format_num, format_numeric, format_verify. i think this can be simplifed
//alias
return format_verify($variable, $type);
}
function format_class($string) {
//used by draw_nav and admiral center to derive an HTML-safe class name from a URL
$string = str_replace('/', '', $string);
$string = str_replace('?', '_', $string);
$string = str_replace('=', '_', $string);
if (empty($string)) $string = 'home';
return $string;
}
function format_code($code) {
//afaik this is just for formatting error messages.
return '<p style="font-family:courier; font-size:13px;">' . nl2br(str_replace('\t', ' ', htmlentities($code))) . '</p>';
}
function format_date($timestamp=false, $error='', $format=false, $relativetime=true, $todaytime=false) {
global $_josh;
if ($timestamp === false) $timestamp = time();
if (!$format) $format = $_josh['date']['format'];
//reject or convert
if (empty($timestamp) || ($timestamp == 'Jan 1 1900 12:00AM')) return $error;
if (!is_int($timestamp)) $timestamp = strToTime($timestamp);
//special thing to format for sql
if (stristr($format, 'sql')) return date('Y-m-d H:i:00', $timestamp);
//special thing to format for sql
if ($format == 'unix') return date('U', $timestamp);
if ($relativetime) {
//get timestamp for today
$todaysdate = mktime(0, 0, 1, $_josh['month'], $_josh['today'], $_josh['year']);
//get timestamp for argument, without time
$returnday = date('d', $timestamp);
$returnyear = date('Y', $timestamp);
$returnmonth = date('n', $timestamp);
$returndate = mktime(0, 0, 1, $returnmonth, $returnday, $returnyear);
//setup return date
$datediff = ($returndate - $todaysdate) / 86400;
if ($datediff == 0) {
$return = ($todaytime) ? format_time($timestamp) : $_josh['date']['strings'][1];
} elseif ($datediff == -1) {
$return = $_josh['date']['strings'][0];
} elseif ($datediff == 1) {
$return = $_josh['date']['strings'][2];
} elseif (($datediff < -1) && ($datediff > -7)) { //last six days
$return = strftime('%A', $timestamp); //return day of week
//$return = date('l', $timestamp); //return day of week
} else {
$return = strftime($format, $timestamp);
//$return = date($format, $timestamp); //M d, Y
}
} else {
$return = strftime($format, $timestamp);
//$return = date($format, $timestamp);
}
if ($return === 1) return $error;
return draw_tag('time', array('datetime'=>date('Y-m-d', $timestamp) . 'T' . date('H:i:s', $timestamp)), $return);
}
function format_date_iso8601($timestamp=false) {
//this looks like DATE_W3C http://www.php.net/manual/en/datetime.constants.php
//use this for xml
if (!$timestamp) $timestamp = time();
if (!is_int($timestamp)) $timestamp = strToTime($timestamp);
return date('Y-m-d', $timestamp) . 'T' . date('H:i:s', $timestamp) . '-07:00';
}
function format_date_rss($timestamp=false) {
//todo ~ define difference between this and format_date_iso8601 above?
if (!$timestamp) $timestamp = time();
if (!is_int($timestamp)) $timestamp = strToTime($timestamp);
return date(DATE_RSS, $timestamp);
}
function format_date_sql($month, $day=false, $year=false, $hour=false, $minute=false, $second=false) {
//format a date for sql
if (!$day || !$year) {
/* new functionality; month could be a timestamp that needs to be converted a sql-ready date
update 9/25/12: since when can this accept a month and nothing else? updating to return null for FSS
if (empty($month)) return 'NULL';
$date = strToTime($month);*/
return 'NULL';
} elseif (!$hour) {
//restore old defaults
$hour = 0;
$minute = 0;
$second = 1;
$date = mktime($hour, $minute, $second, $month, $day, $year);
} else {
$date = mktime($hour, $minute, $second, $month, $day, $year);
}
return '\'' . date('Y-m-d H:i:00', $date) . '\'';
}
function format_date_time($timestamp=false, $error='', $separator=' ', $suppressMidnight=true, $relativetime=true) {
//string_datetime?
if ($timestamp === false) $timestamp = time();
$return = format_date($timestamp, $error, false, $relativetime);
//if (($return == 'Today') || ($return == 'Yesterday') || ($return == 'Tomorrow'))
$time = format_time($timestamp);
if ($suppressMidnight && ($time == '12:00am')) return $return;
return $return . $separator . $time;
}
function format_date_range($start, $end, $separator='–') {
//return a string date range, like Jan 21-22 2010, or Jan 8 from 11-11:30am
if (!is_integer($start)) $start = strtotime($start);
if (!is_integer($end)) $end = strtotime($end);
if (date('Y', $start) == date('Y', $end)) {
if (date('n', $start) == date('n', $end)) {
if (date('j', $start) == date('j', $end)) {
//same day
return format_date($start);
}
//same month
return strftime('%b', $start) . ' ' . strftime('%e', $start) . $separator . strftime('%e', $end) . ', ' . strftime('%Y', $end);
}
//same year
return strftime('%b %e', $start) . $separator . strftime('%b %e', $end) . ', ' . strftime('%Y', $end);
}
//same year
return strftime('%b %e, %Y', $start) . $separator . strftime('%b %e, %Y', $end);
}
function format_date_time_range($start, $end) {
//return a string date range, like Jan 21-22 2010, or Jan 8 from 11-11:30am
if (!is_integer($start)) $start = strtotime($start);
if (!is_integer($end)) $end = strtotime($end);
if (date('Y', $start) == date('Y', $end)) {
if (date('n', $start) == date('n', $end)) {
if (date('j', $start) == date('j', $end)) {
if (date('a', $start) == date('a', $end)) {
//same am/pm
$starttime = (date('i', $start) == '00') ? date('g', $start) : date('g:i', $start);
$endtime = (date('i', $end) == '00') ? date('g', $end) : date('g:i', $end);
return format_date($start) . ' ' . $starttime . '-' . $endtime . date('a', $end);
}
//same day
return format_date($start) . ' from ' . format_time($start) . ' to ' . format_time($end);
}
//same month
return date('M', $start) . ' ' . date('j', $start) . '–' . date('j', $end) . ', ' . date('Y', $end);
}
//same year
return format_date_time($start, false, ' at ') . ' to ' . format_date_time($end, false, ' at ');
}
//different years
return format_date_time($start, false, ' at ') . ' to ' . format_date_time($end, false, ' at ');
}
function format_date_excel($timestamp) {
if (!empty($timestamp)) return @date('n/j/Y', strToTime($timestamp));
}
function format_date_xml($timestamp=false) {
//difference between this and format_date_rss and format_date_iso8601?
if (!$timestamp) $timestamp = 'now';
if (!empty($timestamp) && $timestamp) return @date('Y-m-d', strToTime($timestamp)) . 'T00:00:00.000';
}
function format_email($address) {
//clean up email address or return false if invalid
$address = trim($address);
$address = strToLower($address); //technically, local part could be case-sensitive, but i don't think this happens enough to be significant
$address = str_replace("'", '', $address);
$address = str_replace('"', '', $address);
$address = preg_replace('/\r/', '', $address);
$address = preg_replace('/\n/', '', $address);
//this section of code adapted from http://www.linuxjournal.com/article/9585
$atIndex = strrpos($address, "@");
if (is_bool($atIndex) && !$atIndex) {
return false; //no @ symbol
} else {
$domain = substr($address, $atIndex+1);
$local = substr($address, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
return false; //local part length wrong
} elseif ($domainLen < 1 || $domainLen > 255) {
return false; //domain part length wrong
} elseif ($local[0] == '.' || $local[$localLen-1] == '.') {
return false; //local part starts or ends with '.'
} elseif (preg_match('/\\.\\./', $local)) {
return false; //local part has two consecutive dots
} elseif (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
return false; //character not valid in domain part
} else if (preg_match('/\\.\\./', $domain)) {
return false; //domain part has two consecutive dots
} elseif (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", '', $local))) {
//character not valid in local part unless local part is quoted (and we just stripped the quotes, so)
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) return false;
}
//todo enable dns lookup
//if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) return false; //domain not found in DNS
}
return $address;
}
function format_file_name($str, $ext) {
//formatting for downloaded files
//TODO: only truly invalid characters should be checked. i'm sure it's ok to download files with spaces, for example.
$str = html_entity_decode($str);
$str = str_replace('"', '', $str);
$str = str_replace("'", '', $str);
$str = str_replace('.', '', $str);
$str = str_replace(':', '', $str);
$str = str_replace('/', '', $str);
$str = str_replace('\\', '', $str);
$str = str_replace(' ', ' ', $str);
$str = str_replace(' ', ' ', $str);
//$str = str_replace(' ', '_', $str);
$str = format_string($str, 60, ''); //substr($str, 0, 60);
return $str . '.' . $ext;
return strtolower($str . '.' . $ext);
}
function format_file_size($file) {
$size = @filesize($file);
return format_size($size);
}
function format_get($value) {
//returns int, decimal, text, textarea
//used by db_table_from_array
if (empty($value)) return false;
if (is_numeric($value) || is_numeric(str_replace(',', '', $value))) {
if (strstr($value, '.')) return 'decimal';
return 'int';
} elseif (strlen($value) > 255) {
return 'text';
}
return 'varchar';
}
function format_highlight($haystack, $needles=false) {
//sometimes you want to use a highlighter on html -- usually in search results
if (!$needles) return $haystack; //$needles is optional
if (is_array($needles)) $needles = implode('|', $needles);
//pattern is not yet bulletproof, but supports html now
//thanks to ddrudik at http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22713827.html
$pattern = '/(?<=^|[> ])(' . $needles . ')(?=$|[^a-z])/is';
return preg_replace($pattern, draw_span('highlight', '\\0'), $haystack);
}
function format_html($text, $profile='user') {
//profile can be public, user or admin, with decreasing restrictions
//todo tie this programmically to user() and admin()
//replace links not already in <a> tags
//why was this commented?
$bits = preg_split('/(<a(?:\s+[^>]*)?>.*?<\/a>|<[a-z][^>]*>)/is', $text, null, PREG_SPLIT_DELIM_CAPTURE);
$reconstructed = '';
foreach ($bits as $bit) {
if (strpos($bit, '<') !== 0) $bit = format_html_links($bit);
$reconstructed .= $bit;
}
$text = $reconstructed;
lib_get('simple_html_dom');
$html = str_get_html($text);
if (($profile == 'public') || ($profile == 'user')) $html->set_callback('cleanupUser');
//if ($profile == 'public') $html->set_callback('cleanupPublic');
//$html->set_callback('cleanupAdmin');
if (!function_exists('cleanupAdmin')) {
function cleanupAdmin() {
//todo
}
function cleanupPublic($e) {
//person off the street, aka hacker
if (in_array($e->tag, array('blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li'))) {
//replace these with <p> tags so as to keep the formatting but losing the styling
$e->outertext = ($e->innertext) ? '<p>' . $e->innertext . '</p>' : '';
} elseif (!in_array($e->tag, array('a', 'b', 'br', 'dir', 'div', 'hgroup', 'i', 'p', 'strike', 'strong', 'text'))) {
//narrower list of acceptable tags
$e->outertext = ($e->innertext) ? ' ' . $e->innertext . ' ' : '';
}
}
function cleanupUser($e) {
//this callback is used to clear out bad tags and attributes
//kill bad tags
//never want these tags, or anything inside them
$bad_tags = array('comment', 'form', 'label', 'input', 'link', 'noscript', 'script', 'select', 'style', 'textarea', 'unknown'); //new iframe whitelist
if (in_array($e->tag, $bad_tags)) tagUnset($e);
//these are the tags we want. if you're not one of these, remove but keep your contents eg <NYT_HEADLINE>
//what's a <text> tag? maybe this means actual text to simple_html_dom
if (!in_array($e->tag, array(
'a', 'article', 'aside', 'b', 'blockquote', 'br', 'caption', 'dir', 'div', 'dd', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'hr', 'i', 'iframe', 'img',
'ol', 'li', 'p', 'section', 'span', 'strike', 'strong', 'tbody', 'text', 'table', 'td', 'th', 'tr', 'ul',
'object', 'embed', 'param'
))) $e->outertext = ($e->innertext) ? $e->innertext : '';
//never want these attributes
$bad_attributes = array('onclick', 'onmouseout', 'onmouseover', 'onload');
foreach ($bad_attributes as $b) if (isset($e->$b)) unset($e->$b);
//certain tags we are wary of
if ($e->tag == 'a') {
if ($e->parent->tag == 'a') $e->parent->innertext = $e->innertext;
if ($local_url = format_text_starts(url_base(), $e->href)) {
//local hyperlinks if possible (except backend.livingcities.org situation)
if (url_base() != 'http://backend.livingcities.org') $e->href = $local_url;
}
if ($e->href) $e->href = strip_tags($e->href);
} elseif ($e->tag == 'b') {
//deprecated tag: replace <b> with <strong>
$e->outertext = '<strong>' . $e->innertext . '</strong>';
} elseif ($e->tag == 'i') {
//deprecated tag: replace <i> with <em>
$e->outertext = '<em>' . $e->innertext . '</em>';
} elseif ($e->tag == 'iframe') {
//be cautious with iframes, they can be malicious
if (!in_array(url_domain($e->src), array('google.com', 'vimeo.com', 'youtube.com'))) $e->outertext = '';
} elseif (($e->tag == 'p') && (!$e->innertext || ($e->innertext == ' '))) {
//kill empty p tags (msword and tinymce)
$e->outertext = '';
}
}
function tagUnset($e) {
if (@$e->children) foreach($e->children as $f) tagUnset($f);
if (@$e->innertext) $e->innertext = '';
if (@$e->outertext) $e->outertext = '';
}
}
//reset html to get rid of artifacts and compress
$text = trim($html->save());
$html->clear();
//special josh function to replace email addresses with obfuscated ones via format_ascii
preg_match_all("/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i", $text, $matches);
foreach ($matches[0] as $m) $text = str_replace($m, format_ascii($m), $text);
$text = str_replace(' ', ' ', $text);
return $text;
}
function format_html_entities($string) {
//$string = htmlentities($string);
$string = str_replace('‘', '‘', $string); //left single quote
$string = str_replace('’', '’', $string); //right single quote
$string = str_replace('“', '“', $string); //left double quote
$string = str_replace('”', '”', $string); //right double quote
$string = str_replace('—', '—', $string); //em dash
return $string;
}
function format_html_img($url, $text=false) {
//returns the largest (jpg) image from the specified $url or within the provided $text
//you have to provide the URL because it might need to correct the images
lib_get('simple_html_dom');
$found = array();
if (!$text) $text = url_get($url);
if ($text) {
$text = str_get_html($text);
$images = array();
$supported_types = array('jpg', 'tif', 'png', 'jpeg');
//first, look for facebook share title http://developers.facebook.com/docs/share/
$blocks = $text->find('meta');
foreach ($blocks as $b) if (($b->property == 'og:image') && (file_type($b->content) == 'jpg')) return trim($b->content);
//quick search for <link rel="image_src">,
$blocks = $text->find('link');
foreach ($blocks as $b) if (($b->rel == 'image_src') && $b->href && (file_type($b->href) == 'jpg')) {
if($b->width && $b->height) {
$area = $b->width * $b->height;
max_num($area);
error_debug('<b>' . __function__ . '</b> <link> using ' . htmlentities($b) . ' with area ' . $area, __file__, __line__);
$images[$area] = $b->href;
}
}
//loop through images
$blocks = $text->find('img');
error_debug('<b>' . __function__ . '</b> found ' . count($blocks) . ' images within ' . strlen($text) . ' char text', __file__, __line__);
foreach ($blocks as $b) {
if ($b->width && $b->height && (in_array(file_type($b->src), $supported_types))) {
$area = $b->width * $b->height;
max_num($area);
error_debug('<b>' . __function__ . '</b> using ' . htmlentities($b) . ' with area ' . $area, __file__, __line__);
$images[$area] = $b->src;
} else {
error_debug('<b>' . __function__ . '</b> skipping ' . htmlentities($b) . ' because either width, height or src is missing or src is not jpg', __file__, __line__);
}
}
if ($max = max_num()) {
error_debug('<b>' . __function__ . '</b> found max, which was ' . $max, __file__, __line__);
if (substr($images[$max], 0, 1) == '/') {
$url = url_parse($url);
$images[$max] = $url['base'] . $images[$max];
}
error_debug('<b>' . __function__ . '</b> returning ' . $images[$max], __file__, __line__);
return $images[$max];
} else {
error_debug('<b>' . __function__ . '</b> not returning anything', __file__, __line__);
return false;
}
} else {
error_debug('<b>' . __function__ . '</b> quitting because no text', __file__, __line__);
return false;
}
}
function format_html_links($str) {
//from here: http://snipplr.com/view/2371/regex-regular-expression-to-match-a-url/
//$regex = '@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@';
//daring fireball regex, can't get it to encapsulate correctly (from here: http://daringfireball.net/2010/07/improved_regex_for_matching_urls)
$regex = '@((?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’])))@';
$matches = array();
if ($num = preg_match_all($regex, $str, $matches)) {
$matches = array_unique($matches[0]);
//echo 'matches were ' . draw_array($matches);
foreach($matches as $m) {
if (format_text_starts('http://', $m) || format_text_starts('https://', $m)) {
$str = str_replace($m, draw_link($m, $m), $str);
} else {
$str = str_replace($m, draw_link('http://' . $m, $m), $str);
}
}
}
return $str;
}
function format_html_paragraphs($text, $limit=false) {
lib_get('simple_html_dom');
$text = str_get_html($text);
//first, look for facebook share or meta description http://developers.facebook.com/docs/share/
$blocks = $text->find('meta');
foreach ($blocks as $b) if (($b->property == 'og:description') || ($b->name == 'description')) return trim($b->content);
//otherwise loop through paragraphs and sentences
$blocks = $text->find('p');
error_debug('<b>' . __function__ . '</b> found ' . count($blocks) . ' ps within ' . strlen($text) . ' char text', __file__, __line__);
$return = '';
$total_length = 0;
foreach ($blocks as $b) {
if (!$b->class) {
$b = draw_p(strip_tags($b));
$length = strlen($b);
if ($limit && $length + $total_length > $limit) {
if (!$total_length) {
$sentences = array_separated(strip_tags($b), '.');
error_debug('<b>' . __function__ . '</b> reached limit in first paragraph, breaking into ' . count($sentences) . ' sentences', __file__, __line__);
foreach ($sentences as $s) {
$length = strlen($s) + 2;
if ($length + $total_length <= $limit) {
$return .= $s . '. ';
$total_length += $length;
}
}
$return = draw_p($return);
}
break;
}
$return .= $b;
$total_length += $length;
}
}
return $return;
}
function format_html_text($str) {
$return = strip_tags($str);
$return = str_replace(' ', ' ', $return);
$return = trim($return);
if (empty($return)) return false;
return $return;
}
function format_html_title($text) {
lib_get('simple_html_dom');
$text = str_get_html($text);
$return = '';
//first, look for facebook share title http://developers.facebook.com/docs/share/
$blocks = $text->find('meta');
foreach ($blocks as $b) if ($b->property == 'og:title') return trim($b->content);
//otherwise gather all the h1s, since those aren't usually gamed for SEO
$blocks = $text->find('h1');
foreach ($blocks as $b) $return .= strip_tags($b->innertext) . ' ';
//otherwise go with the page title
if (empty($return)) {
$blocks = $text->find('title');
foreach ($blocks as $b) $return .= strip_tags($b->innertext);
}
return trim($return);
}
function format_html_trim($text) {
global $_josh;
$text = format_html($text);
lib_get('simple_html_dom');
//find td, div or body with longest text block
$html = str_get_html($text);
$blocks = $html->find('text');
foreach ($blocks as $b) max_num(strlen(trim($b)));
if (!function_exists('get_parent')) {
function get_parent($e) {
$options = array('td', 'div', 'body');
if (!is_object($e)) die($e);
return (in_array($e->tag, $options)) ? $e : get_parent($e->parent);
}
}
foreach ($blocks as $b) {
$len = strlen(trim($b));
if ($len == max_num()) {
$e = get_parent($b->parent);
$text = $e->innertext;
echo $text;
}
}
$html->clear();
unset($html);
$html = str_get_html($text);
//get rid of any sub-divs
$blocks = $html->find('div');
foreach ($blocks as $b) $b->outertext = '';
//reset html to get rid of artifacts and compress
$text = trim($html->save());
$html->clear();
return $text;
}
function format_image($path, $type=false) {
global $_josh;
//function to take any image and return JPG encoded binary. could send to format image resize at that point
//type should be used if you're sending a temp name (eg file upload)
//requires the imagemagick convert unix command
if (!$file = file_get($path)) return false;
if (!$type) $type = file_ext($path);
$target_name = DIRECTORY_WRITE . '/temp-target.jpg';
$imagick = exec('which convert');
if (empty($imagick)) $imagick = '/usr/local/bin/convert'; //not able to get correct path on my mac now
if (($type == 'jpg') || ($type == 'jpeg')) {
return $file;
} elseif (($type == 'gif') || ($type == 'png')) {
//convert
$cmd = $imagick . ' ' . realpath($path) . ' ' . DIRECTORY_ROOT . $target_name;
exec($cmd);
} elseif ($type == 'pdf') {
//return a screenshot of the first page
exec($imagick . ' ' . realpath($path) . '[0] ' . DIRECTORY_ROOT . $target_name);
} else {
error_handle('unhandled image convert', __function__ . ' ran into a problem converting ' . $path, __file__, __line__);
return false;
}
if ($source = file_get($target_name)) {
file_delete($target_name);
return $source;
} else {
error_handle('ImageMagick Not Installed', __function__ . ' requires the ' . draw_link('http://www.imagemagick.org/', 'ImageMagick PHP library') . ' to work on the command line. Please install it and try again. ', __file__, __line__);
return false;
}
}
function format_image_resize($source, $max_width=false, $max_height=false) {
if (!function_exists('imagecreatefromjpeg')) error_handle('library missing', 'the GD library needs to be installed to run format_image_resize', __file__, __line__);
if (empty($source)) return null;
if (!function_exists('resize')) {
function resize($new_width, $new_height, $source_name, $target_name, $width, $height) {
//resize an image and save to the $target_name
$tmp = imagecreatetruecolor($new_width, $new_height);
if (!$image = imagecreatefromjpeg(DIRECTORY_ROOT . $source_name)) error_handle('could not create image', 'the system could not create an image from ' . $source_name, __file__, __line__);
imagecopyresampled($tmp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($tmp, DIRECTORY_ROOT . $target_name, 100);
imagedestroy($tmp);
imagedestroy($image);
}
function crop($new_width, $new_height, $target_name) {
//crop an image and save to the $target_name
list($width, $height) = getimagesize(DIRECTORY_ROOT . $target_name);
//by default, crop from center
$offsetx = ($width - $new_width) / 2;
$offsety = ($height - $new_height) / 2;
if ($offsetx < 0) $offsetx = 0;
if ($offsety < 0) $offsety = 0;
//this crops from top-left
//$offsetx = $offsety = 0;
$tmp = imagecreatetruecolor($new_width, $new_height);
if (!$image = @imagecreatefromjpeg(DIRECTORY_ROOT . $target_name)) error_handle('could not create image', 'the system could not create an image from ' . $source_name, __file__, __line__);
imagecopyresized($tmp, $image, 0, 0, $offsetx, $offsety, $new_width, $new_height, $new_width, $new_height);
imagejpeg($tmp, DIRECTORY_ROOT . $target_name, 100);
imagedestroy($tmp);
imagedestroy($image);
}
}
//save to file, is file-based operation, unfortunately
$source_name = DIRECTORY_WRITE . '/temp-source.jpg';
$target_name = DIRECTORY_WRITE . '/temp-target.jpg';
file_put($source_name, $source);
//get source image dimensions
list($width, $height) = getimagesize(DIRECTORY_ROOT . $source_name);
if(!$width || !$height) {
// image is probably corrupt
echo draw_page('image corrupt', 'the uploaded image cannot be read, try opening the image in photo editing software, re-saving it, and then try again');
exit();
}
//execute differently depending on target parameters
if ($max_width && $max_height) {
//resizing both
if (($width == $max_width) && ($height == $max_height)) {
//already exact width and height, skip resizing
copy(DIRECTORY_ROOT . $source_name, DIRECTORY_ROOT . $target_name);
} else {
//this was for the scenario where your target was a long landscape and you got a squarish image.
//this doesn't work if your target is squarish and you get a long landscape
//maybe we need a ratio function?
//square to long scenario: input 400 x 300 (actual 1.3 ratio), target 400 x 100 (target 4) need to resize width then crop target > actual
//long to square scenario: input 400 x 100 (actual 4 ratio), target 400 x 300 (target 1.3) need to resize height then crop target < actual
$target_ratio = $max_width / $max_height;
$actual_ratio = $width / $height;
//if ($max_width >= $max_height) {
if ($target_ratio >= $actual_ratio) {
//landscape or square. resize width, then crop height
$new_height = ($height / $width) * $max_width;
resize($max_width, $new_height, $source_name, $target_name, $width, $height);
} else {
//portrait. resize height, then crop width
$new_width = ($width / $height) * $max_height;
resize($new_width, $max_height, $source_name, $target_name, $width, $height);
}
crop($max_width, $max_height, $target_name);
}
} elseif ($max_width) {
//only resizing width
if ($width == $max_width) {
//already exact width, skip resizing
copy(DIRECTORY_ROOT . $source_name, DIRECTORY_ROOT . $target_name);
} else {
//resize width
$new_height = ($height / $width) * $max_width;
resize($max_width, $new_height, $source_name, $target_name, $width, $height);
}
} elseif ($max_height) {
//only resizing height
if ($height == $max_height) {
//already exact height, skip resizing
copy(DIRECTORY_ROOT . $source_name, DIRECTORY_ROOT . $target_name);
} else {
//resize height
$new_width = ($width / $height) * $max_height;
resize($new_width, $max_height, $source_name, $target_name, $width, $height);
}
}
$return = file_get($target_name);
//clean up
file_delete($source_name);
file_delete($target_name);
return $return;
}
function format_inches($inches) {
//for naomi osnos dec 4, 2011
if ($inches < 12) return $inches . '"';
$return = round($inches / 12) . '\'';
if ($inches = $inches % 12) $return .= ' ' . $inches . '"';
return $return;
}
function format_js_desanitize() {
error_deprecated(__FUNCTION__ . ' was deprecated on 3/11/2010 because css should be used for rollovers from now on');
//javascript function for decoding sanitized strings
return '
function desanitize(string) {
return string.replace(/replacedash/g, "-").replace(/replaceslash/g, "/").replace(/replacespace/g, " ").substring(1);
}
';
}
function format_js_sanitize($string) {
error_deprecated(__FUNCTION__ . ' was deprecated on 3/11/2010 because css or draw_navigation should be used for rollovers from now on');
//return javascript-sanitized key
//need for rollover script for seedco financial and phoebe murer
$string = 'a' . $string; //doesn't like variables that start with numbers
$string = str_replace('-', 'replacedash', $string); //or contain dashes
$string = str_replace('/', 'replaceslash', $string); //or contain slashes
$string = str_replace(' ', 'replacespace', $string); //or contain spaces
return $string;
}
function format_money($value, $dollarsign=true, $comma=true, $error='') {
$negative = ($value < 0);
$value = format_num($value, 2, $comma, $error);
if ($value == $error) return $value;
if ($dollarsign) {
if ($negative) {
$value = '-$' . str_replace('-', '', $value);
} else {
$value = '$' . $value;
}
}
return $value;
}
function format_more($string, $link=false, $separator='<p>[more]</p>') {
if (!$link) return str_replace($separator, '', $string);
if ($jump = strpos($string, $separator)) return substr($string, 0, $jump) . draw_p(draw_link($link, 'Read more…'), 'more');
return $string;
}
function format_null($value) {
//should this really be named db_null()?
if (!strlen($value)) return 'NULL'; //don't use empty() here because 0s will be replaced with NULLs
if (!is_numeric($value)) return '\'' . $value . '\'';
return $value;
}
function format_num($value, $decimals=false, $comma=true, $error='') {
//output function
if (empty($value)) return $error;
if (!format_verify($value, 'num')) return $error;
if ($comma) $comma = ',';
return number_format($value, $decimals, '.', $comma);
}
/*
this relationship between above and below is confusing!
format_num is like number_format but with some checking.
format_numeric forces out a number from a string
*/
function format_numeric($value, $integer=false) {
//takes a string and reduces to just its numeric elements
$characters = '-0123456789';
$value = $value . ''; //force it to be a string
if (!$integer) $characters .= '.';
$newval = '';
for ($i = 0; $i < strlen($value); $i++) if (strpos($characters, $value[$i]) !== false) $newval .= $value[$i];
if (!strlen($newval)) {
error_debug('<b>format_numeric</b> received ' . $value . ' and is sending back false', __file__, __line__);
return false;
} else {
error_debug('<b>format_numeric</b> received ' . $value . ' and is sending back ' . $newval, __file__, __line__);
return $newval - 0;
}
}
function format_percentage($float, $precision=2) {
return round($float * 100, $precision) . '%';
}
function format_phone($string, $fail=false) { //format a phone number to (123) 456-7890 format
$number = '';
for ($i = 0; $i < strlen($string); $i++) if (is_numeric($string[$i])) $number .= $string[$i];
if ((strlen($number) != 10) || ($number == '9999999999')) {
if ($fail) return false;
return $string;
}
return '(' . substr($number, 0, 3) . ') ' . substr($number, 3, 3) . '-' . substr($number, 6, 4);
}
function format_pluralize($entity, $count=2) {
if ($count == 1) return $entity;
$length = strlen($entity);
if (substr($entity, -1) == 's') {
//already ends in an s
return $entity;
} elseif (substr(strtolower($entity), -6) == ' media') {
//needs no change
return $entity;
} elseif (in_array($entity, array('day'))) {
//nonstandard behavior
return $entity . 's';
} elseif (substr($entity, -1) == 'y') {
//ends in an ies
return substr($entity, 0, ($length - 1)) . 'ies';
} else {
//needs just an s
return $entity . 's';
}
}
function format_post_bits($fieldnames) {
//takes a comma-separated list of POST keys (checkboxes) and sets bit values in their places
global $_POST;
$fields = array_separated($fieldnames);
foreach ($fields as $field) $_POST[$field] = (isset($_POST[$field])) ? 1 : 0;
}
function format_post_date($str, $array=false) {
global $_POST;
if (!$array) $array = $_POST;
$month = $array[$str . 'Month'];
$day = $array[$str . 'Day'];
$year = $array[$str . 'Year'];
$hour = isset($array[$str . 'Hour']) ? $array[$str . 'Hour'] : 0;
$minute = isset($array[$str . 'Minute']) ? $array[$str . 'Minute'] : 0;
$second = isset($array[$str . 'Second']) ? $array[$str . 'Second'] : 0;
if (isset($array[$str . 'AMPM'])) {
if ($array[$str . 'AMPM'] == 'AM') {
if ($hour == 12) $hour = 0;
} else {
if ($hour != 12) $hour +=12;
}
}
error_debug('<b>format_post_date</b> for ' . $str . ' into mdyhms: ' . $month . ', ' . $day . ', ' . $year . ', ' . $hour . ', ' . $minute . ', ' . $second, __file__, __line__);
return format_date_sql($month, $day, $year, $hour, $minute, $second);
}
function format_post_float($fieldnames) {
//takes a comma-separated list of POST keys and replaces them with monetary values or NULLs if they're empty
global $_POST;
$fields = array_separated($fieldnames);
foreach ($fields as $field) {
$_POST[$field] = format_numeric($_POST[$field]);
if ($_POST[$field] === false) $_POST[$field] = 'NULL';
}
}
function format_post_html($fieldnames) {
//takes a comma-separated list of POST keys and formats the html in them
global $_POST;
$fields = array_separated($fieldnames);
foreach ($fields as $field) {
$return = format_html($_POST[$field]);
$_POST[$field] = (empty($return)) ? 'NULL' : '"' . $_POST[$field] . '"';
}
}
function format_post_nulls($fieldnames) {
//takes a comma-separated list of POST keys and replaces them with NULLs if they're empty
global $_POST;
error_debug('<b>format_post_nulls</b> for ' . $fieldnames, __file__, __line__);
$fields = array_separated($fieldnames);
foreach ($fields as $field) {