Fakoli Framework
Utility Functions

Library of commonly used functions. More...

Functions

 checkRole ($role, $account=null)
 Check whether the user has one of a specified set of roles. More...
 
 hasRole ($role, $account=null)
 Determine whether a user has a specific role explicitly set. More...
 
 filterByRole ($items, $field)
 Filter the given list, retaining only the objects that match the current user's role profile in the given parameter. More...
 
 formatAddress ()
 Utility function to nicely format addresses, etc. More...
 
 formatCurrency ($amount)
 Utility function to format currency using $ and , and stuff. More...
 
 formatDate ($date)
 Utility function to format date (no time component). More...
 
 formatMonthYear ($date)
 
 formatDateShort ($date)
 Utility function to format date in short form (MM/DD/YYYY), with no time component. More...
 
 formatDateLong ($date)
 
 formatTimestamp ($ts)
 Utility function to format readable date from a timestamp (no time component). More...
 
 formatTimestampShort ($ts)
 
 getMonthDays ($m, $y)
 Returns the number of days in the specified month. More...
 
 getMonthWeekDays ($month, $year)
 Get the number of week days in the specified month. More...
 
 formatTime12 ($time)
 Format a time in 12 hour clock, no seconds. More...
 
 formatDateTime12 ($time)
 Format a date and time in 12 hour clock, no seconds. More...
 
 formatDateTime12Hr ($datetime)
 
 formatStartDateToEndDate ($start, $end)
 
 format_phone ($phone)
 
 now ()
 Returns the current time and date in a database compatible format. More...
 
 today ()
 Returns today as a string. More...
 
 jsSafe ($str, $escapeEntities=false)
 Utility function to escape a string correctly for use in a Javascript client-side call. More...
 
 htmlsafe ($str)
 
 cleanHTMLTags ($str)
 
 HTMLToText ($html)
 
 cleanQuotes ($str)
 
 printMIMETypeList ($types)
 Outputs the MIME type list based on an array of MIME types. More...
 
 getDocType ($doc)
 Returns a human-readable type name for a document, based on the file extension of the supplied file name. More...
 
 getDocSize ($doc)
 Returns the file size in Kb for a document. More...
 
 getDocMimeType ($name)
 
 getDocIcon ($doc)
 
 checkNumeric ($p)
 Security helper function. More...
 
 checkNumericList ($p, $separator=",")
 Security helper function. More...
 
 checkIdentifier ($p)
 Security helper function. More...
 
 checkValidEmail ($e)
 Security helper function. More...
 
 color ($count)
 Utility function to nicely format addresses, etc. More...
 
 ellipsis ($txt, $max, $wholeWord=false)
 Truncate the supplied text at the given maximum length. More...
 
 rteSafe ($strText)
 
 rtePrepare ($strText, $css)
 
 rteClean ($strText)
 
 firstSentence ($text)
 Returns the first sentence of the supplied text. More...
 
 stripHTML ($text)
 
 parseMultiParam ($collection, $param)
 Parse out multiple values from the provided collection that have the same root name, and return the results in an array. More...
 
 option ($value, $text, $sel="")
 Write out an option tag, marking as selected if applicable. More...
 
 str_option ($value, $text, $sel="")
 Write out an option tag to a string, marking as selected if applicable. More...
 
 redirect ($page)
 Simplified redirect. More...
 
 getCleanQueryString ()
 Returns the query string for the current page, cleaned of any Fakoli-related navigation parameters. More...
 
 trace ($msg, $lvl, $callStack=null)
 Send output to the trace log. More...
 
 getScaledSize ($size, $decimal_places=1)
 Get human-readable file size from raw number of bytes. More...
 
 roundFormat ($num, $abbrev=false)
 
 getIcon ($file)
 Retrieves a graphic icon appropriate for the given file. More...
 
 includeRemote ($host, $file)
 Includes the contents of the given remote file, with any relative src or href references converted to absolute references. More...
 
 getRemote ($url, $username="", $password="")
 Retrieve the contents of the remote file at the given URL. More...
 
 jsonRequest ($url, $params=array())
 Make a simple GET request to a JSON-return RESTful API, passing the supplied parameters. More...
 
 saveRemote ($url, $saveAs)
 Retreive the contents of the remote file at the given URL and save it to the specified location on the local disk. More...
 
 canonicalizeURL ($url)
 Takes a URL and converts relative URLs to absolute URLs for the current site. More...
 
 sanitizePath ($path)
 Sanitize a file path, removing relative path sections and ensuring the correct directory separator is used throughout. More...
 
 postRemote ($url, $data=null, $timeout=30)
 Make a POST request to a remote URL, returning the results. More...
 
 postRemoteXML ($url, $xml, $timeout=30)
 
 getRemoteHeaders ($url)
 Retrieve the HTTP headers for the specified remote URL (excluding the body). More...
 
 wrapURL ($url, $width=120)
 Break a URL at a given string position. More...
 
 codify ($name)
 Takes a text string and converts it into a code-compliant format, suitable for use as a variable name or identifier. More...
 
 prettify ($name)
 Takes a variable or field name and converts it into a human-readable version (assuming that the original contains human-readable words, of course). More...
 
 pluralize ($text, $count=0)
 Takes a singular string and makes it plural. More...
 
 formatAsHTML ($text)
 Takes a string and formats it for display as HTML, removing any HTML tags it contains, and converting carriage returns to br tags. More...
 
 startsWith ($text, $start)
 Tests whether a string starts with a given sub-string. More...
 
 endsWith ($text, $end)
 Tests whether a string ends with the given sub-string. More...
 
 stripHTMLTags ($text)
 Removes all HTML tags from the specified string. More...
 
 ordinalSuffix ($n, $sup=false)
 Adds the english ordinal suffix to a number. More...
 
 makeURL ($uri)
 Ensures that the http:// protocol specifier prefix is present in the supplied string. More...
 
 formatCheckListItemsforView ($options, $items)
 For dataitems that are rendered as CheckListFieldRenderer, this function converts the comma-delimited list of items for display. More...
 
 baseURI ($uri=null)
 Returns the base URI for the current script, with the query string removed. More...
 
 appendToQueryString ($qs, $params)
 Appends the specified parameters to the supplied query string. More...
 
 registerURLRewriteParameters ()
 Register any URL rewrite parameters that should be excluded from query string reformatting. More...
 
 getFullQueryString ($includePOST=true)
 Generates a query string containing the values passed to this page. More...
 
 toJSArray ($items, $field="")
 
 makeRandomString ($len)
 Creates a randomized string of characters. More...
 
 arrayFilterKey ( $input, $callback)
 Filter an array based on applying the specified callback to the keys. More...
 
 ajaxReturn ($msg=null)
 Returns a string output and exits the script cleanly. More...
 
 getMIMEType ($filename)
 
 array_remove_keys ($array)
 Remove specified keys from the given array. More...
 
 xmlEntities ($string)
 Function to provide html to XML entity renaming. More...
 
 encode7bit ($text)
 Encode text to 7-bit clean format, suitable for mail headers. More...
 
 GUID ()
 Generates a version 4 GUID. More...
 
 plainGUID ()
 Generates a version 4 GUID with no punctutation. More...
 
 getBacktrace ($ignore=2)
 Returns a formatted backtrace suitable for debugging output. More...
 
 luhnTest ($num)
 Performs a Luhn validity test for credit card or IMEI numbers. More...
 
 countMatchingElements ($a, $b)
 Determines the number of items that two comma-separated lists have in common. More...
 
 printIncludes ($html=true, $return=false)
 Outputs a list of all included files. More...
 

