Framework  3.9
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...
 
 checkIdentifierList ($p)
 Security helper function. More...
 
 checkValidEmail ($e)
 Security helper function. More...
 
 checkValidDate ($d)
 Security helper function. More...
 
 checkValidDateTime ($d)
 Security helper function. More...
 
 checkPlainGUID ($guid)
 Checkes whether the provided string is an undecorated GUID (i.e. More...
 
 checkGUID ($guid)
 Checks whether the provided string is in a valid form for a GUID. 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)
 
 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...
 
 registerRedirectLogCallback ($callback)
 
 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=3, $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="")
 
 prettyPrintJSON ($json)
 Format the JSON in the supplied string to be more human-readable. More...
 
 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...
 
 replaceValues ($substitutions, $target)
 Given an array of pairs of old and new values, replace all instances of old values with new values in the target string. More...
 
 fopen_utf8 ($filename)
 Opens a text file, detects the encoding, inteprets the BOM if present, attaches a stream filter to convert to UTF-8. More...
 
 fgetcsv_noBOM ($fp)
 
 tempdir ($dir=null, $prefix='tmp_', $mode=0700, $maxAttempts=1000)
 Creates a random unique temporary directory, with specified parameters, that does not already exist (like tempnam(), but for dirs). More...
 

Variables

 $image_types = array( "image/jpeg", "image/gif", "image/x-png", "image/pjpeg" )
 MIME types allowable for image uploads. More...
 
 $_redirectLogCallback = null
 
 $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 1783 of file functions.inc.

1784 {
1785  if (class_exists(FakoliEarlyExit))
1786  {
1787  throw new FakoliEarlyExit($msg);
1788  }
1789  else
1790  {
1791  session_write_close();
1792  die($msg);
1793  }
1794 }

◆ 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 1594 of file functions.inc.

1595 {
1596  trace ("QS: $qs PARAMS: $params", 3);
1597  if (strpos($qs, "?") === false && strpos($qs, "&") === false)
1598  {
1599  $qs .= "?$params";
1600  return $qs;
1601  }
1602 
1603  $qs .= "&$params";
1604  $qs = preg_replace("/&&+/", "&", $qs);
1605  if (strpos($qs, "?") === false) $qs = "?".$qs;
1606 
1607  return $qs;
1608 }
trace($msg, $lvl=3, $callStack=null)
Send output to the trace log.
Definition: functions.inc:1010

◆ 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 1885 of file functions.inc.

1886 {
1887  for($i = 1; $i < func_num_args(); ++$i)
1888  {
1889  unset($array[func_get_arg($i)]);
1890  }
1891 
1892  return $array;
1893 }

◆ 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 1752 of file functions.inc.

1753 {
1754  if ( !is_array( $input ) )
1755  {
1756  return null;
1757  }
1758 
1759  if ( empty( $input ) )
1760  {
1761  return $input;
1762  }
1763 
1764  $filteredKeys = array_filter( array_keys( $input ), $callback );
1765 
1766  if ( empty( $filteredKeys ) )
1767  {
1768  return array();
1769  }
1770 
1771  $input = array_intersect_key( array_flip( $filteredKeys ), $input );
1772 
1773  return $input;
1774 }

◆ 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 1582 of file functions.inc.

1583 {
1584  if (!$uri) $uri = $_SERVER['REQUEST_URI'];
1585  return preg_replace("/\\?.*$/", "", $uri);
1586 }

◆ 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 1278 of file functions.inc.

1279 {
1280  global $config;
1281 
1282  if (startsWith($url, "http://") || startsWith($url, "https://")) return $url;
1283 
1284 
1285  if (!startsWith($url, "/"))
1286  {
1287  $out = realpath($config['homedir']."/".$url);
1288  }
1289  else
1290  {
1291  $out = realpath($config['homedir'].$url);
1292  }
1293 
1294  $out = str_replace('\\', '/', $out);
1295 
1296  if (!startsWith($out, $config['homedir'])) return null;
1297  $out = str_replace($config['homedir'], "http://{$config['http_host']}", $out);
1298 
1299  trace("$url -> $out", 4);
1300  return $out;
1301 }
startsWith($text, $start)
Tests whether a string starts with a given sub-string.
Definition: functions.inc:1470

◆ checkGUID()

checkGUID (   $guid)

Checks whether the provided string is in a valid form for a GUID.

Parameters
string$guidthe GUID candidate
Returns
string the value of the parameter if it is a valid GUID

Definition at line 744 of file functions.inc.

745 {
746  if (preg_match('/^\{?[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}?$/i', $guid))
747  {
748  return $guid;
749  }
750 
751  die("Invalid Parameter");
752 }

◆ 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 }

◆ checkIdentifierList()

checkIdentifierList (   $p)

Security helper function.

Check that the given parameter is a comma-separated list of valid identifiers (alphanumeric, _ and digits only with no spaces). Empty string is valid

Definition at line 675 of file functions.inc.

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

