Framework  3.9
functions.inc
Go to the documentation of this file.
1 <?php
2 /**************************************************************
3 
4  Copyright (c) 2007-2010 Sonjara, Inc
5 
6  Permission is hereby granted, free of charge, to any person
7  obtaining a copy of this software and associated documentation
8  files (the "Software"), to deal in the Software without
9  restriction, including without limitation the rights to use,
10  copy, modify, merge, publish, distribute, sublicense, and/or sell
11  copies of the Software, and to permit persons to whom the
12  Software is furnished to do so, subject to the following
13  conditions:
14 
15  The above copyright notice and this permission notice shall be
16  included in all copies or substantial portions of the Software.
17 
18  Except as contained in this notice, the name(s) of the above
19  copyright holders shall not be used in advertising or otherwise
20  to promote the sale, use or other dealings in this Software
21  without prior written authorization.
22 
23  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
25  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
27  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
28  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
30  OTHER DEALINGS IN THE SOFTWARE.
31 
32 *****************************************************************/
33 
34 require_once realpath(dirname(__FILE__)."/document_handler.inc");
35 require_once realpath(dirname(__FILE__)."/date_utils.inc");
36 
52 function checkRole($role, $account = null)
53 {
54  global $user;
55 
56  if (!$account) $account = $user;
57 
58  if ($role == "" || $account->role == "admin") return true;
59  if (!$account) return false;
60 
61  if ($role != "" && $account->role == "") return false;
62 
63  $userRoles = explode(",", $account->role);
64  foreach($userRoles as $ur)
65  {
66  if ($ur == "admin") return true;
67  $expr = "/\\b{$ur}\\b/";
68  $allowed = (preg_match($expr, $role) > 0) ? true : false;
69  if ($allowed) break;
70  }
71 
72  return $allowed;
73 }
74 
82 function hasRole($role, $account = null)
83 {
84  global $user;
85 
86  if (!$account) $account = $user;
87  if (!$role) return false;
88 
89  $expr = "/\\b{$role}\\b/";
90  return (preg_match($expr, $account->role) > 0) ? true : false;
91 }
92 
101 function filterByRole($items, $field)
102 {
103  $ret = array();
104  foreach($items as $item)
105  {
106  if (checkRole($item->get($field)))
107  {
108  $ret[] = $item;
109  }
110  }
111 
112  return $ret;
113 }
114 
118 $image_types = array( "image/jpeg", "image/gif", "image/x-png", "image/pjpeg" );
119 
126 function formatAddress()
127 {
128  $numargs = func_num_args();
129  $arg_list = func_get_args();
130  for ($i = 0; $i < $numargs; $i++)
131  {
132  if ($arg_list[$i]) echo $arg_list[$i]."<br>\n";
133  }
134 }
135 
136 
142 function formatCurrency($amount)
143 {
144  return "$".number_format($amount, 2, '.', ',');
145 }
146 
154 function formatDate($date)
155 {
156 
157  if ($date !='Jan 1 1900 12:00AM')
158  {
159  return date("F d, Y", strtotime($date));
160  }
161 }
162 
169 function formatMonthYear($date)
170 {
171 
172  if ($date !='Jan 1 1900 12:00AM')
173  {
174  return date("F Y", strtotime($date));
175  }
176 }
177 
183 function formatDateShort($date)
184 {
185  $text = "";
186 
187  if ($date)
188  {
189  $text = date("m/d/Y", strtotime($date));
190  }
191 
192  if ($text == "01/01/1900") $text = "";
193 
194  return $text;
195 }
196 
203 function formatDateLong($date)
204 {
205  $text = "";
206 
207  if ($date)
208  {
209  $text = date("l F j, Y", strtotime($date));
210  }
211 
212  return $text;
213 }
214 
223 function formatTimestamp($ts)
224 {
225  if (!$ts) return "N/A";
226 
227 
228  $yyyy = substr($ts,0,4);
229  $mm = substr($ts,4,2);
230  $dd = substr($ts,6,2);
231  $hh = substr($ts,8,2);
232  $mi = substr($ts,10,2);
233  $ss = substr($ts,12,2);
234 
235  if ($yyyy == '0000') return "N/A";
236 
237  return date("F d, Y", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
238 }
239 
240 /*
241  * Format timestamp with date in short format
242  * e.g., 1/2/2011 and include time in 12 hour format
243  * e.g., 10:15am
244  *
245  * Deprecated
246  */
247 function formatTimestampShort($ts)
248 {
249  if (!$ts) return "N/A";
250 
251  $yyyy = substr($ts,0,4);
252  $mm = substr($ts,4,2);
253  $dd = substr($ts,6,2);
254  $hh = substr($ts,8,2);
255  $mi = substr($ts,10,2);
256  $ss = substr($ts,12,2);
257 
258  if ($yyyy == '0000') return "N/A";
259 
260  return date("m/d/Y g:ia", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
261 
262 }
263 
272 function getMonthDays($m, $y)
273 {
274  $monthDays = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
275  $d = $monthDays[$m - 1];
276  if ($m == 2 && ($y % 4) == 0 && ($y % 100) != 0) $d++;
277 
278  return $d;
279 }
280 
289 function getMonthWeekDays($month, $year)
290 {
291  $weekDaysInMonth = array
292  (
293  28 => array(20, 20, 20, 20, 20, 20, 20),
294  29 => array(21, 21, 21, 21, 21, 20, 20),
295  30 => array(22, 22, 22, 22, 21, 20, 21),
296  31 => array(23, 23, 23, 22, 21, 21, 22)
297  );
298 
299  $days = getMonthDays($month, $year);
300  $date = strtotime("$year-$month-01");
301 
302  $first = date("N", $date) - 1;
303  return $weekDaysInMonth[$days][$first];
304 }
305 
311 function formatTime12($time)
312 {
313  return date("g:ia", $time);
314 }
315 
321 function formatDateTime12($time)
322 {
323  return date("m/d/Y g:ia", $time);
324 }
325 
326 /*
327  * Formats a datetime in date short format
328  * with hours on 12 hour clock, no seconds.
329  * If time component is 00:00:00, then
330  * don't return time.
331  *
332  * Deprecated
333  */
334 function formatDateTime12Hr($datetime)
335 {
336  $yyyy = substr($datetime,0,4);
337  $mm = substr($datetime,5,2);
338  $dd = substr($datetime,8,2);
339  $hh = substr($datetime,11,2);
340  $mi = substr($datetime,14,2);
341  $ss = "00";
342 
343  if ($yyyy == '0000') return "N/A";
344  if($hh == '00')
345  return date("m/d/Y", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
346  else
347  return date("m/d/Y g:ia", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
348 }
349 
350 /*
351  * If start and end dates are the same date
352  * then show the date followed by start and end time.
353  * Otherwise, show start date and time to end date
354  * and time.
355  *
356  * $start - datetime
357  * $end - datetime
358  *
359  * Deprecated
360  */
361 function formatStartDateToEndDate($start, $end)
362 {
363  $yyyy = substr($start,0,4);
364  $yyyy_2 = substr($end,0,4);
365  $mm = substr($start,5,2);
366  $mm_2 = substr($end,5,2);
367  $dd = substr($start,8,2);
368  $dd_2 = substr($end,8,2);
369 
370  if($yyyy != $yyyy_2 || $mm != $mm_2 || $dd != $dd_2)
371  {
372  return formatDateTime12Hr($start) ." &ndash; ". formatDateTime12Hr($end);
373  }
374  else
375  {
376  $hh = substr($start,11,2);
377  $mi = substr($start,14,2);
378  $hh_2 = substr($end,11,2);
379  $mi_2 = substr($end,14,2);
380  $s_time = date("g:ia", mktime($hh,$mi));
381  $e_time = date("g:ia", mktime($hh_2,$mi_2));
382  return formatDateShort($start) . " $s_time &ndash; $e_time";
383  }
384 }
385 
386 /*
387  * Given a phone number containing various
388  * separator characters between the numbers,
389  * clear out the separators and standardize
390  * the format as
391  * (xxx) xxx-xxxx
392  *
393  * tylerhall on 11/30/-1
394  * http://snipplr.com/view/25/format-phone-number/
395  *
396  * Deprecated
397  */
398 function format_phone($phone)
399 {
400  $phone = preg_replace("/[^0-9]/", "", $phone);
401 
402  if(strlen($phone) == 7)
403  return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
404  elseif(strlen($phone) == 10)
405  return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
406  else
407  return $phone;
408 }
409 
410 
411 
416 function now()
417 {
418  return date('Y/m/d H:i:s');
419 }
420 
424 function today()
425 {
426  return date('Y-m-d');
427 }
428 
434 function jsSafe($str, $escapeEntities = false)
435 {
436  $str = str_replace("\\", "\\\\", $str);
437  $str = preg_replace("/'/","\'",$str);
438  $str = preg_replace('/"/','\"',$str);
439  $str = str_replace("\r", "", $str);
440  $str = str_replace("\n", "\\n", $str);
441  $str = str_replace("&#39;", "\'", $str);
442  $str = str_ireplace("</script>", "\\x3C/script\\x3E", $str);
443 
444  if ($escapeEntities)
445  {
446  $str = str_replace("&", "&amp;", $str);
447  }
448  return $str;
449 }
450 
451 function htmlsafe($str)
452 {
453  return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
454 }
455 
456 function cleanHTMLTags($str)
457 {
458  return str_replace(array("<", ">"), array("&lt;", "&gt;"), $str);
459 }
460 
461 function HTMLToText($html)
462 {
463  $patterns = array("/<br>/", "/&nbsp;/", "/<p>/", "/<BR>/", "/<P>/");
464  $replacements = array("\r\n", " ", "\r\n", "\r\n", "\r\n");
465  $text = stripHTML(preg_replace($patterns, $replacements, $html));
466 
467  return $text;
468 }
469 
470 function cleanQuotes($str)
471 {
472  $chr_map = array(
473  // Windows codepage 1252
474  "\xC2\x82" => "'", // U+0082 U+201A single low-9 quotation mark
475  "\xC2\x84" => '"', // U+0084 U+201E double low-9 quotation mark
476  "\xC2\x8B" => "'", // U+008B U+2039 single left-pointing angle quotation mark
477  "\xC2\x91" => "'", // U+0091 U+2018 left single quotation mark
478  "\xC2\x92" => "'", // U+0092 U+2019 right single quotation mark
479  "\xC2\x93" => '"', // U+0093 U+201C left double quotation mark
480  "\xC2\x94" => '"', // U+0094 U+201D right double quotation mark
481  "\xC2\x9B" => "'", // U+009B U+203A single right-pointing angle quotation mark
482 
483  // Regular Unicode // U+0022 quotation mark (")
484  // U+0027 apostrophe (')
485  "\xC2\xAB" => '"', // U+00AB left-pointing double angle quotation mark
486  "\xC2\xBB" => '"', // U+00BB right-pointing double angle quotation mark
487  "\xE2\x80\x98" => "'", // U+2018 left single quotation mark
488  "\xE2\x80\x99" => "'", // U+2019 right single quotation mark
489  "\xE2\x80\x9A" => "'", // U+201A single low-9 quotation mark
490  "\xE2\x80\x9B" => "'", // U+201B single high-reversed-9 quotation mark
491  "\xE2\x80\x9C" => '"', // U+201C left double quotation mark
492  "\xE2\x80\x9D" => '"', // U+201D right double quotation mark
493  "\xE2\x80\x9E" => '"', // U+201E double low-9 quotation mark
494  "\xE2\x80\x9F" => '"', // U+201F double high-reversed-9 quotation mark
495  "\xE2\x80\xB9" => "'", // U+2039 single left-pointing angle quotation mark
496  "\xE2\x80\xBA" => "'", // U+203A single right-pointing angle quotation mark
497  );
498  $chr = array_keys ($chr_map); // but: for efficiency you should
499  $rpl = array_values($chr_map); // pre-calculate these two arrays
500  $str = str_replace($chr, $rpl, html_entity_decode($str, ENT_QUOTES, "UTF-8"));
501  return $str;
502 }
503 
511 function printMIMETypeList($types)
512 {
513  print "*";
514  //foreach ($types as $t)
515  //{
516  // if ($out) $out .= ",";
517  // $out .= $t;
518  //}
519 
520  //print $out;
521 }
522 
531 function getDocType($doc)
532 {
533  global $doc_extensions;
534 
535  $d = strtolower($doc);
536 
537  $ext = substr($d, strrpos($d, "."));
538 
539  $doc_type = $doc_extensions[$ext];
540 
541  if (!$doc_type) $doc_type = "Unknown";
542 
543  return $doc_type;
544 
545 }
546 
554 function getDocSize($doc)
555 {
556  global $config;
557 
558  // Find the file name for the file on disk
559 
560  $doc_file = $doc;
561 
562  $doc_file = str_replace($config["uploadurl"], $config["uploaddir"], $doc_file);
563 
564  // If the file exists, return its size
565 
566  if (file_exists($doc_file))
567  {
568  $doc_size = (int)(filesize($doc_file)/1024);
569  }
570  else
571  {
572  $doc_size = 0;
573  }
574 
575  return $doc_size;
576 }
577 
578 // ?Is getMIMEType supposed to be used instead of getMimeType??
579 // Doesn't seem to work.
586 function getDocMimeType($name)
587 {
588  global $doc_mime_types;
589 
590  $n = strtolower($name);
591  $extension = substr($n, strrpos($n, "."));
592  $type = $doc_mime_types[$extension];
593  if (!$type) $type="application/octet-stream";
594  return $type;
595 
596 }
597 
598 /*function getMimeType($name)
599 {
600  global $doc_mime_types;
601 
602  $n = strtolower($name);
603  $extension = substr($n, strrpos($n, "."));
604  $type = $doc_mime_types[$extension];
605  if (!$type) $type="application/octet-stream";
606  return $type;
607 }*/
608 
615 function getDocIcon($doc)
616 {
617  global $doc_icons;
618  $n = strtolower($doc);
619  $extension = substr($n, strrpos($n, "."));
620  $icon = $doc_icons[$extension];
621  if (!$icon) $icon = "/fakoli/images/file_icon.png";
622  return $icon;
623 }
624 
630 function checkNumeric($p)
631 {
632  if (is_array($p))
633  {
634  foreach($p as $v)
635  {
636  if ($v!="" && !is_numeric($v)) die("Invalid Parameter");
637  }
638  }
639  else if ($p!="" && !is_numeric($p)) die("Invalid Parameter");
640  return $p;
641 }
642 
649 function checkNumericList($p, $separator = ",")
650 {
651  if (is_array($p))
652  {
653  foreach($p as $v)
654  {
655  if ($v != "" & !preg_match("/^[0-9\\.{$separator}]*$/", $v)) die("Invalid Parameter");
656  }
657  }
658  else if ($p!="" && !preg_match("/^[0-9\\.{$separator}]*$/", $p)) die("Invalid Parameter");
659  return $p;
660 }
661 
666 function checkIdentifier($p)
667 {
668  return preg_match("/^[A-Za-z0-9_\\-\\.]*$/", $p) ? $p : die("Invalid Parameter");
669 }
670 
676 {
677  return preg_match("/^[A-Za-z0-9_\\-\\.,]*$/", $p) ? $p : die("Invalid Parameter");
678 }
679 
685 function checkValidEmail($e)
686 {
687  return (filter_var($e, FILTER_VALIDATE_EMAIL)) ? $e : die("Invalid Parameter");
688 }
689 
695 function checkValidDate($d)
696 {
697  if (!$d) return $d;
698  $formats = array("Y-m-d", "Y/m/d", "m/d/Y");
699  foreach($formats as $format)
700  {
701  if ($d == date($format, strtotime($d))) return $d;
702  }
703 
704  die("Invalid Parameter");
705 }
706 
712 function checkValidDateTime($d)
713 {
714  if (!$d) return $d;
715  $formats = array("Y-m-d H:i:s", "Y/m/d H:i:s", "m/d/Y H:i:s", "Y-m-d g:i:sa", "Y/m/d g:i:sa", "m/d/Y g:i:sa");
716  foreach($formats as $format)
717  {
718  if ($d == date($format, strtotime($d))) return $d;
719  }
720 
721  die("Invalid Parameter");
722 }
723 
729 function checkPlainGUID($guid)
730 {
731  if (preg_match('/^[A-F0-9]{32}$/i', $guid))
732  {
733  return $guid;
734  }
735 
736  die("Invalid Parameter");
737 }
738 
744 function checkGUID($guid)
745 {
746  if (preg_match('/^\{?[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}?$/i', $guid))
747  {
748  return $guid;
749  }
750 
751  die("Invalid Parameter");
752 }
753 
762 function color($count)
763 {
764 
765 $color = "#FFFFFF";
766 if ($count%2==0) $color = "#EEEEEE";
767 return $color;
768 }
769 
779 function ellipsis($txt, $max, $wholeWord = false)
780 {
781  if (strlen($txt) > $max)
782  {
783  if (!$wholeWord)
784  {
785  $txt = substr($txt, 0, $max)."...";
786  }
787  else
788  {
789  $txt = substr($txt, 0, $max);
790  $pos = strrpos($txt, " ");
791  if ($pos)
792  {
793  while($pos && $txt[$pos - 1] == '.')
794  {
795  $pos--;
796  }
797  }
798  $txt = substr($txt, 0, $pos)."...";
799  }
800  }
801 
802  return $txt;
803 }
804 
811 function rteSafe($strText) {
812  //returns safe code for preloading in the RTE
813  $tmpString = $strText;
814 
815  //convert all types of single quotes
816  $tmpString = str_replace(chr(145), chr(39), $tmpString);
817  $tmpString = str_replace(chr(146), chr(39), $tmpString);
818  $tmpString = str_replace("'", "&#39;", $tmpString);
819 
820  //convert all types of double quotes
821  $tmpString = str_replace(chr(147), chr(34), $tmpString);
822  $tmpString = str_replace(chr(148), chr(34), $tmpString);
823 // $tmpString = str_replace("\"", "\"", $tmpString);
824 
825  //replace carriage returns & line feeds
826  $tmpString = str_replace(chr(10), " ", $tmpString);
827  $tmpString = str_replace(chr(13), " ", $tmpString);
828 
829  return $tmpString;
830 }
831 
839 function firstSentence($text)
840 {
841  $text = preg_replace("/<br>/i", " ", $text);
842  $text = preg_replace("/<.*?>/", "", $text);
843  $pos = strpos($text, ". ");
844  return ($pos) ? substr($text, 0, $pos + 1) : $text;
845 }
846 
847 function stripHTML($text)
848 {
849  /*$text = preg_replace("/<.*?>/", "", $text);*/
850  $text = strip_tags($text);
851 
852  // JDG 5/19/2011 - remove &ndash, &nbsp;
853  $text = html_entity_decode($text);
854  $text = trim($text);
855  return $text;
856 }
857 
865 function parseMultiParam($collection, $param)
866 {
867  $len = strlen($param);
868  $values = array();
869 
870  foreach($collection as $field => $value)
871  {
872  if (!strncmp($field, $param, $len))
873  {
874  $values[] = $value;
875  }
876  }
877 
878  return $values;
879 }
880 
888 function option($value, $text, $sel = "")
889 {
890  echo "<option value='$value'";
891  if ($sel === $value)
892  {
893  echo " selected";
894  }
895  echo ">$text</option>";
896 }
897 
898 
906 function str_option($value, $text, $sel = "")
907 {
908  $opt = "<option value='$value'";
909  if ($sel == $value)
910  {
911  $opt .= " selected";
912  }
913  $opt .= ">$text</option>";
914 
915  return $opt;
916 }
917 
919 
920 function registerRedirectLogCallback($callback)
921 {
922  global $_redirectLogCallback;
923  $_redirectLogCallback = $callback;
924 }
925 
930 function redirect($page)
931 {
932  global $_redirectLogCallback;
933  global $config;
934 
935  if ($config['prettyURLs'] === false)
936  {
937  $page = preg_replace("/^\\/?([\\w\\d_]+?)\\?/", "/page.php?identifier=$1&", $page);
938  $page = preg_replace("/^\\/?([\\w\\d_]+)$/", "/page.php?identifier=$1", $page);
939  }
940 
941  trace("redirect:: page is $page", 3);
942  $server = $config['http_host'];
943  if (!$server) $server="localhost:8080";
944 
945  //AJG: 3/9/11 - maintain current protocol by default
946 
947  $https = $_SERVER['HTTPS'];
948  if ($https == "off") $https = false;
949  if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
950  {
951  $https = true;
952  }
953 
954  $protocol = $https ? "https" : "http";
955 
956  // JDG 9/27/10 - handle https
957  if (!strncmp($page, "http://", 7) OR (!strncmp($page, "https://", 8)))
958  {
959  $location = $page;
960  }
961  else if ($page[0] == '/')
962  {
963  $location = "$protocol://$server$page";
964  }
965 // else if (preg_match( "/^[\\w\\d_\\-]+$/", $page))
966 // {
967 // $location = "http://$server/$page";
968 // }
969  else
970  {
971  $directory = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['REQUEST_URI']));
972  if ($directory == "/") $directory = "";
973  $location = "$protocol://".$server.$directory."/".$page;
974  }
975 
976  header("Location: $location");
978  session_write_close();
979  exit;
980 }
981 
987 {
988  $qs = $_SERVER['QUERY_STRING'];
989 
990  $params = array();
991 
992  foreach($_GET as $key => $value)
993  {
994  if ($key != "identifier" && $key != "section") $params[$key] = $value;
995  }
996 
997  return http_build_query($params);
998 }
999 
1000 $traceLevels = array(1 => "FATAL",
1001  2 => "ERROR",
1002  3 => "TRACE",
1003  4 => "DEBUG",
1004  5 => "NOTE*");
1010 function trace($msg, $lvl = 3, $callStack = null)
1011 {
1012  global $config;
1013  global $traceLevels;
1014 
1015  if ($lvl <= $config["trace_level"])
1016  {
1017  switch($config["trace_detail"])
1018  {
1019  case TraceDetailFull:
1020 
1021  $callStack = $callStack ? $callStack : debug_backtrace();
1022  if (count($callStack) > 1)
1023  {
1024  $callingFn = $callStack[1];
1025  }
1026  else
1027  {
1028  $callingFn = $callStack[0];
1029  }
1030  $file = str_replace($config["homedir"], "", $callingFn["file"]);
1031  $ref = $file.":".$callingFn["line"]." ";
1032  if ($callingFn["class"])
1033  {
1034  $ref .= $callingFn["class"].$callingFn["type"];
1035  }
1036 
1037  $ref .= $callingFn["function"]."(): ";
1038 
1039  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s")." : ".$_SERVER['REQUEST_URI']." : ".$ref." ".$msg."\r\n", 3, $config["trace_path"]);
1040  break;
1041 
1042  case TraceDetailHigh:
1043 
1044  $callStack = $callStack ? $callStack : debug_backtrace();
1045 
1046  if (count($callStack) > 1)
1047  {
1048  $callingFn = $callStack[1];
1049  }
1050  else
1051  {
1052  $callingFn = $callStack[0];
1053  }
1054 
1055  $file = str_replace($config["homedir"], "", $callingFn["file"]);
1056  $ref = $file.":".$callingFn["line"]." ";
1057  if ($callingFn["class"])
1058  {
1059  $ref .= $callingFn["class"].$callingFn["type"];
1060  }
1061 
1062  $ref .= $callingFn["function"]."(): ";
1063 
1064  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s")." : ".$ref." ".$msg."\r\n", 3, $config["trace_path"]);
1065  break;
1066 
1067 
1068  case TraceDetailMedium:
1069  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s : ").$msg."\r\n", 3, $config["trace_path"]);
1070  break;
1071 
1072  case TraceDetailNormal:
1073  default:
1074 
1075  error_log("[".$traceLevels[$lvl]."] ".$msg."\r\n", 3, $config["trace_path"]);
1076  break;
1077  }
1078  }
1079 }
1080 
1081 
1088 function getScaledSize($size, $decimal_places = 1)
1089 {
1090  if (!$size) return "";
1091 
1092  $result = "";
1093  if ($size > 1073741824)
1094  {
1095  $result = sprintf("%.{$decimal_places}fGB", ($size / 1073741824));
1096  }
1097  else if ($size > 1048576)
1098  {
1099  $result = sprintf("%.{$decimal_places}fMB", ($size / 1048576));
1100  }
1101  else if ($size > 1024)
1102  {
1103  $result = intval($size / 1024)."KB";
1104  }
1105  else
1106  {
1107  $result = "$size bytes";
1108  }
1109 
1110  return $result;
1111 }
1112 
1113 function roundFormat($num,$abbrev = false)
1114 {
1115  if (!$num) return "";
1116 
1117  $result = "";
1118  if ($abbrev == false) {
1119  if ($num >= 1000000000) {
1120  $result = sprintf("%.1f billion", ($num / 1000000000));
1121  } elseif ($num >= 1000000) {
1122  $result = sprintf("%.1f million", ($num / 1000000));;
1123  } elseif ($num >= 1000) {
1124  $result = sprintf("%.0f,000", ($num / 1000));;
1125  }
1126  } else {
1127  if ($num >= 1000000000) {
1128  $result = sprintf("%.1f bn", ($num / 1000000000));
1129  } elseif ($num >= 1000000) {
1130  $result = sprintf("%.1f m", ($num / 1000000));;
1131  } elseif ($num >= 1000) {
1132  $result = sprintf("%.0f,000", ($num / 1000));
1133  }
1134  }
1135  return $result;
1136 }
1137 
1138 $_icons = array(".doc" => "/images/msword_icon.png",
1139  ".xls" => "/images/msexcel_icon.png",
1140  ".pdf" => "/images/pdf_icon.png",
1141  ".ppt" => "/images/ppt_icon.png",
1142  "default" => "/images/file_icon.png");
1143 
1149 function getIcon($file)
1150 {
1151  global $_icons;
1152  global $auto_form_defaults;
1153 
1154  $ext = substr($file, strrpos($file, "."));
1155  $icon = $_icons[$ext];
1156  trace("getIcon($file) $ext $icon", 3);
1157 
1158  if (!isset($icon))
1159  {
1160  $icon = $_icons["default"];
1161  }
1162 
1163  return $auto_form_defaults["componentPath"].$icon;
1164 }
1165 
1173 function includeRemote($host, $file)
1174 {
1175  $ch = curl_init("http://$host/$file");
1176  curl_setopt($ch, CURLOPT_HEADER, 0);
1177  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1178  $html = curl_exec($ch);
1179  curl_close($ch);
1180 
1181  $html = preg_replace("/(src|href)(=['\"])\//", "$1$2http://$host/", $html);
1182  echo $html;
1183 }
1184 
1192 function getRemote($url, $username = "", $password = "")
1193 {
1194  $url = canonicalizeURL($url);
1195  trace("Retrieving $url", 3);
1196  $ch = curl_init("$url");
1197  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1198  curl_setopt($ch, CURLOPT_HEADER, 0);
1199  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1200 
1201  if ($username)
1202  {
1203  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
1204  curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
1205  }
1206 
1207  $html = curl_exec($ch);
1208 
1209  if ($html === FALSE) throw new Exception(curl_error($ch));
1210 
1211  curl_close($ch);
1212 
1213  return $html;
1214 }
1215 
1221 function jsonRequest($url, $params = array())
1222 {
1223  $qs = array();
1224  foreach($params as $key => $value)
1225  {
1226  $qs[] = "$key=".urlencode($value);
1227  }
1228 
1229  $qs = implode("&", $qs);
1230 
1231  $api = "{$url}?{$qs}";
1232  trace($api);
1233  $response = getRemote($api);
1234  return json_decode($response);
1235 }
1236 
1246 function saveRemote($url, $saveAs)
1247 {
1248  trace("Downloading $url to $saveAs", 3);
1249 
1250  $ch = curl_init ($url);
1251  curl_setopt($ch, CURLOPT_HEADER, 0);
1252  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1253  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1254  curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
1255  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1256 
1257  $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
1258  $bytes = curl_exec($ch);
1259  curl_close ($ch);
1260 
1261  trace(count($bytes)." bytes recieved", 3);
1262 
1263  if(file_exists($saveAs))
1264  {
1265  unlink($saveAs);
1266  }
1267 
1268  file_put_contents($saveAs, $bytes);
1269 
1270  return $contentType;
1271 }
1272 
1278 function canonicalizeURL($url)
1279 {
1280  global $config;
1281 
1282  if (startsWith($url, "http://") || startsWith($url, "https://")) return $url;
1283 
1284 
1285  if (!startsWith($url, "/"))
1286  {
1287  $out = realpath($config['homedir']."/".$url);
1288  }
1289  else
1290  {
1291  $out = realpath($config['homedir'].$url);
1292  }
1293 
1294  $out = str_replace('\\', '/', $out);
1295 
1296  if (!startsWith($out, $config['homedir'])) return null;
1297  $out = str_replace($config['homedir'], "http://{$config['http_host']}", $out);
1298 
1299  trace("$url -> $out", 4);
1300  return $out;
1301 }
1302 
1309 function sanitizePath($path)
1310 {
1311  $path = str_replace("/", DIRECTORY_SEPARATOR, $path);
1312  $path = str_replace("\\", DIRECTORY_SEPARATOR, $path);
1313  $path = str_replace("..".DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
1314  $path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
1315  return $path;
1316 }
1317 
1325 function postRemote($url, $data = null, $timeout = 30)
1326 {
1327  $ch = curl_init();
1328  curl_setopt($ch, CURLOPT_URL, $url);
1329  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1330  curl_setopt($ch, CURLOPT_HEADER, 0);
1331  curl_setopt($ch, CURLOPT_POST, 1);
1332  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
1333  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
1334  $result = trim(curl_exec($ch));
1335  curl_close($ch);
1336  return $result;
1337 }
1338 
1339 function postRemoteXML($url, $xml, $timeout = 30)
1340 {
1341  $ch = curl_init($url);
1342  curl_setopt($ch, CURLOPT_MUTE, 1);
1343  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
1344  curl_setopt($ch, CURLOPT_POST, 1);
1345  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
1346  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
1347  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1348  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
1349  $result = trim(curl_exec($ch));
1350  curl_close($ch);
1351  return $result;
1352 }
1353 
1359 function getRemoteHeaders($url)
1360 {
1361  $ch = curl_init();
1362  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1363  curl_setopt($ch, CURLOPT_HEADER, 1);
1364  curl_setopt($ch, CURLOPT_NOBODY, 1);
1365  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1366 
1367  $html = curl_exec($ch);
1368 
1369  curl_close($ch);
1370 
1371  return $html;
1372 }
1373 
1381 function wrapURL($url, $width = 120)
1382 {
1383  $text = str_replace(" ", "%20", $url);
1384  $text = str_replace("/", " ", $text);
1385  $text = wordwrap($text, $width, "/<br>", true);
1386  $text = str_replace(" ", "/", $text);
1387 
1388  return $text;
1389 }
1390 
1399 function codify($name)
1400 {
1401  $name = preg_replace("/[\\s\\W]+/", "_", $name);
1402  $name = str_replace("&", "and", $name);
1403  return $name;
1404 }
1405 
1413 function prettify($name)
1414 {
1415  $name = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $name);
1416  $name = str_replace("_", " ", $name);
1417  $name = ucwords($name);
1418 
1419  return $name;
1420 }
1421 
1428 function pluralize($text, $count = 0)
1429 {
1430  if ($count == 1) return $text;
1431 
1432  $c = $text;
1433 
1434  if (preg_match("/[^aeiouAEIOU]y$/", $c))
1435  {
1436  $c = substr($c, 0, -1)."ies";
1437  }
1438  else if (preg_match("/(?:ss|[^aeiou]o|x|s|ch)$/", $c))
1439  {
1440  $c .= "es";
1441  }
1442  else
1443  {
1444  $c .= "s";
1445  }
1446 
1447  return $c;
1448 }
1449 
1456 function formatAsHTML($text)
1457 {
1458  if (preg_match("/<.*?>/", $text)) return $text;
1459  $text = str_replace("\n", "<br/>", $text);
1460 
1461  return $text;
1462 }
1463 
1470 function startsWith($text, $start)
1471 {
1472  return (strncmp($text, $start, strlen($start)) == 0);
1473 }
1474 
1481 function endsWith($text, $end)
1482 {
1483  return (substr($text, -strlen($end)) == $end);
1484 }
1485 
1491 function stripHTMLTags($text)
1492 {
1493  return preg_replace("/<.*?>/", "", $text);
1494 }
1495 
1503 function ordinalSuffix($n, $sup = false)
1504 {
1505  $suffix = "";
1506  if (is_numeric($n))
1507  {
1508  $n = trim($n);
1509 
1510  $lastTwo = substr($n, -2, 2);
1511  $lastOne = substr($n, -1, 1);
1512 
1513  if ($lastTwo == "11" || $lastTwo == "12" || $lastTwo == "13") $suffix = "th";
1514  else
1515  {
1516  switch($lastOne)
1517  {
1518  case "1": $suffix = "st"; break;
1519  case "2": $suffix = "nd"; break;
1520  case "3": $suffix = "rd"; break;
1521  default: $suffix = "th";
1522  }
1523  }
1524  }
1525  else return $n;
1526 
1527  // JDG 2/10/12 - fix was not returning value if $sup false
1528  if ($sup)
1529  return "$n<sup>$suffix</sup>";
1530  else
1531  return "$n$suffix";
1532 }
1533 
1539 function makeURL($uri)
1540 {
1541  if (!startsWith($uri, "http://")) $uri = "http://$uri";
1542  return $uri;
1543 }
1544 
1555 function formatCheckListItemsforView($options, $items)
1556 {
1557  if(count($options) == 0) return;
1558 
1559  $values = explode(",", $items);
1560 
1561  foreach($values as $value)
1562  {
1563  if(array_key_exists($value, $options))
1564  {
1565  $list .= $options[$value] . ", ";
1566  }
1567  else
1568  $list .= $value . ", ";
1569  }
1570 
1571  if(strlen($list) > 0)
1572  $list = substr($list, 0, strlen($list) - 2);
1573 
1574  return $list;
1575 }
1576 
1582 function baseURI($uri = null)
1583 {
1584  if (!$uri) $uri = $_SERVER['REQUEST_URI'];
1585  return preg_replace("/\\?.*$/", "", $uri);
1586 }
1587 
1594 function appendToQueryString($qs, $params)
1595 {
1596  trace ("QS: $qs PARAMS: $params", 3);
1597  if (strpos($qs, "?") === false && strpos($qs, "&") === false)
1598  {
1599  $qs .= "?$params";
1600  return $qs;
1601  }
1602 
1603  $qs .= "&$params";
1604  $qs = preg_replace("/&&+/", "&", $qs);
1605  if (strpos($qs, "?") === false) $qs = "?".$qs;
1606 
1607  return $qs;
1608 }
1609 
1611 
1617 {
1618  global $__urlRewriteParams;
1619 
1620  for($i = 0; $i < func_num_args(); ++$i)
1621  {
1622  $__urlRewriteParams[func_get_arg($i)] = true;
1623  }
1624 }
1625 
1634 function getFullQueryString($includePOST = true)
1635 {
1636  global $__urlRewriteParams;
1637 
1638  $qs = "";
1639  $sep = "?";
1640 
1641  foreach($_GET as $name => $value)
1642  {
1643  if (array_key_exists($name, $__urlRewriteParams)) continue;
1644 
1645  if (is_array($value))
1646  {
1647  foreach($value as $key => $val)
1648  {
1649  $qs .= $sep.urlencode($name)."[".urlencode($key)."]=".urlencode($val);
1650  $sep = "&";
1651  }
1652  }
1653  else
1654  {
1655  $qs .= $sep.urlencode($name)."=".urlencode($value);
1656  $sep = "&";
1657  }
1658  }
1659 
1660  if ($includePOST)
1661  {
1662  foreach($_POST as $name => $value)
1663  {
1664  if (is_array($value))
1665  {
1666  foreach($value as $key => $val)
1667  {
1668  $qs .= $sep.urlencode($name)."[".urlencode($key)."]=".urlencode($val);
1669  $sep = "&";
1670  }
1671  }
1672  else
1673  {
1674  $qs .= $sep.urlencode($name)."=".urlencode($value);
1675  $sep = "&";
1676  }
1677  }
1678  }
1679 
1680  trace("Full Query String: $qs", 3);
1681  return $qs;
1682 }
1683 
1684 /*
1685  * Convert a php array to a javascript array.
1686  *
1687  * @items - array of objects or simple array
1688  *
1689  * @field - if items is array of objects, the field
1690  * in the object to use to create the javascript array
1691  *
1692  * returns javascript array in the format "[cat, dog, spider]";
1693  */
1694 function toJSArray($items, $field = "")
1695 {
1696  $js_arr = "[";
1697  $first = true;
1698 
1699  if(count($items) == 0)
1700  return "";
1701 
1702  if(is_object($items[0]) && !$field)
1703  {
1704  $field = $items[0]->getPrimaryKey();
1705  }
1706 
1707  foreach($items as $item)
1708  {
1709  if (!$first) $js_arr .=", ";
1710  $js_arr .= (is_object($item) && $field) ? $item->$field : $item;
1711  $first = false;
1712  }
1713 
1714  $js_arr .= "]";
1715 
1716  return $js_arr;
1717 }
1718 
1723 function prettyPrintJSON($json)
1724 {
1725  return json_encode(json_decode($json), JSON_PRETTY_PRINT);
1726 }
1727 
1735 function makeRandomString($len)
1736 {
1737  $str = "";
1738  for($i = 0; $i < $len; ++$i)
1739  {
1740  $str .= chr(ord('a') + rand(0, 25));
1741  }
1742 
1743  return $str;
1744 }
1745 
1752 function arrayFilterKey( $input, $callback )
1753 {
1754  if ( !is_array( $input ) )
1755  {
1756  return null;
1757  }
1758 
1759  if ( empty( $input ) )
1760  {
1761  return $input;
1762  }
1763 
1764  $filteredKeys = array_filter( array_keys( $input ), $callback );
1765 
1766  if ( empty( $filteredKeys ) )
1767  {
1768  return array();
1769  }
1770 
1771  $input = array_intersect_key( array_flip( $filteredKeys ), $input );
1772 
1773  return $input;
1774 }
1775 
1783 function ajaxReturn($msg = null)
1784 {
1785  if (class_exists(FakoliEarlyExit))
1786  {
1787  throw new FakoliEarlyExit($msg);
1788  }
1789  else
1790  {
1791  session_write_close();
1792  die($msg);
1793  }
1794 }
1795 
1802 function getMIMEType($filename)
1803 {
1804  $mime_types = array(
1805 
1806  'txt' => 'text/plain',
1807  'htm' => 'text/html',
1808  'html' => 'text/html',
1809  'css' => 'text/css',
1810  'js' => 'application/javascript',
1811  'json' => 'application/json',
1812  'xml' => 'application/xml',
1813  'swf' => 'application/x-shockwave-flash',
1814  'flv' => 'video/x-flv',
1815 
1816  // images
1817  'png' => 'image/png',
1818  'jpe' => 'image/jpeg',
1819  'jpeg' => 'image/jpeg',
1820  'jpg' => 'image/jpeg',
1821  'gif' => 'image/gif',
1822  'bmp' => 'image/bmp',
1823  'ico' => 'image/vnd.microsoft.icon',
1824  'tiff' => 'image/tiff',
1825  'tif' => 'image/tiff',
1826  'svg' => 'image/svg+xml',
1827  'svgz' => 'image/svg+xml',
1828 
1829  // archives
1830  'zip' => 'application/zip',
1831  'rar' => 'application/x-rar-compressed',
1832  'exe' => 'application/x-msdownload',
1833  'msi' => 'application/x-msdownload',
1834  'cab' => 'application/vnd.ms-cab-compressed',
1835 
1836  // audio/video
1837  'mp3' => 'audio/mpeg',
1838  'm4a' => 'video/mp4',
1839  'qt' => 'video/quicktime',
1840  'mov' => 'video/quicktime',
1841 
1842  // adobe
1843  'pdf' => 'application/pdf',
1844  'psd' => 'image/vnd.adobe.photoshop',
1845  'ai' => 'application/postscript',
1846  'eps' => 'application/postscript',
1847  'ps' => 'application/postscript',
1848 
1849  // ms office
1850  'doc' => 'application/msword',
1851  'rtf' => 'application/rtf',
1852  'xls' => 'application/vnd.ms-excel',
1853  'ppt' => 'application/vnd.ms-powerpoint',
1854 
1855  // open office
1856  'odt' => 'application/vnd.oasis.opendocument.text',
1857  'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1858  );
1859 
1860  $ext = strtolower(array_pop(explode('.',$filename)));
1861 
1862  if (array_key_exists($ext, $mime_types))
1863  {
1864  return $mime_types[$ext];
1865  }
1866  elseif (function_exists('finfo_open'))
1867  {
1868  $finfo = finfo_open(FILEINFO_MIME);
1869  $mimetype = finfo_file($finfo, $filename);
1870  finfo_close($finfo);
1871  return $mimetype;
1872  }
1873  else
1874  {
1875  // Prevent other file types (such as source code or configuration files) from being served
1876  die("");
1877  }
1878 }
1879 
1885 function array_remove_keys($array)
1886 {
1887  for($i = 1; $i < func_num_args(); ++$i)
1888  {
1889  unset($array[func_get_arg($i)]);
1890  }
1891 
1892  return $array;
1893 }
1894 
1903 function xmlEntities($string)
1904 {
1905  if (defined(ENT_XML1)) return htmlentities($value, ENT_XML1);
1906 
1907  $result = '';
1908  foreach (str_split(utf8_decode(htmlspecialchars($string))) as $char)
1909  {
1910  $num = ord($char);
1911  if ($num > 127) {
1912  $result .= '&#' . $num . ';';
1913  } else {
1914  $result .= $char;
1915  }
1916  }
1917  return $result;
1918 }
1919 
1925 function encode7bit($text)
1926 {
1927  return mb_encode_mimeheader($text, "iso-8859-1", "Q");
1928 }
1929 
1935 function GUID()
1936 {
1937  if (function_exists('random_int') === true)
1938  {
1939  return '{'.sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', random_int(0, 65535), random_int(0, 65535), random_int(0, 65535), random_int(16384, 20479), random_int(32768, 49151), random_int(0, 65535), random_int(0, 65535), random_int(0, 65535)).'}';
1940  }
1941 
1942  if (function_exists('com_create_guid') === true)
1943  {
1944  return trim(com_create_guid(), '{}');
1945  }
1946 
1947  return '{'.sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)).'}';
1948 }
1949 
1954 function plainGUID()
1955 {
1956  return str_replace(array("{", "}", "-"), array("", "", ""), GUID());
1957 }
1958 
1962 function getBacktrace($ignore = 2)
1963 {
1964  $trace = '';
1965  foreach (debug_backtrace() as $k => $v) {
1966  if ($k < $ignore) {
1967  continue;
1968  }
1969 
1970  array_walk($v['args'], function (&$item, $key) {
1971  $item = var_export($item, true);
1972  });
1973 
1974  $trace .= '#' . ($k - $ignore) . ' ' . $v['file'] . '(' . $v['line'] . '): ' . (isset($v['class']) ? $v['class'] . '->' : '') . $v['function'] . '(' . implode(', ', $v['args']) . ')' . "\n";
1975  }
1976 
1977  return $trace;
1978 }
1979 
1985 function luhnTest($num)
1986 {
1987  $len = strlen($num);
1988  for ($i = $len-1; $i >= 0; $i--)
1989  {
1990  $ord = ord($num[$i]);
1991  if (($len - 1) & $i)
1992  {
1993  $sum += $ord;
1994  }
1995  else
1996  {
1997  $sum += $ord / 5 + (2 * $ord) % 10;
1998  }
1999  }
2000  return $sum % 10 == 0;
2001 }
2002 
2003 
2011 function countMatchingElements($a, $b)
2012 {
2013  $arr1 = explode(",", $a);
2014  $arr2 = explode(",", $b);
2015  return count(array_intersect($arr1, $arr2));
2016 }
2017 
2023 function printIncludes($html = true, $return = false)
2024 {
2025  if ($return)
2026  {
2027  ob_start();
2028  }
2029 
2030  $includes = get_included_files();
2031  if ($html) echo "<ul>\n";
2032  foreach($includes as $include)
2033  {
2034  if ($html)
2035  {
2036  echo "<li>$include</li>";
2037  }
2038  else
2039  {
2040  echo $include."\n";
2041  }
2042  }
2043  if ($html) echo "</ul>";
2044 
2045  if ($return)
2046  {
2047  $out = ob_get_contents();
2048  ob_end_clean();
2049  return $out;
2050  }
2051 }
2052 
2060 function replaceValues($substitutions, $target)
2061 {
2062  foreach($substitutions as $old => $new)
2063  {
2064  $expr = "/\\b{$old}\\b/";
2065  trace("{$expr} => $new", 3);
2066  $target = preg_replace($expr, $new, $target);
2067  trace($target, 3);
2068  }
2069 
2070  return $target;
2071 }
2072 
2082 function fopen_utf8($filename){
2083  $encoding='';
2084  $handle = fopen($filename, 'r');
2085  $bom = fread($handle, 2);
2086  // fclose($handle);
2087  rewind($handle);
2088 
2089 
2090  if($bom === chr(0xff).chr(0xfe) || $bom === chr(0xfe).chr(0xff)){
2091  // UTF16 Byte Order Mark present
2092  $encoding = 'UTF-16';
2093  } else {
2094  $file_sample = fread($handle, 1000) . 'e'; //read first 1000 bytes
2095  // + e is a workaround for mb_string bug
2096  rewind($handle);
2097 
2098  $encoding = mb_detect_encoding($file_sample , 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
2099  }
2100  if ($encoding && $encoding != 'UTF-8'){
2101  stream_filter_append($handle, 'convert.iconv.'.$encoding.'/UTF-8');
2102  }
2103  return ($handle);
2104 }
2105 
2106 function fgetcsv_noBOM($fp)
2107 {
2108  $fields = fgetcsv($fp);
2109  if (is_array($fields))
2110  {
2111  $bom = pack('CCC', 0xEF, 0xBB, 0xBF);
2112  if (substr($fields[0], 0, 3) === $bom)
2113  {
2114  $fields[0] = substr($fields[0], 3);
2115  }
2116  }
2117  return $fields;
2118 }
2119 
2139 function tempdir($dir = null, $prefix = 'tmp_', $mode = 0700, $maxAttempts = 1000)
2140 {
2141  /* Use the system temp dir by default. */
2142  if (is_null($dir))
2143  {
2144  $dir = sys_get_temp_dir();
2145  }
2146 
2147  /* Trim trailing slashes from $dir. */
2148  $dir = rtrim($dir, DIRECTORY_SEPARATOR);
2149 
2150  /* If we don't have permission to create a directory, fail, otherwise we will
2151  * be stuck in an endless loop.
2152  */
2153  if (!is_dir($dir) || !is_writable($dir))
2154  {
2155  return false;
2156  }
2157 
2158  /* Make sure characters in prefix are safe. */
2159  if (strpbrk($prefix, '\\/:*?"<>|') !== false)
2160  {
2161  return false;
2162  }
2163 
2164  /* Attempt to create a random directory until it works. Abort if we reach
2165  * $maxAttempts. Something screwy could be happening with the filesystem
2166  * and our loop could otherwise become endless.
2167  */
2168  $attempts = 0;
2169  do
2170  {
2171  $path = sprintf('%s%s%s%s', $dir, DIRECTORY_SEPARATOR, $prefix, mt_rand(100000, mt_getrandmax()));
2172  } while (
2173  !mkdir($path, $mode) &&
2174  $attempts++ < $maxAttempts
2175  );
2176 
2177  return $path;
2178 }
2182 ?>
$doc_extensions
Mapping of common file extensions to human-readable document type.
$doc_icons
$doc_mime_types
$traceLevels
Definition: functions.inc:1000
endsWith($text, $end)
Tests whether a string ends with the given sub-string.
Definition: functions.inc:1481
checkNumericList($p, $separator=",")
Security helper function.
Definition: functions.inc:649
codify($name)
Takes a text string and converts it into a code-compliant format, suitable for use as a variable name...
Definition: functions.inc:1399
cleanQuotes($str)
Definition: functions.inc:470
formatCheckListItemsforView($options, $items)
For dataitems that are rendered as CheckListFieldRenderer, this function converts the comma-delimited...
Definition: functions.inc:1555
getMIMEType($filename)
Definition: functions.inc:1802
formatDateTime12($time)
Format a date and time in 12 hour clock, no seconds.
Definition: functions.inc:321
xmlEntities($string)
Function to provide html to XML entity renaming.
Definition: functions.inc:1903
formatMonthYear($date)
Definition: functions.inc:169
fgetcsv_noBOM($fp)
Definition: functions.inc:2106
checkRole($role, $account=null)
Check whether the user has one of a specified set of roles.
Definition: functions.inc:52
formatTimestamp($ts)
Utility function to format readable date from a timestamp (no time component).
Definition: functions.inc:223
checkNumeric($p)
Security helper function.
Definition: functions.inc:630
color($count)
Utility function to nicely format addresses, etc.
Definition: functions.inc:762
formatStartDateToEndDate($start, $end)
Definition: functions.inc:361
fopen_utf8($filename)
Opens a text file, detects the encoding, inteprets the BOM if present, attaches a stream filter to co...
Definition: functions.inc:2082
plainGUID()
Generates a version 4 GUID with no punctutation.
Definition: functions.inc:1954
stripHTMLTags($text)
Removes all HTML tags from the specified string.
Definition: functions.inc:1491
tempdir($dir=null, $prefix='tmp_', $mode=0700, $maxAttempts=1000)
Creates a random unique temporary directory, with specified parameters, that does not already exist (...
Definition: functions.inc:2139
getDocType($doc)
Returns a human-readable type name for a document, based on the file extension of the supplied file n...
Definition: functions.inc:531
getDocSize($doc)
Returns the file size in Kb for a document.
Definition: functions.inc:554
checkValidDateTime($d)
Security helper function.
Definition: functions.inc:712
makeURL($uri)
Ensures that the http:// protocol specifier prefix is present in the supplied string.
Definition: functions.inc:1539
parseMultiParam($collection, $param)
Parse out multiple values from the provided collection that have the same root name,...
Definition: functions.inc:865
countMatchingElements($a, $b)
Determines the number of items that two comma-separated lists have in common.
Definition: functions.inc:2011
roundFormat($num, $abbrev=false)
Definition: functions.inc:1113
getScaledSize($size, $decimal_places=1)
Get human-readable file size from raw number of bytes.
Definition: functions.inc:1088
formatDateShort($date)
Utility function to format date in short form (MM/DD/YYYY), with no time component.
Definition: functions.inc:183
ordinalSuffix($n, $sup=false)
Adds the english ordinal suffix to a number.
Definition: functions.inc:1503
trace($msg, $lvl=3, $callStack=null)
Send output to the trace log.
Definition: functions.inc:1010
getBacktrace($ignore=2)
Returns a formatted backtrace suitable for debugging output.
Definition: functions.inc:1962
wrapURL($url, $width=120)
Break a URL at a given string position.
Definition: functions.inc:1381
pluralize($text, $count=0)
Takes a singular string and makes it plural.
Definition: functions.inc:1428
getRemoteHeaders($url)
Retrieve the HTTP headers for the specified remote URL (excluding the body).
Definition: functions.inc:1359
formatDateTime12Hr($datetime)
Definition: functions.inc:334
today()
Returns today as a string.
Definition: functions.inc:424
formatDateLong($date)
Definition: functions.inc:203
getDocMimeType($name)
Definition: functions.inc:586
postRemoteXML($url, $xml, $timeout=30)
Definition: functions.inc:1339
hasRole($role, $account=null)
Determine whether a user has a specific role explicitly set.
Definition: functions.inc:82
checkIdentifierList($p)
Security helper function.
Definition: functions.inc:675
stripHTML($text)
Definition: functions.inc:847
$image_types
MIME types allowable for image uploads.
Definition: functions.inc:118
postRemote($url, $data=null, $timeout=30)
Make a POST request to a remote URL, returning the results.
Definition: functions.inc:1325
checkIdentifier($p)
Security helper function.
Definition: functions.inc:666
rteSafe($strText)
Definition: functions.inc:811
prettyPrintJSON($json)
Format the JSON in the supplied string to be more human-readable.
Definition: functions.inc:1723
printIncludes($html=true, $return=false)
Outputs a list of all included files.
Definition: functions.inc:2023
formatCurrency($amount)
Utility function to format currency using $ and , and stuff.
Definition: functions.inc:142
saveRemote($url, $saveAs)
Retreive the contents of the remote file at the given URL and save it to the specified location on th...
Definition: functions.inc:1246
checkGUID($guid)
Checks whether the provided string is in a valid form for a GUID.
Definition: functions.inc:744
getIcon($file)
Retrieves a graphic icon appropriate for the given file.
Definition: functions.inc:1149
array_remove_keys($array)
Remove specified keys from the given array.
Definition: functions.inc:1885
now()
Returns the current time and date in a database compatible format.
Definition: functions.inc:416
baseURI($uri=null)
Returns the base URI for the current script, with the query string removed.
Definition: functions.inc:1582
getCleanQueryString()
Returns the query string for the current page, cleaned of any Fakoli-related navigation parameters.
Definition: functions.inc:986
filterByRole($items, $field)
Filter the given list, retaining only the objects that match the current user's role profile in the g...
Definition: functions.inc:101
GUID()
Generates a version 4 GUID.
Definition: functions.inc:1935
arrayFilterKey( $input, $callback)
Filter an array based on applying the specified callback to the keys.
Definition: functions.inc:1752
formatDate($date)
Utility function to format date (no time component).
Definition: functions.inc:154
firstSentence($text)
Returns the first sentence of the supplied text.
Definition: functions.inc:839
jsSafe($str, $escapeEntities=false)
Utility function to escape a string correctly for use in a Javascript client-side call.
Definition: functions.inc:434
formatAsHTML($text)
Takes a string and formats it for display as HTML, removing any HTML tags it contains,...
Definition: functions.inc:1456
option($value, $text, $sel="")
Write out an option tag, marking as selected if applicable.
Definition: functions.inc:888
luhnTest($num)
Performs a Luhn validity test for credit card or IMEI numbers.
Definition: functions.inc:1985
getFullQueryString($includePOST=true)
Generates a query string containing the values passed to this page.
Definition: functions.inc:1634
$__urlRewriteParams
Definition: functions.inc:1610
format_phone($phone)
Definition: functions.inc:398
redirect($page)
Simplified redirect.
Definition: functions.inc:930
ellipsis($txt, $max, $wholeWord=false)
Truncate the supplied text at the given maximum length.
Definition: functions.inc:779
startsWith($text, $start)
Tests whether a string starts with a given sub-string.
Definition: functions.inc:1470
getMonthWeekDays($month, $year)
Get the number of week days in the specified month.
Definition: functions.inc:289
HTMLToText($html)
Definition: functions.inc:461
canonicalizeURL($url)
Takes a URL and converts relative URLs to absolute URLs for the current site.
Definition: functions.inc:1278
encode7bit($text)
Encode text to 7-bit clean format, suitable for mail headers.
Definition: functions.inc:1925
getMonthDays($m, $y)
Returns the number of days in the specified month.
Definition: functions.inc:272
appendToQueryString($qs, $params)
Appends the specified parameters to the supplied query string.
Definition: functions.inc:1594
prettify($name)
Takes a variable or field name and converts it into a human-readable version (assuming that the origi...
Definition: functions.inc:1413
registerURLRewriteParameters()
Register any URL rewrite parameters that should be excluded from query string reformatting.
Definition: functions.inc:1616
includeRemote($host, $file)
Includes the contents of the given remote file, with any relative src or href references converted to...
Definition: functions.inc:1173
ajaxReturn($msg=null)
Returns a string output and exits the script cleanly.
Definition: functions.inc:1783
getDocIcon($doc)
Definition: functions.inc:615
htmlsafe($str)
Definition: functions.inc:451
registerRedirectLogCallback($callback)
Definition: functions.inc:920
formatTimestampShort($ts)
Definition: functions.inc:247
replaceValues($substitutions, $target)
Given an array of pairs of old and new values, replace all instances of old values with new values in...
Definition: functions.inc:2060
sanitizePath($path)
Sanitize a file path, removing relative path sections and ensuring the correct directory separator is...
Definition: functions.inc:1309
toJSArray($items, $field="")
Definition: functions.inc:1694
$_redirectLogCallback
Definition: functions.inc:918
printMIMETypeList($types)
Outputs the MIME type list based on an array of MIME types.
Definition: functions.inc:511
formatTime12($time)
Format a time in 12 hour clock, no seconds.
Definition: functions.inc:311
cleanHTMLTags($str)
Definition: functions.inc:456
formatAddress()
Utility function to nicely format addresses, etc.
Definition: functions.inc:126
jsonRequest($url, $params=array())
Make a simple GET request to a JSON-return RESTful API, passing the supplied parameters.
Definition: functions.inc:1221
$_icons
Definition: functions.inc:1138
checkValidEmail($e)
Security helper function.
Definition: functions.inc:685
checkPlainGUID($guid)
Checkes whether the provided string is an undecorated GUID (i.e.
Definition: functions.inc:729
checkValidDate($d)
Security helper function.
Definition: functions.inc:695
getRemote($url, $username="", $password="")
Retrieve the contents of the remote file at the given URL.
Definition: functions.inc:1192
str_option($value, $text, $sel="")
Write out an option tag to a string, marking as selected if applicable.
Definition: functions.inc:906
makeRandomString($len)
Creates a randomized string of characters.
Definition: functions.inc:1735