Variables

 $image_types = array( "image/jpeg", "image/gif", "image/x-png", "image/pjpeg" )
 MIME types allowable for image uploads. More...
 
 $traceLevels
 
 $_icons
 
 $__urlRewriteParams = array()
 

Detailed Description

Library of commonly used functions.

Function Documentation

◆ ajaxReturn()

ajaxReturn (   $msg = null)

Returns a string output and exits the script cleanly.

We used to be able to use die(), but because of PHP 5's messed up session handling this throws an error if there is a custom session handler registered.

Parameters
string$msg

Definition at line 1723 of file functions.inc.

1724 {
1725  if (class_exists(FakoliEarlyExit))
1726  {
1727  throw new FakoliEarlyExit($msg);
1728  }
1729  else
1730  {
1731  session_write_close();
1732  die($msg);
1733  }
1734 }

◆ appendToQueryString()

appendToQueryString (   $qs,
  $params 
)

Appends the specified parameters to the supplied query string.

Parameters
string$qsthe query string
string$paramsparameters to append in query string format
Returns
string combined string

Definition at line 1543 of file functions.inc.

1544 {
1545  if (!$qs)
1546  {
1547  $qs = "?$params";
1548  }
1549  else
1550  {
1551  $qs .= "&$params";
1552  }
1553 
1554  if ($qs[0] != "?") $qs = "?$qs";
1555  $qs = preg_replace("/&&+/", "&", $qs);
1556 
1557  return $qs;
1558 }

◆ array_remove_keys()

array_remove_keys (   $array)

Remove specified keys from the given array.

Parameters
array$arraythe array to strip
Returns
stripped array

Definition at line 1824 of file functions.inc.

1825 {
1826  for($i = 1; $i < func_num_args(); ++$i)
1827  {
1828  unset($array[func_get_arg($i)]);
1829  }
1830 
1831  return $array;
1832 }

◆ arrayFilterKey()

arrayFilterKey (   $input,
  $callback 
)

Filter an array based on applying the specified callback to the keys.

Parameters
array$inputthe array to be filtered
callback$callbacka callback function or method
Returns
array the filtered array.

Definition at line 1692 of file functions.inc.

1693 {
1694  if ( !is_array( $input ) )
1695  {
1696  return null;
1697  }
1698 
1699  if ( empty( $input ) )
1700  {
1701  return $input;
1702  }
1703 
1704  $filteredKeys = array_filter( array_keys( $input ), $callback );
1705 
1706  if ( empty( $filteredKeys ) )
1707  {
1708  return array();
1709  }
1710 
1711  $input = array_intersect_key( array_flip( $filteredKeys ), $input );
1712 
1713  return $input;
1714 }

◆ baseURI()

baseURI (   $uri = null)

Returns the base URI for the current script, with the query string removed.

string

Parameters
$uri(optional) the URI to truncate - if not specified, the URI for the currently executing script is used.

Definition at line 1531 of file functions.inc.

1532 {
1533  if (!$uri) $uri = $_SERVER['REQUEST_URI'];
1534  return preg_replace("/\\?.*$/", "", $uri);
1535 }

◆ canonicalizeURL()

canonicalizeURL (   $url)

Takes a URL and converts relative URLs to absolute URLs for the current site.

Parameters
string$urlthe URL to convert
Returns
string full canonical form for the URL

Definition at line 1227 of file functions.inc.

1228 {
1229  global $config;
1230 
1231  if (startsWith($url, "http://") || startsWith($url, "https://")) return $url;
1232 
1233 
1234  if (!startsWith($url, "/"))
1235  {
1236  $out = realpath($config['homedir']."/".$url);
1237  }
1238  else
1239  {
1240  $out = realpath($config['homedir'].$url);
1241  }
1242 
1243  $out = str_replace('\\', '/', $out);
1244 
1245  if (!startsWith($out, $config['homedir'])) return null;
1246  $out = str_replace($config['homedir'], "http://{$config['http_host']}", $out);
1247 
1248  trace("$url -> $out", 4);
1249  return $out;
1250 }
startsWith($text, $start)
Tests whether a string starts with a given sub-string.
Definition: functions.inc:1419
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ checkIdentifier()

checkIdentifier (   $p)

Security helper function.

Check that the given parameter is a valid identifier (alphanumeric, _ and digits only with no spaces). Empty string is valid

Definition at line 666 of file functions.inc.

667 {
668  return preg_match("/^[A-Za-z0-9_\\-\\.]*$/", $p) ? $p : die("Invalid Parameter");
669 }

◆ checkNumeric()

checkNumeric (   $p)

Security helper function.

Check that the given parameter is a numeric value.

Parameters
string$pthe parameter to check
Returns
the value of the parameter if it matches the required format

Definition at line 630 of file functions.inc.

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 }

◆ checkNumericList()

checkNumericList (   $p,
  $separator = "," 
)

Security helper function.

Check that the given parameter contains a list of numeric values with the given separator.

Parameters
string$pthe parameter to check
string$separatorthe list separator (default to comma)
Returns
the value of the parameter if it matches the required format

Definition at line 649 of file functions.inc.

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 }

◆ checkRole()

checkRole (   $role,
  $account = null 
)

Check whether the user has one of a specified set of roles.

Parameters
string$rolethe role(s) to check against, as a comma-delimited list
object$account(optional) the account object to check (must have a 'role' property). If not provided, the default user account is used (assumed to be in the global $user variable).
Returns
boolean true if the user has one of the roles, false otherwise.

Definition at line 52 of file functions.inc.

53 {
54  global $user;
55 
56  if (!$account) $account = $user;
57 
58  if ($role == "" || $account->role == "super" || $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 == "super" || $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 }

◆ checkValidEmail()

checkValidEmail (   $e)

Security helper function.

Check that the given parameter is a valid email. Empty string is valid

Parameters
string$ethe parameter to check
Returns
string the value of the parameter if it matches the required format

Definition at line 676 of file functions.inc.

677 {
678  return (filter_var($e, FILTER_VALIDATE_EMAIL)) ? $e : die("Invalid Parameter");
679 }

◆ cleanHTMLTags()

cleanHTMLTags (   $str)

Definition at line 456 of file functions.inc.

457 {
458  return str_replace(array("<", ">"), array("&lt;", "&gt;"), $str);
459 }

◆ cleanQuotes()

cleanQuotes (   $str)

Definition at line 470 of file functions.inc.

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 }

◆ codify()

codify (   $name)

Takes a text string and converts it into a code-compliant format, suitable for use as a variable name or identifier.

Principally this involved replacing all whitespace and sequences of non-word characters (such as punctuation) with underscores.

Parameters
$namethe name to codify
Returns
the code-ish version of the name

Definition at line 1348 of file functions.inc.

1349 {
1350  $name = preg_replace("/[\\s\\W]+/", "_", $name);
1351  $name = str_replace("&", "and", $name);
1352  return $name;
1353 }

◆ color()