◆ 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 }

◆ checkPlainGUID()

checkPlainGUID (   $guid)

Checkes whether the provided string is an undecorated GUID (i.e.

a string of 32 hex characters)

Parameters
string$guidthe GUID candidate
Returns
string the value of the parameter if it is a valid undecorated GUID

Definition at line 729 of file functions.inc.

730 {
731  if (preg_match('/^[A-F0-9]{32}$/i', $guid))
732  {
733  return $guid;
734  }
735 
736  die("Invalid Parameter");
737 }

◆ 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 == "admin") return true;
59  if (!$account) return false;
60 
61  if ($role != "" && $account->role == "") return false;
62 
63  $userRoles = explode(",", $account->role);
64  foreach($userRoles as $ur)
65  {
66  if ($ur == "admin") return true;
67  $expr = "/\\b{$ur}\\b/";
68  $allowed = (preg_match($expr, $role) > 0) ? true : false;
69  if ($allowed) break;
70  }
71 
72  return $allowed;
73 }

◆ checkValidDate()

checkValidDate (   $d)

Security helper function.

Check that the given parameter is a valid date.

Parameters
string$dthe date
Returns
string the value of the parameter if it is in a valid date format

Definition at line 695 of file functions.inc.

696 {
697  if (!$d) return $d;
698  $formats = array("Y-m-d", "Y/m/d", "m/d/Y");
699  foreach($formats as $format)
700  {
701  if ($d == date($format, strtotime($d))) return $d;
702  }
703 
704  die("Invalid Parameter");
705 }

◆ checkValidDateTime()

checkValidDateTime (   $d)

Security helper function.

Check that the given parameter is a valid date time.

Parameters
string$dthe date time
Returns
string the value of the parameter if it is in a valid date time format

Definition at line 712 of file functions.inc.

713 {
714  if (!$d) return $d;
715  $formats = array("Y-m-d H:i:s", "Y/m/d H:i:s", "m/d/Y H:i:s", "Y-m-d g:i:sa", "Y/m/d g:i:sa", "m/d/Y g:i:sa");
716  foreach($formats as $format)
717  {
718  if ($d == date($format, strtotime($d))) return $d;
719  }
720 
721  die("Invalid Parameter");
722 }

◆ 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 685 of file functions.inc.

686 {
687  return (filter_var($e, FILTER_VALIDATE_EMAIL)) ? $e : die("Invalid Parameter");
688 }

◆ 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 1399 of file functions.inc.

1400 {
1401  $name = preg_replace("/[\\s\\W]+/", "_", $name);
1402  $name = str_replace("&", "and", $name);
1403  return $name;
1404 }

◆ 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 762 of file functions.inc.

763 {
764 
765 $color = "#FFFFFF";
766 if ($count%2==0) $color = "#EEEEEE";
767 return $color;
768 }

◆ 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 2011 of file functions.inc.

2012 {
2013  $arr1 = explode(",", $a);
2014  $arr2 = explode(",", $b);
2015  return count(array_intersect($arr1, $arr2));
2016 }

◆ 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 779 of file functions.inc.

780 {
781  if (strlen($txt) > $max)
782  {
783  if (!$wholeWord)
784  {
785  $txt = substr($txt, 0, $max)."...";
786  }
787  else
788  {
789  $txt = substr($txt, 0, $max);
790  $pos = strrpos($txt, " ");
791  if ($pos)
792  {
793  while($pos && $txt[$pos - 1] == '.')
794  {
795  $pos--;
796  }
797  }
798  $txt = substr($txt, 0, $pos)."...";
799  }
800  }
801 
802  return $txt;
803 }

◆ 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 1925 of file functions.inc.

1926 {
1927  return mb_encode_mimeheader($text, "iso-8859-1", "Q");
1928 }

◆ 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 1481 of file functions.inc.

1482 {
1483  return (substr($text, -strlen($end)) == $end);
1484 }

◆ fgetcsv_noBOM()

fgetcsv_noBOM (   $fp)

Definition at line 2106 of file functions.inc.

2107 {
2108  $fields = fgetcsv($fp);
2109  if (is_array($fields))
2110  {
2111  $bom = pack('CCC', 0xEF, 0xBB, 0xBF);
2112  if (substr($fields[0], 0, 3) === $bom)
2113  {
2114  $fields[0] = substr($fields[0], 3);
2115  }
2116  }
2117  return $fields;
2118 }

◆ 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 839 of file functions.inc.

840 {
841  $text = preg_replace("/<br>/i", " ", $text);
842  $text = preg_replace("/<.*?>/", "", $text);
843  $pos = strpos($text, ". ");
844  return ($pos) ? substr($text, 0, $pos + 1) : $text;
845 }

◆ fopen_utf8()

fopen_utf8 (   $filename)

Opens a text file, detects the encoding, inteprets the BOM if present, attaches a stream filter to convert to UTF-8.

