34 require_once realpath(dirname(__FILE__).
"/document_handler.inc");
35 require_once realpath(dirname(__FILE__).
"/date_utils.inc");
56 if (!$account) $account = $user;
58 if ($role ==
"" || $account->role ==
"admin")
return true;
59 if (!$account)
return false;
61 if ($role !=
"" && $account->role ==
"")
return false;
63 $userRoles = explode(
",", $account->role);
64 foreach($userRoles as $ur)
66 if ($ur ==
"admin")
return true;
67 $expr =
"/\\b{$ur}\\b/";
68 $allowed = (preg_match($expr, $role) > 0) ?
true :
false;
86 if (!$account) $account = $user;
87 if (!$role)
return false;
89 $expr =
"/\\b{$role}\\b/";
90 return (preg_match($expr, $account->role) > 0) ? true :
false;
104 foreach($items as $item)
118 $image_types = array(
"image/jpeg",
"image/gif",
"image/x-png",
"image/pjpeg" );
128 $numargs = func_num_args();
129 $arg_list = func_get_args();
130 for ($i = 0; $i < $numargs; $i++)
132 if ($arg_list[$i]) echo $arg_list[$i].
"<br>\n";
144 return "$".number_format($amount, 2,
'.',
',');
157 if ($date !=
'Jan 1 1900 12:00AM')
159 return date(
"F d, Y", strtotime($date));
172 if ($date !=
'Jan 1 1900 12:00AM')
174 return date(
"F Y", strtotime($date));
189 $text = date(
"m/d/Y", strtotime($date));
192 if ($text ==
"01/01/1900") $text =
"";
209 $text = date(
"l F j, Y", strtotime($date));
225 if (!$ts)
return "N/A";
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);
235 if ($yyyy ==
'0000')
return "N/A";
237 return date(
"F d, Y", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
249 if (!$ts)
return "N/A";
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);
258 if ($yyyy ==
'0000')
return "N/A";
260 return date(
"m/d/Y g:ia", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
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++;
291 $weekDaysInMonth = array
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)
300 $date = strtotime(
"$year-$month-01");
302 $first = date(
"N", $date) - 1;
303 return $weekDaysInMonth[$days][$first];
313 return date(
"g:ia", $time);
323 return date(
"m/d/Y g:ia", $time);
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);
343 if ($yyyy ==
'0000')
return "N/A";
345 return date(
"m/d/Y", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
347 return date(
"m/d/Y g:ia", mktime($hh,$mi,$ss,$mm,$dd,$yyyy));
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);
370 if($yyyy != $yyyy_2 || $mm != $mm_2 || $dd != $dd_2)
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));
400 $phone = preg_replace(
"/[^0-9]/",
"", $phone);
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);
418 return date(
'Y/m/d H:i:s');
426 return date(
'Y-m-d');
434 function jsSafe($str, $escapeEntities =
false)
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(
"'",
"\'", $str);
442 $str = str_ireplace(
"</script>",
"\\x3C/script\\x3E", $str);
446 $str = str_replace(
"&",
"&", $str);
453 return htmlspecialchars($str, ENT_QUOTES,
'UTF-8');
458 return str_replace(array(
"<",
">"), array(
"<",
">"), $str);
463 $patterns = array(
"/<br>/",
"/ /",
"/<p>/",
"/<BR>/",
"/<P>/");
464 $replacements = array(
"\r\n",
" ",
"\r\n",
"\r\n",
"\r\n");
465 $text =
stripHTML(preg_replace($patterns, $replacements, $html));
487 "\xE2\x80\x98" =>
"'",
488 "\xE2\x80\x99" =>
"'",
489 "\xE2\x80\x9A" =>
"'",
490 "\xE2\x80\x9B" =>
"'",
491 "\xE2\x80\x9C" =>
'"',
492 "\xE2\x80\x9D" =>
'"',
493 "\xE2\x80\x9E" =>
'"',
494 "\xE2\x80\x9F" =>
'"',
495 "\xE2\x80\xB9" =>
"'",
496 "\xE2\x80\xBA" =>
"'",
498 $chr = array_keys ($chr_map);
499 $rpl = array_values($chr_map);
500 $str = str_replace($chr, $rpl, html_entity_decode($str, ENT_QUOTES,
"UTF-8"));
535 $d = strtolower($doc);
537 $ext = substr($d, strrpos($d,
"."));
541 if (!$doc_type) $doc_type =
"Unknown";
562 $doc_file = str_replace($config[
"uploadurl"], $config[
"uploaddir"], $doc_file);
566 if (file_exists($doc_file))
568 $doc_size = (int)(filesize($doc_file)/1024);
590 $n = strtolower($name);
591 $extension = substr($n, strrpos($n,
"."));
593 if (!$type) $type=
"application/octet-stream";
618 $n = strtolower($doc);
619 $extension = substr($n, strrpos($n,
"."));
621 if (!$icon) $icon =
"/fakoli/images/file_icon.png";
636 if ($v!=
"" && !is_numeric($v)) die(
"Invalid Parameter");
639 else if ($p!=
"" && !is_numeric($p)) die(
"Invalid Parameter");
655 if ($v !=
"" & !preg_match(
"/^[0-9\\.{$separator}]*$/", $v)) die(
"Invalid Parameter");
658 else if ($p!=
"" && !preg_match(
"/^[0-9\\.{$separator}]*$/", $p)) die(
"Invalid Parameter");
668 return preg_match(
"/^[A-Za-z0-9_\\-\\.]*$/", $p) ? $p : die(
"Invalid Parameter");
677 return preg_match(
"/^[A-Za-z0-9_\\-\\.,]*$/", $p) ? $p : die(
"Invalid Parameter");
687 return (filter_var($e, FILTER_VALIDATE_EMAIL)) ? $e : die(
"Invalid Parameter");
698 $formats = array(
"Y-m-d",
"Y/m/d",
"m/d/Y");
699 foreach($formats as $format)
701 if ($d == date($format, strtotime($d)))
return $d;
704 die(
"Invalid Parameter");
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)
718 if ($d == date($format, strtotime($d)))
return $d;
721 die(
"Invalid Parameter");
731 if (preg_match(
'/^[A-F0-9]{32}$/i', $guid))
736 die(
"Invalid Parameter");
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))
751 die(
"Invalid Parameter");
766 if ($count%2==0) $color =
"#EEEEEE";
781 if (strlen($txt) > $max)
785 $txt = substr($txt, 0, $max).
"...";
789 $txt = substr($txt, 0, $max);
790 $pos = strrpos($txt,
" ");
793 while($pos && $txt[$pos - 1] ==
'.')
798 $txt = substr($txt, 0, $pos).
"...";
813 $tmpString = $strText;
816 $tmpString = str_replace(chr(145), chr(39), $tmpString);
817 $tmpString = str_replace(chr(146), chr(39), $tmpString);
818 $tmpString = str_replace(
"'",
"'", $tmpString);
821 $tmpString = str_replace(chr(147), chr(34), $tmpString);
822 $tmpString = str_replace(chr(148), chr(34), $tmpString);
826 $tmpString = str_replace(chr(10),
" ", $tmpString);
827 $tmpString = str_replace(chr(13),
" ", $tmpString);
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;
850 $text = strip_tags($text);
853 $text = html_entity_decode($text);
867 $len = strlen($param);
870 foreach($collection as $field => $value)
872 if (!strncmp($field, $param, $len))
888 function option($value, $text, $sel =
"")
890 echo
"<option value='$value'";
895 echo
">$text</option>";
908 $opt =
"<option value='$value'";
913 $opt .=
">$text</option>";
935 if ($config[
'prettyURLs'] ===
false)
937 $page = preg_replace(
"/^\\/?([\\w\\d_]+?)\\?/",
"/page.php?identifier=$1&", $page);
938 $page = preg_replace(
"/^\\/?([\\w\\d_]+)$/",
"/page.php?identifier=$1", $page);
941 trace(
"redirect:: page is $page", 3);
942 $server = $config[
'http_host'];
943 if (!$server) $server=
"localhost:8080";
947 $https = $_SERVER[
'HTTPS'];
948 if ($https ==
"off") $https =
false;
949 if (isset($_SERVER[
'HTTP_X_FORWARDED_PROTO']) && $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ===
'https')
954 $protocol = $https ?
"https" :
"http";
957 if (!strncmp($page,
"http://", 7) OR (!strncmp($page,
"https://", 8)))
961 else if ($page[0] ==
'/')
963 $location =
"$protocol://$server$page";
971 $directory = str_replace(DIRECTORY_SEPARATOR,
'/', dirname($_SERVER[
'REQUEST_URI']));
972 if ($directory ==
"/") $directory =
"";
973 $location =
"$protocol://".$server.$directory.
"/".$page;
976 header(
"Location: $location");
978 session_write_close();
988 $qs = $_SERVER[
'QUERY_STRING'];
992 foreach($_GET as $key => $value)
994 if ($key !=
"identifier" && $key !=
"section") $params[$key] = $value;
997 return http_build_query($params);
1010 function trace($msg, $lvl = 3, $callStack =
null)
1015 if ($lvl <= $config[
"trace_level"])
1017 switch($config[
"trace_detail"])
1019 case TraceDetailFull:
1021 $callStack = $callStack ? $callStack : debug_backtrace();
1022 if (count($callStack) > 1)
1024 $callingFn = $callStack[1];
1028 $callingFn = $callStack[0];
1030 $file = str_replace($config[
"homedir"],
"", $callingFn[
"file"]);
1031 $ref = $file.
":".$callingFn[
"line"].
" ";
1032 if ($callingFn[
"class"])
1034 $ref .= $callingFn[
"class"].$callingFn[
"type"];
1037 $ref .= $callingFn[
"function"].
"(): ";
1039 error_log(
"[".
$traceLevels[$lvl].
"] ".date(
"Y-m-d H:i:s").
" : ".$_SERVER[
'REQUEST_URI'].
" : ".$ref.
" ".$msg.
"\r\n", 3, $config[
"trace_path"]);
1042 case TraceDetailHigh:
1044 $callStack = $callStack ? $callStack : debug_backtrace();
1046 if (count($callStack) > 1)
1048 $callingFn = $callStack[1];
1052 $callingFn = $callStack[0];
1055 $file = str_replace($config[
"homedir"],
"", $callingFn[
"file"]);
1056 $ref = $file.
":".$callingFn[
"line"].
" ";
1057 if ($callingFn[
"class"])
1059 $ref .= $callingFn[
"class"].$callingFn[
"type"];
1062 $ref .= $callingFn[
"function"].
"(): ";
1064 error_log(
"[".
$traceLevels[$lvl].
"] ".date(
"Y-m-d H:i:s").
" : ".$ref.
" ".$msg.
"\r\n", 3, $config[
"trace_path"]);
1068 case TraceDetailMedium:
1069 error_log(
"[".
$traceLevels[$lvl].
"] ".date(
"Y-m-d H:i:s : ").$msg.
"\r\n", 3, $config[
"trace_path"]);
1072 case TraceDetailNormal:
1075 error_log(
"[".
$traceLevels[$lvl].
"] ".$msg.
"\r\n", 3, $config[
"trace_path"]);
1090 if (!$size)
return "";
1093 if ($size > 1073741824)
1095 $result = sprintf(
"%.{$decimal_places}fGB", ($size / 1073741824));
1097 else if ($size > 1048576)
1099 $result = sprintf(
"%.{$decimal_places}fMB", ($size / 1048576));
1101 else if ($size > 1024)
1103 $result = intval($size / 1024).
"KB";
1107 $result =
"$size bytes";
1115 if (!$num)
return "";
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));;
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));
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");
1152 global $auto_form_defaults;
1154 $ext = substr($file, strrpos($file,
"."));
1156 trace(
"getIcon($file) $ext $icon", 3);
1163 return $auto_form_defaults[
"componentPath"].$icon;
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);
1181 $html = preg_replace(
"/(src|href)(=['\"])\//",
"$1$2http://$host/", $html);
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);
1203 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
1204 curl_setopt($ch, CURLOPT_USERPWD,
"$username:$password");
1207 $html = curl_exec($ch);
1209 if ($html === FALSE)
throw new Exception(curl_error($ch));
1224 foreach($params as $key => $value)
1226 $qs[] =
"$key=".urlencode($value);
1229 $qs = implode(
"&", $qs);
1231 $api =
"{$url}?{$qs}";
1234 return json_decode($response);
1248 trace(
"Downloading $url to $saveAs", 3);
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);
1257 $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
1258 $bytes = curl_exec($ch);
1261 trace(count($bytes).
" bytes recieved", 3);
1263 if(file_exists($saveAs))
1268 file_put_contents($saveAs, $bytes);
1270 return $contentType;
1287 $out = realpath($config[
'homedir'].
"/".$url);
1291 $out = realpath($config[
'homedir'].$url);
1294 $out = str_replace(
'\\',
'/', $out);
1296 if (!
startsWith($out, $config[
'homedir']))
return null;
1297 $out = str_replace($config[
'homedir'],
"http://{$config['http_host']}", $out);
1299 trace(
"$url -> $out", 4);
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);
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));
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));
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);
1367 $html = curl_exec($ch);
1383 $text = str_replace(
" ",
"%20", $url);
1384 $text = str_replace(
"/",
" ", $text);
1385 $text = wordwrap($text, $width,
"/<br>",
true);
1386 $text = str_replace(
" ",
"/", $text);
1401 $name = preg_replace(
"/[\\s\\W]+/",
"_", $name);
1402 $name = str_replace(
"&",
"and", $name);
1415 $name = preg_replace(
"/([a-z])([A-Z0-9])/",
"$1 $2", $name);
1416 $name = str_replace(
"_",
" ", $name);
1417 $name = ucwords($name);
1430 if ($count == 1)
return $text;
1434 if (preg_match(
"/[^aeiouAEIOU]y$/", $c))
1436 $c = substr($c, 0, -1).
"ies";
1438 else if (preg_match(
"/(?:ss|[^aeiou]o|x|s|ch)$/", $c))
1458 if (preg_match(
"/<.*?>/", $text))
return $text;
1459 $text = str_replace(
"\n",
"<br/>", $text);
1472 return (strncmp($text, $start, strlen($start)) == 0);
1483 return (substr($text, -strlen($end)) == $end);
1493 return preg_replace(
"/<.*?>/",
"", $text);
1510 $lastTwo = substr($n, -2, 2);
1511 $lastOne = substr($n, -1, 1);
1513 if ($lastTwo ==
"11" || $lastTwo ==
"12" || $lastTwo ==
"13") $suffix =
"th";
1518 case "1": $suffix =
"st";
break;
1519 case "2": $suffix =
"nd";
break;
1520 case "3": $suffix =
"rd";
break;
1521 default: $suffix =
"th";
1529 return "$n<sup>$suffix</sup>";
1541 if (!
startsWith($uri,
"http://")) $uri =
"http://$uri";
1557 if(count($options) == 0)
return;
1559 $values = explode(
",", $items);
1561 foreach($values as $value)
1563 if(array_key_exists($value, $options))
1565 $list .= $options[$value] .
", ";
1568 $list .= $value .
", ";
1571 if(strlen($list) > 0)
1572 $list = substr($list, 0, strlen($list) - 2);
1584 if (!$uri) $uri = $_SERVER[
'REQUEST_URI'];
1585 return preg_replace(
"/\\?.*$/",
"", $uri);
1596 trace (
"QS: $qs PARAMS: $params", 3);
1597 if (strpos($qs,
"?") ===
false && strpos($qs,
"&") ===
false)
1604 $qs = preg_replace(
"/&&+/",
"&", $qs);
1605 if (strpos($qs,
"?") ===
false) $qs =
"?".$qs;
1620 for($i = 0; $i < func_num_args(); ++$i)
1641 foreach($_GET as $name => $value)
1645 if (is_array($value))
1647 foreach($value as $key => $val)
1649 $qs .= $sep.urlencode($name).
"[".urlencode($key).
"]=".urlencode($val);
1655 $qs .= $sep.urlencode($name).
"=".urlencode($value);
1662 foreach($_POST as $name => $value)
1664 if (is_array($value))
1666 foreach($value as $key => $val)
1668 $qs .= $sep.urlencode($name).
"[".urlencode($key).
"]=".urlencode($val);
1674 $qs .= $sep.urlencode($name).
"=".urlencode($value);
1680 trace(
"Full Query String: $qs", 3);
1699 if(count($items) == 0)
1702 if(is_object($items[0]) && !$field)
1704 $field = $items[0]->getPrimaryKey();
1707 foreach($items as $item)
1709 if (!$first) $js_arr .=
", ";
1710 $js_arr .= (is_object($item) && $field) ? $item->$field : $item;
1725 return json_encode(json_decode($json), JSON_PRETTY_PRINT);
1738 for($i = 0; $i < $len; ++$i)
1740 $str .= chr(ord(
'a') + rand(0, 25));
1754 if ( !is_array( $input ) )
1759 if ( empty( $input ) )
1764 $filteredKeys = array_filter( array_keys( $input ), $callback );
1766 if ( empty( $filteredKeys ) )
1771 $input = array_intersect_key( array_flip( $filteredKeys ), $input );
1785 if (class_exists(FakoliEarlyExit))
1787 throw new FakoliEarlyExit($msg);
1791 session_write_close();
1804 $mime_types = array(
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',
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',
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',
1837 'mp3' =>
'audio/mpeg',
1838 'm4a' =>
'video/mp4',
1839 'qt' =>
'video/quicktime',
1840 'mov' =>
'video/quicktime',
1843 'pdf' =>
'application/pdf',
1844 'psd' =>
'image/vnd.adobe.photoshop',
1845 'ai' =>
'application/postscript',
1846 'eps' =>
'application/postscript',
1847 'ps' =>
'application/postscript',
1850 'doc' =>
'application/msword',
1851 'rtf' =>
'application/rtf',
1852 'xls' =>
'application/vnd.ms-excel',
1853 'ppt' =>
'application/vnd.ms-powerpoint',
1856 'odt' =>
'application/vnd.oasis.opendocument.text',
1857 'ods' =>
'application/vnd.oasis.opendocument.spreadsheet',
1860 $ext = strtolower(array_pop(explode(
'.',$filename)));
1862 if (array_key_exists($ext, $mime_types))
1864 return $mime_types[$ext];
1866 elseif (function_exists(
'finfo_open'))
1868 $finfo = finfo_open(FILEINFO_MIME);
1869 $mimetype = finfo_file($finfo, $filename);
1870 finfo_close($finfo);
1887 for($i = 1; $i < func_num_args(); ++$i)
1889 unset($array[func_get_arg($i)]);
1905 if (defined(ENT_XML1))
return htmlentities($value, ENT_XML1);
1908 foreach (str_split(utf8_decode(htmlspecialchars($string))) as $char)
1912 $result .=
'&#' . $num .
';';
1927 return mb_encode_mimeheader($text,
"iso-8859-1",
"Q");
1937 if (function_exists(
'random_int') ===
true)
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)).
'}';
1942 if (function_exists(
'com_create_guid') ===
true)
1944 return trim(com_create_guid(),
'{}');
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)).
'}';
1956 return str_replace(array(
"{",
"}",
"-"), array(
"",
"",
""),
GUID());
1965 foreach (debug_backtrace() as $k => $v) {
1970 array_walk($v[
'args'],
function (&$item, $key) {
1971 $item = var_export($item,
true);
1974 $trace .=
'#' . ($k - $ignore) .
' ' . $v[
'file'] .
'(' . $v[
'line'] .
'): ' . (isset($v[
'class']) ? $v[
'class'] .
'->' :
'') . $v[
'function'] .
'(' . implode(
', ', $v[
'args']) .
')' .
"\n";
1987 $len = strlen($num);
1988 for ($i = $len-1; $i >= 0; $i--)
1990 $ord = ord($num[$i]);
1991 if (($len - 1) & $i)
1997 $sum += $ord / 5 + (2 * $ord) % 10;
2000 return $sum % 10 == 0;
2013 $arr1 = explode(
",", $a);
2014 $arr2 = explode(
",", $b);
2015 return count(array_intersect($arr1, $arr2));
2030 $includes = get_included_files();
2031 if ($html) echo
"<ul>\n";
2032 foreach($includes as $include)
2036 echo
"<li>$include</li>";
2043 if ($html) echo
"</ul>";
2047 $out = ob_get_contents();
2062 foreach($substitutions as $old => $new)
2064 $expr =
"/\\b{$old}\\b/";
2065 trace(
"{$expr} => $new", 3);
2066 $target = preg_replace($expr, $new, $target);
2084 $handle = fopen($filename,
'r');
2085 $bom = fread($handle, 2);
2090 if($bom === chr(0xff).chr(0xfe) || $bom === chr(0xfe).chr(0xff)){
2092 $encoding =
'UTF-16';
2094 $file_sample = fread($handle, 1000) .
'e';
2098 $encoding = mb_detect_encoding($file_sample ,
'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
2100 if ($encoding && $encoding !=
'UTF-8'){
2101 stream_filter_append($handle,
'convert.iconv.'.$encoding.
'/UTF-8');
2108 $fields = fgetcsv($fp);
2109 if (is_array($fields))
2111 $bom = pack(
'CCC', 0xEF, 0xBB, 0xBF);
2112 if (substr($fields[0], 0, 3) === $bom)
2114 $fields[0] = substr($fields[0], 3);
2139 function tempdir($dir =
null, $prefix =
'tmp_', $mode = 0700, $maxAttempts = 1000)
2144 $dir = sys_get_temp_dir();
2148 $dir = rtrim($dir, DIRECTORY_SEPARATOR);
2153 if (!is_dir($dir) || !is_writable($dir))
2159 if (strpbrk($prefix,
'\\/:*?"<>|') !==
false)
2171 $path = sprintf(
'%s%s%s%s', $dir, DIRECTORY_SEPARATOR, $prefix, mt_rand(100000, mt_getrandmax()));
2173 !mkdir($path, $mode) &&
2174 $attempts++ < $maxAttempts
$doc_extensions
Mapping of common file extensions to human-readable document type.
endsWith($text, $end)
Tests whether a string ends with the given sub-string.
checkNumericList($p, $separator=",")
Security helper function.
codify($name)
Takes a text string and converts it into a code-compliant format, suitable for use as a variable name...
formatCheckListItemsforView($options, $items)
For dataitems that are rendered as CheckListFieldRenderer, this function converts the comma-delimited...
formatDateTime12($time)
Format a date and time in 12 hour clock, no seconds.
xmlEntities($string)
Function to provide html to XML entity renaming.
checkRole($role, $account=null)
Check whether the user has one of a specified set of roles.
formatTimestamp($ts)
Utility function to format readable date from a timestamp (no time component).
checkNumeric($p)
Security helper function.
color($count)
Utility function to nicely format addresses, etc.
formatStartDateToEndDate($start, $end)
fopen_utf8($filename)
Opens a text file, detects the encoding, inteprets the BOM if present, attaches a stream filter to co...
plainGUID()
Generates a version 4 GUID with no punctutation.
stripHTMLTags($text)
Removes all HTML tags from the specified string.
tempdir($dir=null, $prefix='tmp_', $mode=0700, $maxAttempts=1000)
Creates a random unique temporary directory, with specified parameters, that does not already exist (...
getDocType($doc)
Returns a human-readable type name for a document, based on the file extension of the supplied file n...
getDocSize($doc)
Returns the file size in Kb for a document.
checkValidDateTime($d)
Security helper function.
makeURL($uri)
Ensures that the http:// protocol specifier prefix is present in the supplied string.
parseMultiParam($collection, $param)
Parse out multiple values from the provided collection that have the same root name,...
countMatchingElements($a, $b)
Determines the number of items that two comma-separated lists have in common.
roundFormat($num, $abbrev=false)
getScaledSize($size, $decimal_places=1)
Get human-readable file size from raw number of bytes.
formatDateShort($date)
Utility function to format date in short form (MM/DD/YYYY), with no time component.
ordinalSuffix($n, $sup=false)
Adds the english ordinal suffix to a number.
trace($msg, $lvl=3, $callStack=null)
Send output to the trace log.
getBacktrace($ignore=2)
Returns a formatted backtrace suitable for debugging output.
wrapURL($url, $width=120)
Break a URL at a given string position.
pluralize($text, $count=0)
Takes a singular string and makes it plural.
getRemoteHeaders($url)
Retrieve the HTTP headers for the specified remote URL (excluding the body).
formatDateTime12Hr($datetime)
today()
Returns today as a string.
postRemoteXML($url, $xml, $timeout=30)
hasRole($role, $account=null)
Determine whether a user has a specific role explicitly set.
checkIdentifierList($p)
Security helper function.
$image_types
MIME types allowable for image uploads.
postRemote($url, $data=null, $timeout=30)
Make a POST request to a remote URL, returning the results.
checkIdentifier($p)
Security helper function.
prettyPrintJSON($json)
Format the JSON in the supplied string to be more human-readable.
printIncludes($html=true, $return=false)
Outputs a list of all included files.
formatCurrency($amount)
Utility function to format currency using $ and , and stuff.
saveRemote($url, $saveAs)
Retreive the contents of the remote file at the given URL and save it to the specified location on th...
checkGUID($guid)
Checks whether the provided string is in a valid form for a GUID.
getIcon($file)
Retrieves a graphic icon appropriate for the given file.
array_remove_keys($array)
Remove specified keys from the given array.
now()
Returns the current time and date in a database compatible format.
baseURI($uri=null)
Returns the base URI for the current script, with the query string removed.
getCleanQueryString()
Returns the query string for the current page, cleaned of any Fakoli-related navigation parameters.
filterByRole($items, $field)
Filter the given list, retaining only the objects that match the current user's role profile in the g...
GUID()
Generates a version 4 GUID.
arrayFilterKey( $input, $callback)
Filter an array based on applying the specified callback to the keys.
formatDate($date)
Utility function to format date (no time component).
firstSentence($text)
Returns the first sentence of the supplied text.
jsSafe($str, $escapeEntities=false)
Utility function to escape a string correctly for use in a Javascript client-side call.
formatAsHTML($text)
Takes a string and formats it for display as HTML, removing any HTML tags it contains,...
option($value, $text, $sel="")
Write out an option tag, marking as selected if applicable.
luhnTest($num)
Performs a Luhn validity test for credit card or IMEI numbers.
getFullQueryString($includePOST=true)
Generates a query string containing the values passed to this page.
redirect($page)
Simplified redirect.
ellipsis($txt, $max, $wholeWord=false)
Truncate the supplied text at the given maximum length.
startsWith($text, $start)
Tests whether a string starts with a given sub-string.
getMonthWeekDays($month, $year)
Get the number of week days in the specified month.
canonicalizeURL($url)
Takes a URL and converts relative URLs to absolute URLs for the current site.
encode7bit($text)
Encode text to 7-bit clean format, suitable for mail headers.
getMonthDays($m, $y)
Returns the number of days in the specified month.
appendToQueryString($qs, $params)
Appends the specified parameters to the supplied query string.
prettify($name)
Takes a variable or field name and converts it into a human-readable version (assuming that the origi...
registerURLRewriteParameters()
Register any URL rewrite parameters that should be excluded from query string reformatting.
includeRemote($host, $file)
Includes the contents of the given remote file, with any relative src or href references converted to...
ajaxReturn($msg=null)
Returns a string output and exits the script cleanly.
registerRedirectLogCallback($callback)
formatTimestampShort($ts)
replaceValues($substitutions, $target)
Given an array of pairs of old and new values, replace all instances of old values with new values in...
sanitizePath($path)
Sanitize a file path, removing relative path sections and ensuring the correct directory separator is...
toJSArray($items, $field="")
printMIMETypeList($types)
Outputs the MIME type list based on an array of MIME types.
formatTime12($time)
Format a time in 12 hour clock, no seconds.
formatAddress()
Utility function to nicely format addresses, etc.
jsonRequest($url, $params=array())
Make a simple GET request to a JSON-return RESTful API, passing the supplied parameters.
checkValidEmail($e)
Security helper function.
checkPlainGUID($guid)
Checkes whether the provided string is an undecorated GUID (i.e.
checkValidDate($d)
Security helper function.
getRemote($url, $username="", $password="")
Retrieve the contents of the remote file at the given URL.
str_option($value, $text, $sel="")
Write out an option tag to a string, marking as selected if applicable.
makeRandomString($len)
Creates a randomized string of characters.