color (   $count)

Utility function to nicely format addresses, etc.

(skips blank entries, places all other entries on separate lines)

Parameters
integer$countthe index of the current line

Deprecated

Definition at line 689 of file functions.inc.

690 {
691 
692 $color = "#FFFFFF";
693 if ($count%2==0) $color = "#EEEEEE";
694 return $color;
695 }

◆ countMatchingElements()

countMatchingElements (   $a,
  $b 
)

Determines the number of items that two comma-separated lists have in common.

Useful for determining matches between checklist fields or roles.

Parameters
string$athe first string to test
string$bthe second string to test
Returns
integer the number of elements they have in common

Definition at line 1944 of file functions.inc.

1945 {
1946  $arr1 = explode(",", $a);
1947  $arr2 = explode(",", $b);
1948  return count(array_intersect($arr1, $arr2));
1949 }

◆ ellipsis()

ellipsis (   $txt,
  $max,
  $wholeWord = false 
)

Truncate the supplied text at the given maximum length.

If the string is truncated then an ellipsis is added.

Parameters
string$txtthe text to truncate
integer$maxthe maximum allowed length
boolean$wholeWordtrue to truncate to whole words only
Returns
string the truncated string

Definition at line 706 of file functions.inc.

707 {
708  if (strlen($txt) > $max)
709  {
710  if (!$wholeWord)
711  {
712  $txt = substr($txt, 0, $max)."...";
713  }
714  else
715  {
716  $txt = substr($txt, 0, $max);
717  $pos = strrpos($txt, " ");
718  if ($pos)
719  {
720  while($pos && $txt[$pos - 1] == '.')
721  {
722  $pos--;
723  }
724  }
725  $txt = substr($txt, 0, $pos)."...";
726  }
727  }
728 
729  return $txt;
730 }

◆ encode7bit()

encode7bit (   $text)

Encode text to 7-bit clean format, suitable for mail headers.

Parameters
string$textthe possibly unclean text
Returns
string the text with 8-bit characters encoded in hex format

Definition at line 1864 of file functions.inc.

1865 {
1866  return mb_encode_mimeheader($text, "iso-8859-1", "Q");
1867 }

◆ endsWith()

endsWith (   $text,
  $end 
)

Tests whether a string ends with the given sub-string.

Parameters
$textthe string to test
$endthe sub-string to look for at the end
Returns
boolean true if the string ends with the sub-string, false otherwise

Definition at line 1430 of file functions.inc.

1431 {
1432  return (substr($text, -strlen($end)) == $end);
1433 }

◆ filterByRole()

filterByRole (   $items,
  $field 
)

Filter the given list, retaining only the objects that match the current user's role profile in the given parameter.

Parameters
string$itemsthe array of items to be filtered
string$fieldthe name of the field defining the role restriction
Returns
array the filtered array

Definition at line 101 of file functions.inc.

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 }
checkRole($role, $account=null)
Check whether the user has one of a specified set of roles.
Definition: functions.inc:52

◆ firstSentence()

firstSentence (   $text)

Returns the first sentence of the supplied text.

HTML formatting is removed. The first sentence is defined as the text up to the first occurrence of the substring ". ". If this substring does not appear, the whole (HTML-stripped) text is returned.

Parameters
string$textthe text of which the first sentence is to be returned

Definition at line 801 of file functions.inc.

802 {
803  $text = preg_replace("/<br>/i", " ", $text);
804  $text = preg_replace("/<.*?>/", "", $text);
805  $pos = strpos($text, ". ");
806  return ($pos) ? substr($text, 0, $pos + 1) : $text;
807 }

◆ format_phone()

format_phone (   $phone)

Definition at line 398 of file functions.inc.

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 }

◆ formatAddress()

formatAddress ( )

Utility function to nicely format addresses, etc.

(skips blank entries, places all other entries on separate lines)

Deprecated

Definition at line 126 of file functions.inc.

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 }

◆ formatAsHTML()

formatAsHTML (   $text)

Takes a string and formats it for display as HTML, removing any HTML tags it contains, and converting carriage returns to br tags.

Parameters
$textthe text to format
Returns
string the formatted text

Definition at line 1405 of file functions.inc.

1406 {
1407  if (preg_match("/<.*?>/", $text)) return $text;
1408  $text = str_replace("\n", "<br/>", $text);
1409 
1410  return $text;
1411 }

◆ formatCheckListItemsforView()

formatCheckListItemsforView (   $options,
  $items 
)

For dataitems that are rendered as CheckListFieldRenderer, this function converts the comma-delimited list of items for display.

To do: add handling of grouped checkboxes and provide parameter for delimiter between items

Deprecated

Definition at line 1504 of file functions.inc.

1505 {
1506  if(count($options) == 0) return;
1507 
1508  $values = explode(",", $items);
1509 
1510  foreach($values as $value)
1511  {
1512  if(array_key_exists($value, $options))
1513  {
1514  $list .= $options[$value] . ", ";
1515  }
1516  else
1517  $list .= $value . ", ";
1518  }
1519 
1520  if(strlen($list) > 0)
1521  $list = substr($list, 0, strlen($list) - 2);
1522 
1523  return $list;
1524 }

◆ formatCurrency()

formatCurrency (   $amount)

Utility function to format currency using $ and , and stuff.

Deprecated

Definition at line 142 of file functions.inc.

143 {
144  return "$".number_format($amount, 2, '.', ',');
145 }

◆ formatDate()

formatDate (   $date)

Utility function to format date (no time component).

Parameters
string$datethe date to format

Deprecated

Definition at line 154 of file functions.inc.

155 {
156 
157  if ($date !='Jan 1 1900 12:00AM')
158  {
159  return date("F d, Y", strtotime($date));
160  }
161 }

◆ formatDateLong()

formatDateLong (   $date)
Parameters
$dateDeprecated

Definition at line 203 of file functions.inc.

204 {
205  $text = "";
206 
207  if ($date)
208  {
209  $text = date("l F j, Y", strtotime($date));
210  }
211 
212  return $text;
213 }

◆ formatDateShort()

formatDateShort (   $date)

Utility function to format date in short form (MM/DD/YYYY), with no time component.

Deprecated

Definition at line 183 of file functions.inc.

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 }

◆ formatDateTime12()

formatDateTime12 (   $time)

Format a date and time in 12 hour clock, no seconds.

Deprecated

Definition at line 321 of file functions.inc.

322 {
323  return date("m/d/Y g:ia", $time);
324 }

◆ formatDateTime12Hr()

formatDateTime12Hr (   $datetime)

Definition at line 334 of file functions.inc.

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 }

◆ formatMonthYear()

formatMonthYear (   $date)
Parameters
$dateDeprecated

Definition at line 169 of file functions.inc.

170 {
171 
172  if ($date !='Jan 1 1900 12:00AM')
173  {
174  return date("F Y", strtotime($date));
175  }
176 }

◆ formatStartDateToEndDate()

formatStartDateToEndDate (   $start,
  $end 
)

Definition at line 361 of file functions.inc.

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 }
formatDateTime12Hr($datetime)
Definition: functions.inc:334
formatDateShort($date)
Utility function to format date in short form (MM/DD/YYYY), with no time component.
Definition: functions.inc:183

◆ formatTime12()