Thanks to the author of this article: http://www.practicalweb.co.uk/blog/2008/05/18/reading-a-unicode-excel-file-in-php/

Parameters
string$filenamethe file to be opened for reading

Definition at line 2082 of file functions.inc.

2082  {
2083  $encoding='';
2084  $handle = fopen($filename, 'r');
2085  $bom = fread($handle, 2);
2086  // fclose($handle);
2087  rewind($handle);
2088 
2089 
2090  if($bom === chr(0xff).chr(0xfe) || $bom === chr(0xfe).chr(0xff)){
2091  // UTF16 Byte Order Mark present
2092  $encoding = 'UTF-16';
2093  } else {
2094  $file_sample = fread($handle, 1000) . 'e'; //read first 1000 bytes
2095  // + e is a workaround for mb_string bug
2096  rewind($handle);
2097 
2098  $encoding = mb_detect_encoding($file_sample , 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
2099  }
2100  if ($encoding && $encoding != 'UTF-8'){
2101  stream_filter_append($handle, 'convert.iconv.'.$encoding.'/UTF-8');
2102  }
2103  return ($handle);
2104 }

◆ 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 1456 of file functions.inc.

1457 {
1458  if (preg_match("/<.*?>/", $text)) return $text;
1459  $text = str_replace("\n", "<br/>", $text);
1460 
1461  return $text;
1462 }

◆ 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 1555 of file functions.inc.

1556 {
1557  if(count($options) == 0) return;
1558 
1559  $values = explode(",", $items);
1560 
1561  foreach($values as $value)
1562  {
1563  if(array_key_exists($value, $options))
1564  {
1565  $list .= $options[$value] . ", ";
1566  }
1567  else
1568  $list .= $value . ", ";
1569  }
1570 
1571  if(strlen($list) > 0)
1572  $list = substr($list, 0, strlen($list) - 2);
1573 
1574  return $list;
1575 }

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

◆ 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 1962 of file functions.inc.

1963 {
1964  $trace = '';
1965  foreach (debug_backtrace() as $k => $v) {
1966  if ($k < $ignore) {
1967  continue;
1968  }
1969 
1970  array_walk($v['args'], function (&$item, $key) {
1971  $item = var_export($item, true);
1972  });
1973 
1974  $trace .= '#' . ($k - $ignore) . ' ' . $v['file'] . '(' . $v['line'] . '): ' . (isset($v['class']) ? $v['class'] . '->' : '') . $v['function'] . '(' . implode(', ', $v['args']) . ')' . "\n";
1975  }
1976 
1977  return $trace;
1978 }

◆ getCleanQueryString()

getCleanQueryString ( )

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

Definition at line 986 of file functions.inc.

987 {
988  $qs = $_SERVER['QUERY_STRING'];
989 
990  $params = array();
991 
992  foreach($_GET as $key => $value)
993  {
994  if ($key != "identifier" && $key != "section") $params[$key] = $value;
995  }
996 
997  return http_build_query($params);
998 }

◆ 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 1634 of file functions.inc.

1635 {
1636  global $__urlRewriteParams;
1637 
1638  $qs = "";
1639  $sep = "?";
1640 
1641  foreach($_GET as $name => $value)
1642  {
1643  if (array_key_exists($name, $__urlRewriteParams)) continue;
1644 
1645  if (is_array($value))
1646  {
1647  foreach($value as $key => $val)
1648  {
1649  $qs .= $sep.urlencode($name)."[".urlencode($key)."]=".urlencode($val);
1650  $sep = "&";
1651  }
1652  }
1653  else
1654  {
1655  $qs .= $sep.urlencode($name)."=".urlencode($value);
1656  $sep = "&";
1657  }
1658  }
1659 
1660  if ($includePOST)
1661  {
1662  foreach($_POST as $name => $value)
1663  {
1664  if (is_array($value))
1665  {
1666  foreach($value as $key => $val)
1667  {
1668  $qs .= $sep.urlencode($name)."[".urlencode($key)."]=".urlencode($val);
1669  $sep = "&";
1670  }
1671  }
1672  else
1673  {
1674  $qs .= $sep.urlencode($name)."=".urlencode($value);
1675  $sep = "&";
1676  }
1677  }
1678  }
1679 
1680  trace("Full Query String: $qs", 3);
1681  return $qs;
1682 }
$__urlRewriteParams
Definition: functions.inc:1610

◆ 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 1149 of file functions.inc.

1150 {
1151  global $_icons;
1152  global $auto_form_defaults;
1153 
1154  $ext = substr($file, strrpos($file, "."));
1155  $icon = $_icons[$ext];
1156  trace("getIcon($file) $ext $icon", 3);
1157 
1158  if (!isset($icon))
1159  {
1160  $icon = $_icons["default"];
1161  }
1162 
1163  return $auto_form_defaults["componentPath"].$icon;
1164 }
$_icons
Definition: functions.inc:1138

◆ getMIMEType()

getMIMEType (   $filename)
Parameters
String$filenameDeprecated

Definition at line 1802 of file functions.inc.

1803 {
1804  $mime_types = array(
1805 
1806  'txt' => 'text/plain',
1807  'htm' => 'text/html',
1808  'html' => 'text/html',
1809  'css' => 'text/css',
1810  'js' => 'application/javascript',
1811  'json' => 'application/json',
1812  'xml' => 'application/xml',
1813  'swf' => 'application/x-shockwave-flash',
1814  'flv' => 'video/x-flv',
1815 
1816  // images
1817  'png' => 'image/png',
1818  'jpe' => 'image/jpeg',
1819  'jpeg' => 'image/jpeg',
1820  'jpg' => 'image/jpeg',
1821  'gif' => 'image/gif',
1822  'bmp' => 'image/bmp',
1823  'ico' => 'image/vnd.microsoft.icon',
1824  'tiff' => 'image/tiff',
1825  'tif' => 'image/tiff',
1826  'svg' => 'image/svg+xml',
1827  'svgz' => 'image/svg+xml',
1828 
1829  // archives
1830  'zip' => 'application/zip',
1831  'rar' => 'application/x-rar-compressed',
1832  'exe' => 'application/x-msdownload',
1833  'msi' => 'application/x-msdownload',
1834  'cab' => 'application/vnd.ms-cab-compressed',
1835 
1836  // audio/video
1837  'mp3' => 'audio/mpeg',
1838  'm4a' => 'video/mp4',
1839  'qt' => 'video/quicktime',
1840  'mov' => 'video/quicktime',
1841 
1842  // adobe
1843  'pdf' => 'application/pdf',
1844  'psd' => 'image/vnd.adobe.photoshop',
1845  'ai' => 'application/postscript',
1846  'eps' => 'application/postscript',
1847  'ps' => 'application/postscript',
1848 
1849  // ms office
1850  'doc' => 'application/msword',
1851  'rtf' => 'application/rtf',
1852  'xls' => 'application/vnd.ms-excel',
1853  'ppt' => 'application/vnd.ms-powerpoint',
1854 
1855  // open office
1856  'odt' => 'application/vnd.oasis.opendocument.text',
1857  'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
1858  );
1859 
1860  $ext = strtolower(array_pop(explode('.',$filename)));
1861 
1862  if (array_key_exists($ext, $mime_types))
1863  {
1864  return $mime_types[$ext];
1865  }
1866  elseif (function_exists('finfo_open'))
1867  {
1868  $finfo = finfo_open(FILEINFO_MIME);
1869  $mimetype = finfo_file($finfo, $filename);
1870  finfo_close($finfo);
1871  return $mimetype;
1872  }
1873  else
1874  {
1875  // Prevent other file types (such as source code or configuration files) from being served
1876  die("");
1877  }
1878 }

◆ 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 1192 of file functions.inc.

1193 {
1194  $url = canonicalizeURL($url);
1195  trace("Retrieving $url", 3);
1196  $ch = curl_init("$url");
1197  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1198  curl_setopt($ch, CURLOPT_HEADER, 0);
1199  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1200 
1201  if ($username)
1202  {
1203  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
1204  curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
1205  }
1206 
1207  $html = curl_exec($ch);
1208 
1209  if ($html === FALSE) throw new Exception(curl_error($ch));
1210 
1211  curl_close($ch);
1212 
1213  return $html;
1214 }
canonicalizeURL($url)
Takes a URL and converts relative URLs to absolute URLs for the current site.
Definition: functions.inc:1278

◆ 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 1359 of file functions.inc.

1360 {
1361  $ch = curl_init();
1362  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1363  curl_setopt($ch, CURLOPT_HEADER, 1);
1364  curl_setopt($ch, CURLOPT_NOBODY, 1);
1365  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1366 
1367  $html = curl_exec($ch);
1368 
1369  curl_close($ch);
1370 
1371  return $html;
1372 }

◆ 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 1088 of file functions.inc.

1089 {
1090  if (!$size) return "";
1091 
1092  $result = "";
1093  if ($size > 1073741824)
1094  {
1095  $result = sprintf("%.{$decimal_places}fGB", ($size / 1073741824));
1096  }
1097  else if ($size > 1048576)
1098  {
1099  $result = sprintf("%.{$decimal_places}fMB", ($size / 1048576));
1100  }
1101  else if ($size > 1024)
1102  {
1103  $result = intval($size / 1024)."KB";
1104  }
1105  else
1106  {
1107  $result = "$size bytes";
1108  }
1109 
1110  return $result;
1111 }

◆ GUID()

GUID ( )

Generates a version 4 GUID.

Where random_int is available (PHP > 7.0) it is used to ensure cryptographically secure random numbers.

Returns
string

Definition at line 1935 of file functions.inc.

1936 {
1937  if (function_exists('random_int') === true)
1938  {
1939  return '{'.sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', random_int(0, 65535), random_int(0, 65535), random_int(0, 65535), random_int(16384, 20479), random_int(32768, 49151), random_int(0, 65535), random_int(0, 65535), random_int(0, 65535)).'}';
1940  }
1941 
1942  if (function_exists('com_create_guid') === true)
1943  {
1944  return trim(com_create_guid(), '{}');
1945  }
1946 
1947  return '{'.sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)).'}';
1948 }