formatTime12 (   $time)

Format a time in 12 hour clock, no seconds.

Deprecated

Definition at line 311 of file functions.inc.

312 {
313  return date("g:ia", $time);
314 }

◆ formatTimestamp()

formatTimestamp (   $ts)

Utility function to format readable date from a timestamp (no time component).

Timestamp is a string in the format 'YYYYMMDDHHIISS'.

Parameters
string$tsthe timestamp to format.

Deprecated

Definition at line 223 of file functions.inc.

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 }

◆ formatTimestampShort()

formatTimestampShort (   $ts)

Definition at line 247 of file functions.inc.

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 }

◆ getBacktrace()

getBacktrace (   $ignore = 2)

Returns a formatted backtrace suitable for debugging output.

Definition at line 1895 of file functions.inc.

1896 {
1897  $trace = '';
1898  foreach (debug_backtrace() as $k => $v) {
1899  if ($k < $ignore) {
1900  continue;
1901  }
1902 
1903  array_walk($v['args'], function (&$item, $key) {
1904  $item = var_export($item, true);
1905  });
1906 
1907  $trace .= '#' . ($k - $ignore) . ' ' . $v['file'] . '(' . $v['line'] . '): ' . (isset($v['class']) ? $v['class'] . '->' : '') . $v['function'] . '(' . implode(', ', $v['args']) . ')' . "\n";
1908  }
1909 
1910  return $trace;
1911 }

◆ getCleanQueryString()

getCleanQueryString ( )

Returns the query string for the current page, cleaned of any Fakoli-related navigation parameters.

Definition at line 935 of file functions.inc.

936 {
937  $qs = $_SERVER['QUERY_STRING'];
938 
939  $params = array();
940 
941  foreach($_GET as $key => $value)
942  {
943  if ($key != "identifier" && $key != "section") $params[$key] = $value;
944  }
945 
946  return http_build_query($params);
947 }

◆ getDocIcon()

getDocIcon (   $doc)
Parameters
unknown_type$docDeprecated

Definition at line 615 of file functions.inc.

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 }
$doc_icons

◆ getDocMimeType()

getDocMimeType (   $name)
Parameters
$nameDeprecated

Definition at line 586 of file functions.inc.

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 }
$doc_mime_types

◆ getDocSize()

getDocSize (   $doc)

Returns the file size in Kb for a document.

Parameters
string$docthe (local) URL of the document

Deprecated

Definition at line 554 of file functions.inc.

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 }

◆ getDocType()

getDocType (   $doc)

Returns a human-readable type name for a document, based on the file extension of the supplied file name.

Parameters
string$docthe filename of the document

Deprecated

Definition at line 531 of file functions.inc.

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 }
$doc_extensions
Mapping of common file extensions to human-readable document type.

◆ getFullQueryString()

getFullQueryString (   $includePOST = true)

Generates a query string containing the values passed to this page.

The default behavior is to include parameters passed both as GET and POST parameters. To retrieve only the GET parameters, pass false.

Parameters
boolean$includePOSTtrue (default) to include POST parameters, false for only GET parameters
Returns
string the full query string for the current page.

Definition at line 1584 of file functions.inc.

1585 {
1586  global $__urlRewriteParams;
1587 
1588  $qs = "";
1589  $sep = "?";
1590 
1591  foreach($_GET as $name => $value)
1592  {
1593  if (array_key_exists($name, $__urlRewriteParams)) continue;
1594 
1595  if (is_array($value))
1596  {
1597  foreach($value as $key => $val)
1598  {
1599  $qs .= $sep.urlencode($name)."[".urlencode($key)."]=".urlencode($val);
1600  $sep = "&";
1601  }
1602  }
1603  else
1604  {
1605  $qs .= $sep.urlencode($name)."=".urlencode($value);
1606  $sep = "&";
1607  }
1608  }
1609 
1610  if ($includePOST)
1611  {
1612  foreach($_POST as $name => $value)
1613  {
1614  if (is_array($value))
1615  {
1616  foreach($value as $key => $val)
1617  {
1618  $qs .= $sep.urlencode($name)."[".urlencode($key)."]=".urlencode($val);
1619  $sep = "&";
1620  }
1621  }
1622  else
1623  {
1624  $qs .= $sep.urlencode($name)."=".urlencode($value);
1625  $sep = "&";
1626  }
1627  }
1628  }
1629 
1630  return $qs;
1631 }
$__urlRewriteParams
Definition: functions.inc:1560

◆ getIcon()

getIcon (   $file)

Retrieves a graphic icon appropriate for the given file.

Parameters
$filethe name of the file
Returns
string URL of the graphic icon for the file

Definition at line 1098 of file functions.inc.

1099 {
1100  global $_icons;
1101  global $auto_form_defaults;
1102 
1103  $ext = substr($file, strrpos($file, "."));
1104  $icon = $_icons[$ext];
1105  trace("getIcon($file) $ext $icon", 3);
1106 
1107  if (!isset($icon))
1108  {
1109  $icon = $_icons["default"];
1110  }
1111 
1112  return $auto_form_defaults["componentPath"].$icon;
1113 }
$_icons
Definition: functions.inc:1087
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ getMIMEType()

getMIMEType (   $filename)
Parameters
String$filenameDeprecated

Definition at line 1742 of file functions.inc.

1743 {
1744  $mime_types = array(
1745 
1746  'txt' => 'text/plain',
1747  'htm' => 'text/html',
1748  'html' => 'text/html',
1749  'css' => 'text/css',
1750  'js' => 'application/javascript',
1751  'json' => 'application/json',
1752  'xml' => 'application/xml',
1753  'swf' => 'application/x-shockwave-flash',
1754  'flv' => 'video/x-flv',
1755 
1756  // images
1757  'png' => 'image/png',
1758  'jpe' => 'image/jpeg',
1759  'jpeg' => 'image/jpeg',
1760  'jpg' => 'image/jpeg',
1761  'gif' => 'image/gif',
1762  'bmp' => 'image/bmp',
1763  'ico' => 'image/vnd.microsoft.icon',
1764  'tiff' => 'image/tiff',
1765  'tif' => 'image/tiff',
1766  'svg' => 'image/svg+xml',
1767  'svgz' => 'image/svg+xml',
1768 
1769  // archives
1770  'zip' => 'application/zip',
1771  'rar' => 'application/x-rar-compressed',
1772  'exe' => 'application/x-msdownload',
1773  'msi' => 'application/x-msdownload',
1774  'cab' => 'application/vnd.ms-cab-compressed',
1775 
1776  // audio/video
1777  'mp3' => 'audio/mpeg',
1778  'qt' => 'video/quicktime',
1779  'mov' => 'video/quicktime',
1780 
1781  // adobe
1782  'pdf' => 'application/pdf',
1783  'psd' => 'image/vnd.adobe.photoshop',
1784  'ai' => 'application/postscript',
1785  'eps' => 'application/postscript',
1786  'ps' => 'application/postscript',
1787 
1788  // ms office
1789  'doc' => 'application/msword',
1790  'rtf' => 'application/rtf',
1791  'xls' => 'application/vnd.ms-excel',
1792  'ppt' => 'application/vnd.ms-powerpoint',
1793 
1794  // open office
1795  'odt' => 'application/vnd.oasis.opendocument.text',
1796  'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1797  );
1798 
1799  $ext = strtolower(array_pop(explode('.',$filename)));
1800 
1801  if (array_key_exists($ext, $mime_types))
1802  {
1803  return $mime_types[$ext];
1804  }
1805  elseif (function_exists('finfo_open'))
1806  {
1807  $finfo = finfo_open(FILEINFO_MIME);
1808  $mimetype = finfo_file($finfo, $filename);
1809  finfo_close($finfo);
1810  return $mimetype;
1811  }
1812  else
1813  {
1814  // Prevent other file types (such as source code or configuration files) from being served
1815  die("");
1816  }
1817 }

◆ getMonthDays()

getMonthDays (   $m,
  $y 
)

Returns the number of days in the specified month.

Parameters
number$mthe month number
number$ythe year
Returns
number the number of days in that month

Deprecated

Definition at line 272 of file functions.inc.

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 }

◆ getMonthWeekDays()

getMonthWeekDays (   $month,
  $year 
)

Get the number of week days in the specified month.

Parameters
number$mthe month number
number$ythe year
Returns
number the number of week days in that month

Deprecated

Definition at line 289 of file functions.inc.

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 }
getMonthDays($m, $y)
Returns the number of days in the specified month.
Definition: functions.inc:272

◆ getRemote()

getRemote (   $url,
  $username = "",
  $password = "" 
)

Retrieve the contents of the remote file at the given URL.

Parameters
string$urlthe URL to retrieve
string$username(optional) username for basic authentication
string$password(optional) password for basic authentication
Returns
string the contents of the file at that URL

Definition at line 1141 of file functions.inc.

1142 {
1143  $url = canonicalizeURL($url);
1144  trace("Retrieving $url", 3);
1145  $ch = curl_init("$url");
1146  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1147  curl_setopt($ch, CURLOPT_HEADER, 0);
1148  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1149 
1150  if ($username)
1151  {
1152  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
1153  curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
1154  }
1155 
1156  $html = curl_exec($ch);
1157 
1158  if ($html === FALSE) throw new Exception(curl_error($ch));
1159 
1160  curl_close($ch);
1161 
1162  return $html;
1163 }
canonicalizeURL($url)
Takes a URL and converts relative URLs to absolute URLs for the current site.
Definition: functions.inc:1227
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ getRemoteHeaders()

getRemoteHeaders (   $url)

Retrieve the HTTP headers for the specified remote URL (excluding the body).

Parameters
string$urlthe URL to retrieve
Returns
the headers.

Definition at line 1308 of file functions.inc.

1309 {
1310  $ch = curl_init();
1311  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1312  curl_setopt($ch, CURLOPT_HEADER, 1);
1313  curl_setopt($ch, CURLOPT_NOBODY, 1);
1314  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1315 
1316  $html = curl_exec($ch);
1317 
1318  curl_close($ch);
1319 
1320  return $html;
1321 }

◆ getScaledSize()

getScaledSize (   $size,
  $decimal_places = 1 
)

Get human-readable file size from raw number of bytes.

Parameters
$sizethe size of the file in bytes
$decimal_placesthe number of decimal places in the output (default is 1)
Returns
string human-readable file size in appropriate units

Definition at line 1037 of file functions.inc.

1038 {
1039  if (!$size) return "";
1040 
1041  $result = "";
1042  if ($size > 1073741824)
1043  {
1044  $result = sprintf("%.{$decimal_places}fGB", ($size / 1073741824));
1045  }
1046  else if ($size > 1048576)
1047  {
1048  $result = sprintf("%.{$decimal_places}fMB", ($size / 1048576));
1049  }
1050  else if ($size > 1024)
1051  {
1052  $result = intval($size / 1024)."KB";
1053  }
1054  else
1055  {
1056  $result = "$size bytes";
1057  }
1058 
1059  return $result;
1060 }

◆ GUID()

GUID ( )

Generates a version 4 GUID.

Returns
string

Definition at line 1873 of file functions.inc.

1874 {
1875  if (function_exists('com_create_guid') === true)
1876  {
1877  return trim(com_create_guid(), '{}');
1878  }
1879 
1880  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)).'}';
1881 }

◆ hasRole()

hasRole (   $role,
  $account = null 
)

Determine whether a user has a specific role explicitly set.

Unlike checkRole() this does not always return true if a user is super or admin.

Parameters
string$role
object$account
Returns
boolean true if the user has the specified role explicitly set, false otherwise.

Definition at line 82 of file functions.inc.

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 }

◆ htmlsafe()

htmlsafe (   $str)

Definition at line 451 of file functions.inc.

452 {
453  return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
454 }

◆ HTMLToText()

HTMLToText (   $html)

Definition at line 461 of file functions.inc.

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 }
stripHTML($text)
Definition: functions.inc:809

◆ includeRemote()

includeRemote (   $host,
  $file 
)

Includes the contents of the given remote file, with any relative src or href references converted to absolute references.

The included file is echoed directly to the output stream.

Parameters
$hostthe host to retrieve the file from
$filethe URI of the file on the host

Definition at line 1122 of file functions.inc.

1123 {
1124  $ch = curl_init("http://$host/$file");
1125  curl_setopt($ch, CURLOPT_HEADER, 0);
1126  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1127  $html = curl_exec($ch);
1128  curl_close($ch);
1129 
1130  $html = preg_replace("/(src|href)(=['\"])\//", "$1$2http://$host/", $html);
1131  echo $html;
1132 }

◆ jsonRequest()

jsonRequest (   $url,
  $params = array() 
)

Make a simple GET request to a JSON-return RESTful API, passing the supplied parameters.

Parameters
string$urlthe target URL for the API
array$paramsan array of parameters to pass, as key-value pairs

Definition at line 1170 of file functions.inc.

1171 {
1172  $qs = array();
1173  foreach($params as $key => $value)
1174  {
1175  $qs[] = "$key=".urlencode($value);
1176  }
1177 
1178  $qs = implode("&", $qs);
1179 
1180  $api = "{$url}?{$qs}";
1181  trace($api);
1182  $response = getRemote($api);
1183  return json_decode($response);
1184 }
getRemote($url, $username="", $password="")
Retrieve the contents of the remote file at the given URL.
Definition: functions.inc:1141
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ jsSafe()

jsSafe (   $str,
  $escapeEntities = false 
)

Utility function to escape a string correctly for use in a Javascript client-side call.

Parameters
string$strthe string to make safe.

Definition at line 434 of file functions.inc.

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 }

◆ luhnTest()

luhnTest (   $num)

Performs a Luhn validity test for credit card or IMEI numbers.

Parameters
string$numcredit card or IMEI number
Returns
boolean true if valid, false otherwise

Definition at line 1918 of file functions.inc.

1919 {
1920  $len = strlen($num);
1921  for ($i = $len-1; $i >= 0; $i--)
1922  {
1923  $ord = ord($num[$i]);
1924  if (($len - 1) & $i)
1925  {
1926  $sum += $ord;
1927  }
1928  else
1929  {
1930  $sum += $ord / 5 + (2 * $ord) % 10;
1931  }
1932  }
1933  return $sum % 10 == 0;
1934 }

◆ makeRandomString()

makeRandomString (   $len)