◆ 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:847

◆ 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 1173 of file functions.inc.

1174 {
1175  $ch = curl_init("http://$host/$file");
1176  curl_setopt($ch, CURLOPT_HEADER, 0);
1177  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1178  $html = curl_exec($ch);
1179  curl_close($ch);
1180 
1181  $html = preg_replace("/(src|href)(=['\"])\//", "$1$2http://$host/", $html);
1182  echo $html;
1183 }

◆ 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 1221 of file functions.inc.

1222 {
1223  $qs = array();
1224  foreach($params as $key => $value)
1225  {
1226  $qs[] = "$key=".urlencode($value);
1227  }
1228 
1229  $qs = implode("&", $qs);
1230 
1231  $api = "{$url}?{$qs}";
1232  trace($api);
1233  $response = getRemote($api);
1234  return json_decode($response);
1235 }
getRemote($url, $username="", $password="")
Retrieve the contents of the remote file at the given URL.
Definition: functions.inc:1192

◆ 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 1985 of file functions.inc.

1986 {
1987  $len = strlen($num);
1988  for ($i = $len-1; $i >= 0; $i--)
1989  {
1990  $ord = ord($num[$i]);
1991  if (($len - 1) & $i)
1992  {
1993  $sum += $ord;
1994  }
1995  else
1996  {
1997  $sum += $ord / 5 + (2 * $ord) % 10;
1998  }
1999  }
2000  return $sum % 10 == 0;
2001 }