Creates a randomized string of characters.

This is not cryptographically secure and should not be used for cryptographic operations.

Parameters
int$lenthe length of the string to generate
Returns
string the generated string

Definition at line 1675 of file functions.inc.

1676 {
1677  $str = "";
1678  for($i = 0; $i < $len; ++$i)
1679  {
1680  $str .= chr(ord('a') + rand(0, 25));
1681  }
1682 
1683  return $str;
1684 }

◆ makeURL()

makeURL (   $uri)

Ensures that the http:// protocol specifier prefix is present in the supplied string.

Parameters
string$urithe string to process
Returns
string the full URL with protocol prefix added if it was missing.

Definition at line 1488 of file functions.inc.

1489 {
1490  if (!startsWith($uri, "http://")) $uri = "http://$uri";
1491  return $uri;
1492 }
startsWith($text, $start)
Tests whether a string starts with a given sub-string.
Definition: functions.inc:1419

◆ now()

now ( )

Returns the current time and date in a database compatible format.

Returns
string

Definition at line 416 of file functions.inc.

417 {
418  return date('Y/m/d H:i:s');
419 }

◆ option()

option (   $value,
  $text,
  $sel = "" 
)

Write out an option tag, marking as selected if applicable.

Parameters
mixed$valuethe value of the option
string$textthe text for the option
mixed$sela value to compare to the $value field, to determine whether the option should be selected.

Definition at line 850 of file functions.inc.

851 {
852  echo "<option value='$value'";
853  if ($sel === $value)
854  {
855  echo " selected";
856  }
857  echo ">$text</option>";
858 }

◆ ordinalSuffix()

ordinalSuffix (   $n,
  $sup = false 
)

Adds the english ordinal suffix to a number.

If the value passed is not purely numeric, it will be returned unchanged.

Parameters
$nthe value for the ordinal suffix
$suptrue to add HTML superscript tag, false for plain text
Returns
string the value with the appropriate ordinal suffix appended.

Definition at line 1452 of file functions.inc.

1453 {
1454  $suffix = "";
1455  if (is_numeric($n))
1456  {
1457  $n = trim($n);
1458 
1459  $lastTwo = substr($n, -2, 2);
1460  $lastOne = substr($n, -1, 1);
1461 
1462  if ($lastTwo == "11" || $lastTwo == "12" || $lastTwo == "13") $suffix = "th";
1463  else
1464  {
1465  switch($lastOne)
1466  {
1467  case "1": $suffix = "st"; break;
1468  case "2": $suffix = "nd"; break;
1469  case "3": $suffix = "rd"; break;
1470  default: $suffix = "th";
1471  }
1472  }
1473  }
1474  else return $n;
1475 
1476  // JDG 2/10/12 - fix was not returning value if $sup false
1477  if ($sup)
1478  return "$n<sup>$suffix</sup>";
1479  else
1480  return "$n$suffix";
1481 }

◆ parseMultiParam()

parseMultiParam (   $collection,
  $param 
)

Parse out multiple values from the provided collection that have the same root name, and return the results in an array.

Parameters
array$collectionthe parameter collection (usually $_POST or $_GET)
string$paramthe root name for the params to search for

Definition at line 827 of file functions.inc.

828 {
829  $len = strlen($param);
830  $values = array();
831 
832  foreach($collection as $field => $value)
833  {
834  if (!strncmp($field, $param, $len))
835  {
836  $values[] = $value;
837  }
838  }
839 
840  return $values;
841 }

◆ plainGUID()

plainGUID ( )

Generates a version 4 GUID with no punctutation.

Returns
string

Definition at line 1887 of file functions.inc.

1888 {
1889  return str_replace(array("{", "}", "-"), array("", "", ""), GUID());
1890 }
GUID()
Generates a version 4 GUID.
Definition: functions.inc:1873

◆ pluralize()

pluralize (   $text,
  $count = 0 
)

Takes a singular string and makes it plural.

Parameters
$textthe string to make plural
$countinteger (optional) the number of items, to determine whether to pluralize or not
Returns
string the plural version

Definition at line 1377 of file functions.inc.

1378 {
1379  if ($count == 1) return $text;
1380 
1381  $c = $text;
1382 
1383  if (preg_match("/[^aeiouAEIOU]y$/", $c))
1384  {
1385  $c = substr($c, 0, -1)."ies";
1386  }
1387  else if (preg_match("/(?:ss|[^aeiou]o|x|s|ch)$/", $c))
1388  {
1389  $c .= "es";
1390  }
1391  else
1392  {
1393  $c .= "s";
1394  }
1395 
1396  return $c;
1397 }

◆ postRemote()

postRemote (   $url,
  $data = null,
  $timeout = 30 
)

Make a POST request to a remote URL, returning the results.

Parameters
$urlthe URL of the page to submit the POST request to
$datathe POST parameters, passed as an array of key => value pairs
$timeoutthe amount of time to wait for the POST to complete
Returns
string the results of the POST request

Definition at line 1274 of file functions.inc.

1275 {
1276  $ch = curl_init();
1277  curl_setopt($ch, CURLOPT_URL, $url);
1278  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1279  curl_setopt($ch, CURLOPT_HEADER, 0);
1280  curl_setopt($ch, CURLOPT_POST, 1);
1281  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
1282  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
1283  $result = trim(curl_exec($ch));
1284  curl_close($ch);
1285  return $result;
1286 }

◆ postRemoteXML()

postRemoteXML (   $url,
  $xml,
  $timeout = 30 
)

Definition at line 1288 of file functions.inc.

1289 {
1290  $ch = curl_init($url);
1291  curl_setopt($ch, CURLOPT_MUTE, 1);
1292  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
1293  curl_setopt($ch, CURLOPT_POST, 1);
1294  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
1295  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
1296  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1297  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
1298  $result = trim(curl_exec($ch));
1299  curl_close($ch);
1300  return $result;
1301 }

◆ prettify()

prettify (   $name)

Takes a variable or field name and converts it into a human-readable version (assuming that the original contains human-readable words, of course).

It handles CamelCase and underscores. Individual words in the output are capitalized.

Parameters
$namethe string to prettify
Returns
string the prettified version of the string

Definition at line 1362 of file functions.inc.

1363 {
1364  $name = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $name);
1365  $name = str_replace("_", " ", $name);
1366  $name = ucwords($name);
1367 
1368  return $name;
1369 }

◆ printIncludes()

printIncludes (   $html = true,
  $return = false 
)

Outputs a list of all included files.

This is provided as a tool for troubleshooting.

Parameters
boolean$htmlwhether to include HTML formatting in the output (default true)
boolean$returnset to true to return the list as the return value, false to print to the output buffer

Definition at line 1956 of file functions.inc.

1957 {
1958  if ($return)
1959  {
1960  ob_start();
1961  }
1962 
1963  $includes = get_included_files();
1964  if ($html) echo "<ul>\n";
1965  foreach($includes as $include)
1966  {
1967  if ($html)
1968  {
1969  echo "<li>$include</li>";
1970  }
1971  else
1972  {
1973  echo $include."\n";
1974  }
1975  }
1976  if ($html) echo "</ul>";
1977 
1978  if ($return)
1979  {
1980  $out = ob_get_contents();
1981  ob_end_clean();
1982  return $out;
1983  }
1984 }