◆ 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 1735 of file functions.inc.

1736 {
1737  $str = "";
1738  for($i = 0; $i < $len; ++$i)
1739  {
1740  $str .= chr(ord('a') + rand(0, 25));
1741  }
1742 
1743  return $str;
1744 }

◆ 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 1539 of file functions.inc.

1540 {
1541  if (!startsWith($uri, "http://")) $uri = "http://$uri";
1542  return $uri;
1543 }

◆ 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 888 of file functions.inc.

889 {
890  echo "<option value='$value'";
891  if ($sel === $value)
892  {
893  echo " selected";
894  }
895  echo ">$text</option>";
896 }

◆ 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 1503 of file functions.inc.

1504 {
1505  $suffix = "";
1506  if (is_numeric($n))
1507  {
1508  $n = trim($n);
1509 
1510  $lastTwo = substr($n, -2, 2);
1511  $lastOne = substr($n, -1, 1);
1512 
1513  if ($lastTwo == "11" || $lastTwo == "12" || $lastTwo == "13") $suffix = "th";
1514  else
1515  {
1516  switch($lastOne)
1517  {
1518  case "1": $suffix = "st"; break;
1519  case "2": $suffix = "nd"; break;
1520  case "3": $suffix = "rd"; break;
1521  default: $suffix = "th";
1522  }
1523  }
1524  }
1525  else return $n;
1526 
1527  // JDG 2/10/12 - fix was not returning value if $sup false
1528  if ($sup)
1529  return "$n<sup>$suffix</sup>";
1530  else
1531  return "$n$suffix";
1532 }

◆ 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 865 of file functions.inc.

866 {
867  $len = strlen($param);
868  $values = array();
869 
870  foreach($collection as $field => $value)
871  {
872  if (!strncmp($field, $param, $len))
873  {
874  $values[] = $value;
875  }
876  }
877 
878  return $values;
879 }

◆ plainGUID()

plainGUID ( )

Generates a version 4 GUID with no punctutation.

Returns
string

Definition at line 1954 of file functions.inc.

1955 {
1956  return str_replace(array("{", "}", "-"), array("", "", ""), GUID());
1957 }
GUID()
Generates a version 4 GUID.
Definition: functions.inc:1935

◆ 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 1428 of file functions.inc.

1429 {
1430  if ($count == 1) return $text;
1431 
1432  $c = $text;
1433 
1434  if (preg_match("/[^aeiouAEIOU]y$/", $c))
1435  {
1436  $c = substr($c, 0, -1)."ies";
1437  }
1438  else if (preg_match("/(?:ss|[^aeiou]o|x|s|ch)$/", $c))
1439  {
1440  $c .= "es";
1441  }
1442  else
1443  {
1444  $c .= "s";
1445  }
1446 
1447  return $c;
1448 }

◆ 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 1325 of file functions.inc.

1326 {
1327  $ch = curl_init();
1328  curl_setopt($ch, CURLOPT_URL, $url);
1329  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1330  curl_setopt($ch, CURLOPT_HEADER, 0);
1331  curl_setopt($ch, CURLOPT_POST, 1);
1332  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
1333  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
1334  $result = trim(curl_exec($ch));
1335  curl_close($ch);
1336  return $result;
1337 }

◆ postRemoteXML()

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

Definition at line 1339 of file functions.inc.

1340 {
1341  $ch = curl_init($url);
1342  curl_setopt($ch, CURLOPT_MUTE, 1);
1343  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
1344  curl_setopt($ch, CURLOPT_POST, 1);
1345  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
1346  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
1347  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1348  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
1349  $result = trim(curl_exec($ch));
1350  curl_close($ch);
1351  return $result;
1352 }

◆ 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 1413 of file functions.inc.

1414 {
1415  $name = preg_replace("/([a-z])([A-Z0-9])/", "$1 $2", $name);
1416  $name = str_replace("_", " ", $name);
1417  $name = ucwords($name);
1418 
1419  return $name;
1420 }

◆ prettyPrintJSON()

prettyPrintJSON (   $json)

Format the JSON in the supplied string to be more human-readable.

Parameters
string$jsonthe JSON to pretty-print

Definition at line 1723 of file functions.inc.

1724 {
1725  return json_encode(json_decode($json), JSON_PRETTY_PRINT);
1726 }

◆ 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 2023 of file functions.inc.

2024 {
2025  if ($return)
2026  {
2027  ob_start();
2028  }
2029 
2030  $includes = get_included_files();
2031  if ($html) echo "<ul>\n";
2032  foreach($includes as $include)
2033  {
2034  if ($html)
2035  {
2036  echo "<li>$include</li>";
2037  }
2038  else
2039  {
2040  echo $include."\n";
2041  }
2042  }
2043  if ($html) echo "</ul>";
2044 
2045  if ($return)
2046  {
2047  $out = ob_get_contents();
2048  ob_end_clean();
2049  return $out;
2050  }
2051 }

◆ 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
string$pagethe page to redirect to

Definition at line 930 of file functions.inc.

931 {
932  global $_redirectLogCallback;
933  global $config;
934 
935  if ($config['prettyURLs'] === false)
936  {
937  $page = preg_replace("/^\\/?([\\w\\d_]+?)\\?/", "/page.php?identifier=$1&", $page);
938  $page = preg_replace("/^\\/?([\\w\\d_]+)$/", "/page.php?identifier=$1", $page);
939  }
940 
941  trace("redirect:: page is $page", 3);
942  $server = $config['http_host'];
943  if (!$server) $server="localhost:8080";
944 
945  //AJG: 3/9/11 - maintain current protocol by default
946 
947  $https = $_SERVER['HTTPS'];
948  if ($https == "off") $https = false;
949  if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
950  {
951  $https = true;
952  }
953 
954  $protocol = $https ? "https" : "http";
955 
956  // JDG 9/27/10 - handle https
957  if (!strncmp($page, "http://", 7) OR (!strncmp($page, "https://", 8)))
958  {
959  $location = $page;
960  }
961  else if ($page[0] == '/')
962  {
963  $location = "$protocol://$server$page";
964  }
965 // else if (preg_match( "/^[\\w\\d_\\-]+$/", $page))
966 // {
967 // $location = "http://$server/$page";
968 // }
969  else
970  {
971  $directory = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['REQUEST_URI']));
972  if ($directory == "/") $directory = "";
973  $location = "$protocol://".$server.$directory."/".$page;
974  }
975 
976  header("Location: $location");
978  session_write_close();
979  exit;
980 }
$_redirectLogCallback
Definition: functions.inc:918

◆ registerRedirectLogCallback()

registerRedirectLogCallback (   $callback)

Definition at line 920 of file functions.inc.

921 {
922  global $_redirectLogCallback;
923  $_redirectLogCallback = $callback;
924 }

◆ registerURLRewriteParameters()

registerURLRewriteParameters ( )

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

Definition at line 1616 of file functions.inc.

1617 {
1618  global $__urlRewriteParams;
1619 
1620  for($i = 0; $i < func_num_args(); ++$i)
1621  {
1622  $__urlRewriteParams[func_get_arg($i)] = true;
1623  }
1624 }

◆ replaceValues()

replaceValues (   $substitutions,
  $target 
)

Given an array of pairs of old and new values, replace all instances of old values with new values in the target string.

Parameters
array$substitutionsarray of old and new values
string$targetthe target string to update
Returns
string the updated string

Definition at line 2060 of file functions.inc.

2061 {
2062  foreach($substitutions as $old => $new)
2063  {
2064  $expr = "/\\b{$old}\\b/";
2065  trace("{$expr} => $new", 3);
2066  $target = preg_replace($expr, $new, $target);
2067  trace($target, 3);
2068  }
2069 
2070  return $target;
2071 }

◆ roundFormat()

roundFormat (   $num,
  $abbrev = false 
)

Definition at line 1113 of file functions.inc.