◆ printMIMETypeList()

printMIMETypeList (   $types)

Outputs the MIME type list based on an array of MIME types.

Use this function to generate the contents of ACCEPT= attributes for <INPUT TYPE="file" ...> tags.

Deprecated

Definition at line 511 of file functions.inc.

512 {
513  print "*";
514  //foreach ($types as $t)
515  //{
516  // if ($out) $out .= ",";
517  // $out .= $t;
518  //}
519 
520  //print $out;
521 }

◆ redirect()

redirect (   $page)

Simplified redirect.

Parameters
$pagethe page to redirect to

Definition at line 884 of file functions.inc.

885 {
886  global $_SERVER;
887  global $config;
888 
889  if ($config['prettyURLs'] === false)
890  {
891  $page = preg_replace("/^\\/?([\\w\\d_]+?)\\?/", "/page.php?identifier=$1&", $page);
892  $page = preg_replace("/^\\/?([\\w\\d_]+)$/", "/page.php?identifier=$1", $page);
893  }
894 
895  trace("redirect:: page is $page", 3);
896  $server = $config['http_host'];
897  if (!$server) $server="localhost:8080";
898 
899  //AJG: 3/9/11 - maintain current protocol by default
900 
901  $https = $_SERVER['HTTPS'];
902  if ($https == "off") $https = false;
903 
904  $protocol = $https ? "https" : "http";
905 
906  // JDG 9/27/10 - handle https
907  if (!strncmp($page, "http://", 7) OR (!strncmp($page, "https://", 8)))
908  {
909  $location = $page;
910  }
911  else if ($page[0] == '/')
912  {
913  $location = "$protocol://$server$page";
914  }
915 // else if (preg_match( "/^[\\w\\d_\\-]+$/", $page))
916 // {
917 // $location = "http://$server/$page";
918 // }
919  else
920  {
921  $directory = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['REQUEST_URI']));
922  if ($directory == "/") $directory = "";
923  $location = "$protocol://".$server.$directory."/".$page;
924  }
925 
926  header("Location: $location");
927  session_write_close();
928  exit;
929 }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ registerURLRewriteParameters()

registerURLRewriteParameters ( )

Register any URL rewrite parameters that should be excluded from query string reformatting.

Definition at line 1566 of file functions.inc.

1567 {
1568  global $__urlRewriteParams;
1569 
1570  for($i = 0; $i < func_num_args(); ++$i)
1571  {
1572  $__urlRewriteParams[func_get_arg($i)] = true;
1573  }
1574 }
$__urlRewriteParams
Definition: functions.inc:1560

◆ roundFormat()

roundFormat (   $num,
  $abbrev = false 
)

Definition at line 1062 of file functions.inc.

1063 {
1064  if (!$num) return "";
1065 
1066  $result = "";
1067  if ($abbrev == false) {
1068  if ($num >= 1000000000) {
1069  $result = sprintf("%.1f billion", ($num / 1000000000));
1070  } elseif ($num >= 1000000) {
1071  $result = sprintf("%.1f million", ($num / 1000000));;
1072  } elseif ($num >= 1000) {
1073  $result = sprintf("%.0f,000", ($num / 1000));;
1074  }
1075  } else {
1076  if ($num >= 1000000000) {
1077  $result = sprintf("%.1f bn", ($num / 1000000000));
1078  } elseif ($num >= 1000000) {
1079  $result = sprintf("%.1f m", ($num / 1000000));;
1080  } elseif ($num >= 1000) {
1081  $result = sprintf("%.0f,000", ($num / 1000));
1082  }
1083  }
1084  return $result;
1085 }

◆ rteClean()

rteClean (   $strText)
Parameters
unknown_type$strTextDeprecated

Definition at line 778 of file functions.inc.

779 {
780  $patterns = array( "|<\\!\\-\\-\\s+HEADERS\\s+\\-\\->.*<\\!\\-\\-\\s+/HEADERS\\s+\\-\\->|i",
781  "/_base_href=\\\?\".*?\"/i",
782  "|href=\\\?\"http://www.sonjara.com/ictinedtoolkit|i",
783  "|src=\\\?\"http://www.sonjara.com\\/ictinedtoolkit|i",
784  "|href=\\\?\"http://www.ictinedtoolkit.org|i",
785  "|src=\\\?\"http://www.ictinedtoolkit.org|i");
786 
787  $subs = array( "", "", "href=\\\"..", "src=\\\"..", "href=\\\"..", "src=\\\"..");
788 
789  $strText = preg_replace($patterns, $subs, $strText);
790 
791  return $strText;
792 }

◆ rtePrepare()

rtePrepare (   $strText,
  $css 
)
Parameters
unknown_type$strText
unknown_type$cssDeprecated

Definition at line 766 of file functions.inc.

767 {
768  global $_SERVER;
769  return rteSafe($strText);
770 }
rteSafe($strText)
Definition: functions.inc:738

◆ rteSafe()

rteSafe (   $strText)
Parameters
unknown_type$strTextDeprecated

Definition at line 738 of file functions.inc.

738  {
739  //returns safe code for preloading in the RTE
740  $tmpString = $strText;
741 
742  //convert all types of single quotes
743  $tmpString = str_replace(chr(145), chr(39), $tmpString);
744  $tmpString = str_replace(chr(146), chr(39), $tmpString);
745  $tmpString = str_replace("'", "&#39;", $tmpString);
746 
747  //convert all types of double quotes
748  $tmpString = str_replace(chr(147), chr(34), $tmpString);
749  $tmpString = str_replace(chr(148), chr(34), $tmpString);
750 // $tmpString = str_replace("\"", "\"", $tmpString);
751 
752  //replace carriage returns & line feeds
753  $tmpString = str_replace(chr(10), " ", $tmpString);
754  $tmpString = str_replace(chr(13), " ", $tmpString);
755 
756  return $tmpString;
757 }

◆ sanitizePath()

sanitizePath (   $path)

Sanitize a file path, removing relative path sections and ensuring the correct directory separator is used throughout.

Parameters
string$pathpotentially dirty path
Returns
string clean path

Definition at line 1258 of file functions.inc.