1114 {
1115  if (!$num) return "";
1116 
1117  $result = "";
1118  if ($abbrev == false) {
1119  if ($num >= 1000000000) {
1120  $result = sprintf("%.1f billion", ($num / 1000000000));
1121  } elseif ($num >= 1000000) {
1122  $result = sprintf("%.1f million", ($num / 1000000));;
1123  } elseif ($num >= 1000) {
1124  $result = sprintf("%.0f,000", ($num / 1000));;
1125  }
1126  } else {
1127  if ($num >= 1000000000) {
1128  $result = sprintf("%.1f bn", ($num / 1000000000));
1129  } elseif ($num >= 1000000) {
1130  $result = sprintf("%.1f m", ($num / 1000000));;
1131  } elseif ($num >= 1000) {
1132  $result = sprintf("%.0f,000", ($num / 1000));
1133  }
1134  }
1135  return $result;
1136 }

◆ rteSafe()

rteSafe (   $strText)
Parameters
unknown_type$strTextDeprecated

Definition at line 811 of file functions.inc.

811  {
812  //returns safe code for preloading in the RTE
813  $tmpString = $strText;
814 
815  //convert all types of single quotes
816  $tmpString = str_replace(chr(145), chr(39), $tmpString);
817  $tmpString = str_replace(chr(146), chr(39), $tmpString);
818  $tmpString = str_replace("'", "&#39;", $tmpString);
819 
820  //convert all types of double quotes
821  $tmpString = str_replace(chr(147), chr(34), $tmpString);
822  $tmpString = str_replace(chr(148), chr(34), $tmpString);
823 // $tmpString = str_replace("\"", "\"", $tmpString);
824 
825  //replace carriage returns & line feeds
826  $tmpString = str_replace(chr(10), " ", $tmpString);
827  $tmpString = str_replace(chr(13), " ", $tmpString);
828 
829  return $tmpString;
830 }

◆ 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 1309 of file functions.inc.

1310 {
1311  $path = str_replace("/", DIRECTORY_SEPARATOR, $path);
1312  $path = str_replace("\\", DIRECTORY_SEPARATOR, $path);
1313  $path = str_replace("..".DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
1314  $path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
1315  return $path;
1316 }

◆ 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 1246 of file functions.inc.

1247 {
1248  trace("Downloading $url to $saveAs", 3);
1249 
1250  $ch = curl_init ($url);
1251  curl_setopt($ch, CURLOPT_HEADER, 0);
1252  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1253  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1254  curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
1255  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1256 
1257  $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
1258  $bytes = curl_exec($ch);
1259  curl_close ($ch);
1260 
1261  trace(count($bytes)." bytes recieved", 3);
1262 
1263  if(file_exists($saveAs))
1264  {
1265  unlink($saveAs);
1266  }
1267 
1268  file_put_contents($saveAs, $bytes);
1269 
1270  return $contentType;
1271 }

◆ 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 1470 of file functions.inc.

1471 {
1472  return (strncmp($text, $start, strlen($start)) == 0);
1473 }

◆ 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 906 of file functions.inc.

907 {
908  $opt = "<option value='$value'";
909  if ($sel == $value)
910  {
911  $opt .= " selected";
912  }
913  $opt .= ">$text</option>";
914 
915  return $opt;
916 }

◆ stripHTML()

stripHTML (   $text)

Definition at line 847 of file functions.inc.

848 {
849  /*$text = preg_replace("/<.*?>/", "", $text);*/
850  $text = strip_tags($text);
851 
852  // JDG 5/19/2011 - remove &ndash, &nbsp;
853  $text = html_entity_decode($text);
854  $text = trim($text);
855  return $text;
856 }

◆ 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 1491 of file functions.inc.

1492 {
1493  return preg_replace("/<.*?>/", "", $text);
1494 }

◆ tempdir()

tempdir (   $dir = null,
  $prefix = 'tmp_',
  $mode = 0700,
  $maxAttempts = 1000 
)

Creates a random unique temporary directory, with specified parameters, that does not already exist (like tempnam(), but for dirs).

Created dir will begin with the specified prefix, followed by random numbers.

string|null $dir Base directory under which to create temp dir. If null, the default system temp dir (sys_get_temp_dir()) will be used. string $prefix String with which to prefix created dirs. int $mode Octal file permission mask for the newly-created dir. Should begin with a 0. int $maxAttempts Maximum attempts before giving up (to prevent endless loops). string|bool Full path to newly-created dir, or false on failure.

Definition at line 2139 of file functions.inc.

2140 {
2141  /* Use the system temp dir by default. */
2142  if (is_null($dir))
2143  {
2144  $dir = sys_get_temp_dir();
2145  }
2146 
2147  /* Trim trailing slashes from $dir. */
2148  $dir = rtrim($dir, DIRECTORY_SEPARATOR);
2149 
2150  /* If we don't have permission to create a directory, fail, otherwise we will
2151  * be stuck in an endless loop.
2152  */
2153  if (!is_dir($dir) || !is_writable($dir))
2154  {
2155  return false;
2156  }
2157 
2158  /* Make sure characters in prefix are safe. */
2159  if (strpbrk($prefix, '\\/:*?"<>|') !== false)
2160  {
2161  return false;
2162  }
2163 
2164  /* Attempt to create a random directory until it works. Abort if we reach
2165  * $maxAttempts. Something screwy could be happening with the filesystem
2166  * and our loop could otherwise become endless.
2167  */
2168  $attempts = 0;
2169  do
2170  {
2171  $path = sprintf('%s%s%s%s', $dir, DIRECTORY_SEPARATOR, $prefix, mt_rand(100000, mt_getrandmax()));
2172  } while (
2173  !mkdir($path, $mode) &&
2174  $attempts++ < $maxAttempts
2175  );
2176 
2177  return $path;
2178 }

◆ 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 1694 of file functions.inc.

1695 {
1696  $js_arr = "[";
1697  $first = true;
1698 
1699  if(count($items) == 0)
1700  return "";
1701 
1702  if(is_object($items[0]) && !$field)
1703  {
1704  $field = $items[0]->getPrimaryKey();
1705  }
1706 
1707  foreach($items as $item)
1708  {
1709  if (!$first) $js_arr .=", ";
1710  $js_arr .= (is_object($item) && $field) ? $item->$field : $item;
1711  $first = false;
1712  }
1713 
1714  $js_arr .= "]";
1715 
1716  return $js_arr;
1717 }

◆ trace()

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

Send output to the trace log.

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

Definition at line 1010 of file functions.inc.

1011 {
1012  global $config;
1013  global $traceLevels;
1014 
1015  if ($lvl <= $config["trace_level"])
1016  {
1017  switch($config["trace_detail"])
1018  {
1019  case TraceDetailFull:
1020 
1021  $callStack = $callStack ? $callStack : debug_backtrace();
1022  if (count($callStack) > 1)
1023  {
1024  $callingFn = $callStack[1];
1025  }
1026  else
1027  {
1028  $callingFn = $callStack[0];
1029  }
1030  $file = str_replace($config["homedir"], "", $callingFn["file"]);
1031  $ref = $file.":".$callingFn["line"]." ";
1032  if ($callingFn["class"])
1033  {
1034  $ref .= $callingFn["class"].$callingFn["type"];
1035  }
1036 
1037  $ref .= $callingFn["function"]."(): ";
1038 
1039  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s")." : ".$_SERVER['REQUEST_URI']." : ".$ref." ".$msg."\r\n", 3, $config["trace_path"]);
1040  break;
1041 
1042  case TraceDetailHigh:
1043 
1044  $callStack = $callStack ? $callStack : debug_backtrace();
1045 
1046  if (count($callStack) > 1)
1047  {
1048  $callingFn = $callStack[1];
1049  }
1050  else
1051  {
1052  $callingFn = $callStack[0];
1053  }
1054 
1055  $file = str_replace($config["homedir"], "", $callingFn["file"]);
1056  $ref = $file.":".$callingFn["line"]." ";
1057  if ($callingFn["class"])
1058  {
1059  $ref .= $callingFn["class"].$callingFn["type"];
1060  }
1061 
1062  $ref .= $callingFn["function"]."(): ";
1063 
1064  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s")." : ".$ref." ".$msg."\r\n", 3, $config["trace_path"]);
1065  break;
1066 
1067 
1068  case TraceDetailMedium:
1069  error_log("[".$traceLevels[$lvl]."] ".date("Y-m-d H:i:s : ").$msg."\r\n", 3, $config["trace_path"]);
1070  break;
1071 
1072  case TraceDetailNormal:
1073  default:
1074 
1075  error_log("[".$traceLevels[$lvl]."] ".$msg."\r\n", 3, $config["trace_path"]);
1076  break;
1077  }
1078  }
1079 }
$traceLevels
Definition: functions.inc:1000

◆ 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 1381 of file functions.inc.

1382 {
1383  $text = str_replace(" ", "%20", $url);
1384  $text = str_replace("/", " ", $text);
1385  $text = wordwrap($text, $width, "/<br>", true);
1386  $text = str_replace(" ", "/", $text);
1387 
1388  return $text;
1389 }

◆ 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 1903 of file functions.inc.

1904 {
1905  if (defined(ENT_XML1)) return htmlentities($value, ENT_XML1);
1906 
1907  $result = '';
1908  foreach (str_split(utf8_decode(htmlspecialchars($string))) as $char)
1909  {
1910  $num = ord($char);
1911  if ($num > 127) {
1912  $result .= '&#' . $num . ';';
1913  } else {
1914  $result .= $char;
1915  }
1916  }
1917  return $result;
1918 }

Variable Documentation

◆ $__urlRewriteParams

$__urlRewriteParams = array()

Definition at line 1610 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 1138 of file functions.inc.

◆ $_redirectLogCallback

$_redirectLogCallback = null

Definition at line 918 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 1000 of file functions.inc.