1259 {
1260  $path = str_replace("/", DIRECTORY_SEPARATOR, $path);
1261  $path = str_replace("\\", DIRECTORY_SEPARATOR, $path);
1262  $path = str_replace("..".DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
1263  $path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
1264  return $path;
1265 }

◆ saveRemote()

saveRemote (   $url,
  $saveAs 
)

Retreive the contents of the remote file at the given URL and save it to the specified location on the local disk.

Parameters
$urlthe URL to retrieve
$saveAsthe path and file name where the downloaded file should be stored.
Returns
returns the content type of the retrieved file as specified by the server

Definition at line 1195 of file functions.inc.

1196 {
1197  trace("Downloading $url to $saveAs", 3);
1198 
1199  $ch = curl_init ($url);
1200  curl_setopt($ch, CURLOPT_HEADER, 0);
1201  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1202  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1203  curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
1204  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1205 
1206  $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
1207  $bytes = curl_exec($ch);
1208  curl_close ($ch);
1209 
1210  trace(count($bytes)." bytes recieved", 3);
1211 
1212  if(file_exists($saveAs))
1213  {
1214  unlink($saveAs);
1215  }
1216 
1217  file_put_contents($saveAs, $bytes);
1218 
1219  return $contentType;
1220 }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959

◆ startsWith()

startsWith (   $text,
  $start 
)

Tests whether a string starts with a given sub-string.

Parameters
$textthe string to test
$startthe sub-string to look for at the start
Returns
boolean true if the string starts with the sub-string, false otherwise

Definition at line 1419 of file functions.inc.

1420 {
1421  return (strncmp($text, $start, strlen($start)) == 0);
1422 }

◆ str_option()

str_option (   $value,
  $text,
  $sel = "" 
)

Write out an option tag to a string, marking as selected if applicable.

Parameters
mixed$valuethe value of the option
string$textthe text for the option
mixed$sela value to compare to the $value field, to determine whether the option should be selected.

Definition at line 868 of file functions.inc.

869 {
870  $opt = "<option value='$value'";
871  if ($sel == $value)
872  {
873  $opt .= " selected";
874  }
875  $opt .= ">$text</option>";
876 
877  return $opt;
878 }

◆ stripHTML()

stripHTML (   $text)

Definition at line 809 of file functions.inc.

810 {
811  /*$text = preg_replace("/<.*?>/", "", $text);*/
812  $text = strip_tags($text);
813 
814  // JDG 5/19/2011 - remove &ndash, &nbsp;
815  $text = html_entity_decode($text);
816  $text = trim($text);
817  return $text;
818 }

◆ stripHTMLTags()

stripHTMLTags (   $text)

Removes all HTML tags from the specified string.

Parameters
$textthe string from which tags are to be removed
Returns
string the cleaned text.

Definition at line 1440 of file functions.inc.

1441 {
1442  return preg_replace("/<.*?>/", "", $text);
1443 }

◆ today()

today ( )

Returns today as a string.

All of it.

Definition at line 424 of file functions.inc.

425 {
426  return date('Y-m-d');
427 }

◆ toJSArray()

toJSArray (   $items,
  $field = "" 
)

Definition at line 1643 of file functions.inc.

1644 {
1645  $js_arr = "[";
1646  $first = true;
1647 
1648  if(count($items) == 0)
1649  return "";
1650 
1651  if(is_object($items[0]) && !$field)
1652  {
1653  $field = $items[0]->getPrimaryKey();
1654  }
1655 
1656  foreach($items as $item)
1657  {
1658  if (!$first) $js_arr .=", ";
1659  $js_arr .= (is_object($item) && $field) ? $item->$field : $item;
1660  $first = false;
1661  }
1662 
1663  $js_arr .= "]";
1664 
1665  return $js_arr;
1666 }

◆ trace()

trace (   $msg,
  $lvl,
  $callStack = null 
)

Send output to the trace log.

Parameters
$msgthe message to output
$lvlthe severity level (0-5) of this message

Definition at line 959 of file functions.inc.

960 {
961  global $config;
962  global $traceLevels;
963 
964  if ($lvl <= $config["trace_level"])
965  {
966  switch($config["trace_detail"])
967  {
968  case TraceDetailFull:
969 
970  $callStack = $callStack ? $callStack : debug_backtrace();
971  if (count($callStack) > 1)
972  {
973  $callingFn = $callStack[1];
974  }
975  else
976  {
977  $callingFn = $callStack[0];
978  }
979  $file = str_replace($config["homedir"], "", $callingFn["file"]);
980  $ref = $file.":".$callingFn["line"]." ";
981  if ($callingFn["class"])
982  {
983  $ref .= $callingFn["class"].$callingFn["type"];
984  }
985 
986  $ref .= $callingFn["function"]."(): ";
987 
988  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s")." : ".$_SERVER['REQUEST_URI']." : ".$ref." ".$msg."\r\n", 3, $config["trace_path"]);
989  break;
990 
991  case TraceDetailHigh:
992 
993  $callStack = $callStack ? $callStack : debug_backtrace();
994 
995  if (count($callStack) > 1)
996  {
997  $callingFn = $callStack[1];
998  }
999  else
1000  {
1001  $callingFn = $callStack[0];
1002  }
1003 
1004  $file = str_replace($config["homedir"], "", $callingFn["file"]);
1005  $ref = $file.":".$callingFn["line"]." ";
1006  if ($callingFn["class"])
1007  {
1008  $ref .= $callingFn["class"].$callingFn["type"];
1009  }
1010 
1011  $ref .= $callingFn["function"]."(): ";
1012 
1013  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s")." : ".$ref." ".$msg."\r\n", 3, $config["trace_path"]);
1014  break;
1015 
1016 
1017  case TraceDetailMedium:
1018  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s : ").$msg."\r\n", 3, $config["trace_path"]);
1019  break;
1020 
1021  case TraceDetailNormal:
1022  default:
1023 
1024  error_log("[".$traceLevels[$lvl]."] ".$msg."\r\n", 3, $config["trace_path"]);
1025  break;
1026  }
1027  }
1028 }
$traceLevels
Definition: functions.inc:949

◆ wrapURL()

wrapURL (   $url,
  $width = 120 
)

Break a URL at a given string position.

This can help prevent long URLs from messing up your page layout.

Parameters
$urlthe URL to break
$widththe maximum line length (in characters)
Returns
string the URL, wrapped for display

Definition at line 1330 of file functions.inc.

1331 {
1332  $text = str_replace(" ", "%20", $url);
1333  $text = str_replace("/", " ", $text);
1334  $text = wordwrap($text, $width, "/<br>", true);
1335  $text = str_replace(" ", "/", $text);
1336 
1337  return $text;
1338 }

◆ xmlEntities()

xmlEntities (   $string)

Function to provide html to XML entity renaming.

Provides fallback for PHP versions earlier than 5.4 that do not have the ENT_XML1 format available for the htmlentities() call.

Parameters
string$stringthe string to convert
Returns
string

Definition at line 1842 of file functions.inc.

1843 {
1844  if (defined(ENT_XML1)) return htmlentities($value, ENT_XML1);
1845 
1846  $result = '';
1847  foreach (str_split(utf8_decode(htmlspecialchars($string))) as $char)
1848  {
1849  $num = ord($char);
1850  if ($num > 127) {
1851  $result .= '&#' . $num . ';';
1852  } else {
1853  $result .= $char;
1854  }
1855  }
1856  return $result;
1857 }

Variable Documentation

◆ $__urlRewriteParams

$__urlRewriteParams = array()

Definition at line 1560 of file functions.inc.

◆ $_icons

$_icons
Initial value:
= array(".doc" => "/images/msword_icon.png",
".xls" => "/images/msexcel_icon.png",
".pdf" => "/images/pdf_icon.png",
".ppt" => "/images/ppt_icon.png",
"default" => "/images/file_icon.png")

Definition at line 1087 of file functions.inc.

◆ $image_types

$image_types = array( "image/jpeg", "image/gif", "image/x-png", "image/pjpeg" )

MIME types allowable for image uploads.

Definition at line 118 of file functions.inc.

◆ $traceLevels

$traceLevels
Initial value:
= array(1 => "FATAL",
2 => "ERROR",
3 => "TRACE",
4 => "DEBUG",
5 => "NOTE*")

Definition at line 949 of file functions.inc.