Source for file utils.php

Documentation is available at utils.php

  1. <?php
  2. /* ******************************************************************** */
  3. /* CATALYST PHP Source Code */
  4. /* -------------------------------------------------------------------- */
  5. /* This program is free software; you can redistribute it and/or modify */
  6. /* it under the terms of the GNU General Public License as published by */
  7. /* the Free Software Foundation; either version 2 of the License, or */
  8. /* (at your option) any later version. */
  9. /* */
  10. /* This program is distributed in the hope that it will be useful, */
  11. /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
  12. /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
  13. /* GNU General Public License for more details. */
  14. /* */
  15. /* You should have received a copy of the GNU General Public License */
  16. /* along with this program; if not, write to: */
  17. /* The Free Software Foundation, Inc., 59 Temple Place, Suite 330, */
  18. /* Boston, MA 02111-1307 USA */
  19. /* -------------------------------------------------------------------- */
  20. /* */
  21. /* Filename: utils.php */
  22. /* Author: Paul Waite */
  23. /* Description: Various general utility routines. */
  24. /* */
  25. /* ******************************************************************** */
  26. /** @package utils *//**
  27. * Insert vertical space in table
  28. * Insert some vertical whitespace into a table.
  29. * @param integer $height Whitespace height in pixels
  30. * @param integer $cols No. of columns in the target table
  31. * @return string HTML for a row of the given height
  32. */
  33. function vspace($height, $cols=1) {
  34. echo "<tr><td colspan=\"$cols\" height=\"$h\"></td></tr>";
  35. } // vspace
  36. // ----------------------------------------------------------------------
  37.  
  38. /**
  39. * Send a message to the system logfile
  40. * Send message to the syslog, prefixed with APP_NAME nicely. Saves
  41. * having to prefix it each time.
  42. * @param string $msg Message to enter into the system log
  43. * @param string $prefix Prefix to the message
  44. */
  45. function log_sys($msg, $prefix="") {
  46. if ($prefix == "") {
  47. if (defined("APP_NAME")) {
  48. $prefix = APP_NAME;
  49. }
  50. else {
  51. $prefix = "AXYL";
  52. }
  53. }
  54. error_log("$prefix: $msg", 0);
  55. } // log_sys
  56. // ----------------------------------------------------------------------
  57.  
  58. /**
  59. * Exit the application with error message
  60. * Echo the message and leave. Intended to handle 'emergencies'.
  61. * @param string $heading Message heading, subject
  62. * @param string $msg Message in detail
  63. */
  64. function error_exit($heading, $msg="") {
  65. global $RESPONSE;
  66.  
  67. switch ($RESPONSE->browser_type) {
  68. case BROWSER_TYPE_XHTML:
  69. case BROWSER_TYPE_HTML:
  70. $RESPONSE->delete_cookie();
  71. echo "<h3>$heading</h3><strong>$msg</strong>";
  72. break;
  73.  
  74. case BROWSER_TYPE_XHTMLMP:
  75. case BROWSER_TYPE_WML:
  76. case BROWSER_TYPE_WMLUP:
  77. include_once("wml-defs.php");
  78. $card = new WMLcard("error_exit", "System Error");
  79. $card->insert(
  80. "<p>" .
  81. "$heading<br/>" .
  82. "$msg" .
  83. "</p>"
  84. );
  85. // Create the card deck and output it..
  86. $deck = new WMLdeck($card);
  87. echo $deck->wml();
  88. break;
  89.  
  90. default:
  91. $RESPONSE->delete_cookie();
  92. echo "<h3>$heading</h3><strong>$msg</strong>";
  93. } // switch
  94. exit;
  95. } // error_exit
  96. // ----------------------------------------------------------------------
  97.  
  98. /**
  99. * Return an HTTP error message
  100. * Returns a formatted HTTP Error
  101. * @param integer $code HTTP error code
  102. * @return string The formatted HTTP error code
  103. */
  104. function HTTPError($code) {
  105. $s = "";
  106. switch ($code) {
  107. case 401:
  108. $s = "Unauthorised.";
  109. break;
  110. case 403:
  111. $s = "Forbidden.";
  112. break;
  113. case 404:
  114. $s = "Not Found.";
  115. break;
  116. case 405:
  117. $s = "Method Not Allowed.";
  118. break;
  119. case 406:
  120. $s = "Not Acceptable.";
  121. break;
  122. case 500:
  123. $s = "Infernal server error.";
  124. break;
  125. case 501:
  126. $s = "Not Implemented.";
  127. break;
  128. default:
  129. $s = "Unknown Server Error.";
  130. break;
  131. } // switch
  132.  
  133. return "HTTP/1.1 $code: $s";
  134. } // HTTPError
  135. // ----------------------------------------------------------------------
  136.  
  137. /**
  138. * Exit with HTTP error code
  139. * Send a simple error code and then die.
  140. * @param integer $code HTTP error code
  141. */
  142. function errorcode_exit($code) {
  143. error_exit( HTTPError($code) );
  144. } // errorcode_exit
  145. // -----------------------------------------------------
  146.  
  147. /**
  148. * Return a value which may be defaulted
  149. * Returns the value of the variable, if it is valid, otherwise
  150. * returns the specified default value.
  151. * @param mixed $val The value of interest
  152. * @param mixed $default The default value to apply if $val is empty
  153. * @return mixed Either the value, or the default
  154. */
  155. function defaulted($val, $default) {
  156. if (empty($val) || $val == "") return $default;
  157. else return $val;
  158. } // defaulted
  159. // ----------------------------------------------------------------------
  160.  
  161. /**
  162. * Format a string (dotted) form of an IP address. We make sure we have
  163. * the full dotted quad, and if we have to pad it with zeroes, then we
  164. * add the network spec (/24, /16 etc.) as well. If the given IP already
  165. * has a netmask, then we don't change it, and assume the IP is already
  166. * correctly formatted by someone who knows what they are doing!
  167. *
  168. * @param string $pi IP address in string dotted format
  169. * @return string The padded IP address
  170. */
  171. function ip_format($ip) {
  172. // Pad shorthand addresses with zeroes..
  173. $myipbits = explode("/", $ip);
  174. $myip = trim($myipbits[0]);
  175. $mynetmask = trim($myipbits[1]);
  176.  
  177. $octets = explode(".", $myip);
  178. if (count($octets < 4)) {
  179. while ( count($octets) < 4) {
  180. $octets[] = "0";
  181. }
  182. $myip = implode(".", $octets);
  183. }
  184.  
  185. // If not defined already, find the netmask bits,
  186. // by scanning for zeroes from the end..
  187. if ($mynetmask == "") {
  188. $mynetmask = 32;
  189. for ($ix=3; $ix >= 0; $ix--) {
  190. if ($octets[$ix] == 0) $mynetmask -= 8;
  191. else break;
  192. }
  193. }
  194.  
  195. // Append netmask if a network..
  196. if ($mynetmask < 32) {
  197. $myip .= "/$mynetmask";
  198. }
  199. return $myip;
  200. } // ip_format
  201. // -----------------------------------------------------
  202.  
  203. /**
  204. * Check string to see if it is in IPv4 format. This is
  205. * pretty simplistic. It returns true if the string $ip
  206. * is of the form 'n.n.n.n'.
  207. * @return bool True if it is in IPv4 format
  208. */
  209. function is_ipaddress($ip) {
  210. $isip = false;
  211. $myip = explode(".", $ip);
  212. if (count($myip) == 4) {
  213. // A dotted quad is close enough..
  214. $isip = true;
  215. }
  216. return $isip;
  217. } // is_ipaddress
  218. // -----------------------------------------------------
  219.  
  220. /** This function is a utility to allow composite fragments of javascript
  221. * to be replaced or concatenated together to form a new string of
  222. * javascript. This is designed to be used for building short javascript
  223. * statement strings to go in things such as onclick events for form
  224. * elements etc.
  225. */
  226. /** Add script by replacing current content (default) */
  227. ("SCRIPT_REPLACE", 0);
  228. /** Add script by keeping current content and appending to the end */
  229. ("SCRIPT_APPEND", 1);
  230. /** Add script by keeping current content and prefixing to the beginning */
  231. ("SCRIPT_PREFIX", 2);
  232.  
  233. function inline_script($newscript, $oldscript="", $mode=SCRIPT_REPLACE) {
  234. $res = "";
  235. switch ($mode) {
  236. case SCRIPT_APPEND:
  237. if ($oldscript != "") {
  238. if (substr($oldscript, -1) != ";") {
  239. $oldscript .= ";";
  240. }
  241. }
  242. $res = $oldscript . $newscript;
  243. break;
  244. case SCRIPT_PREFIX:
  245. if ($newscript != "") {
  246. if (substr($newscript, -1) != ";") {
  247. $newscript .= ";";
  248. }
  249. }
  250. $res = $newscript . $oldscript;
  251. break;
  252. default:
  253. $res = $newscript;
  254. break;
  255. } // switch
  256.  
  257. // Return new inline script
  258. return $res;
  259. } // inline_script
  260. // -----------------------------------------------------
  261.  
  262. /**
  263. * Resolve a foreign key value
  264. * Resolve a simple single-level foreign key. The variable
  265. * 'display_fields' can contain multiple fields separated
  266. * by the "|" char. A literal is prefixed by "#".
  267. * @param mixed $fkey The value of the foreign key field to look up
  268. * @param string $tbl The name of the table to look up in
  269. * @param string $key_field Name of the key field to look up
  270. * @param string $display_fields Name of the display fields to get data from
  271. * @return mixed The returned value
  272. */
  273. function resolveFK($fkey, $tbl, $key_field, $display_fields) {
  274. debug_trace("utils.php: resolveFK()");
  275. $res = "";
  276. $q = dbrecordset("SELECT * FROM $tbl WHERE $key_field = '$fkey'");
  277. if ($q->hasdata) {
  278. $dispflds = explode("|",$display_fields);
  279. for ($i=0; $i < count($dispflds); $i++) {
  280. if ($i > 0) $res .= " ";
  281. $fld = $dispflds[$i];
  282. if (substr($fld,0,1) == "#") $res .= substr($fld,1);
  283. else $res .= $q->field($fld);
  284. }
  285. }
  286. debug_trace();
  287. return $res;
  288. } // resolveFK
  289. // -----------------------------------------------------
  290.  
  291. /**
  292. * DEPRECATED: This global utility function is now deprecated since the
  293. * code is non-database-independent, and was written solely to support
  294. * Postgresql sequences. Instead, please update your code to use the new
  295. * 'get_next_sequencevalue()' global function, or 'next_sequencevalue()'
  296. * methods on the 'dbupdate' and 'dbinsert' classes, or else use the new
  297. * 'dbseq' class itself.
  298. * Return next sequence value - get the next value of the given sequence
  299. * @param string $seq The name of the sequence to get the next value of
  300. * @return integer The next sequence value
  301. */
  302. function next_sequencevalue($seq) {
  303. debug_trace("utils.php: next_sequencevalue()");
  304. $res = FALSE;
  305. $qseq = new dbrows("SELECT NEXTVAL('$seq')" );
  306. if ($qseq->valid) {
  307. $r = $qseq->get_current();
  308. $qseq->tidyup();
  309. $res = $r[0];
  310. }
  311. debug_trace();
  312. return $res;
  313. } // next_sequencevalue
  314. // -----------------------------------------------------
  315.  
  316. /**
  317. * Detect a URL with the "xxx://" protocol prefix. Returns
  318. * true if it does, else false.
  319. * @param string $url URL to detect protocol prefix
  320. * @return boolean True if it is a prefixed URL
  321. */
  322. function protocol_prefixed($url){
  323. return (strpos($url, "://") !== false);
  324. } // protocol_prefixed
  325. // -----------------------------------------------------
  326.  
  327. /**
  328. * Strip off any xxxx:// protocol prefix from a URL. Usually
  329. * in Axyl, this is "http://", hence the name of this function.
  330. * @param string $url URL to strip of protocol prefix
  331. * @return string URL stripped of protocol prefix.
  332. */
  333. function strip_http_prefix($url){
  334. $urlbits = explode("://", $url);
  335. return (count($urlbits) == 2) ? $urlbits[1] : $url;
  336. } // strip_http_prefix
  337. // -----------------------------------------------------
  338.  
  339. /**
  340. * Make sure there is an http:// on a URL. If already
  341. * present then string is returned untouched.
  342. * @param string $url URL to add protocol prefix to
  343. * @param string $ssl If true then add "https", else "http"
  344. * @return string The URL prefixed with the protocol
  345. */
  346. function add_http_prefix($url, $ssl=false){
  347. $s = strip_http_prefix($url);
  348. $prefix = ($ssl ? "https" : "http");
  349. $s = "$prefix://$s";
  350. return $s;
  351. } // add_http_prefix
  352. // -----------------------------------------------------
  353.  
  354. /**
  355. * Add a parameter keyvalue pair to a URL. We check that
  356. * it isn't already there, and use the right delimiter.
  357. * @param string $href URL to append the new parm to
  358. * @param string $pname Name of the parameter
  359. * @param string $pvalue Value of the parameter
  360. */
  361. function href_addparm($href, $pname, $pvalue) {
  362. if ($href != "") {
  363. $urlbits = explode("?", $href);
  364. $baseurl = $urlbits[0];
  365. $query = (isset($urlbits[1]) ? $urlbits[1] : "");
  366. parse_str($query, $qvars);
  367. $qvars[$pname] = $pvalue;
  368. $q = array();
  369. foreach ($qvars as $name => $val) {
  370. $q[] = "$name=$val";
  371. }
  372. $query = implode("&", $q);
  373. $href = $baseurl . (($query != "") ? "?$query" : "");
  374. }
  375. return $href;
  376. } // href_addparm
  377. // -----------------------------------------------------
  378.  
  379. /**
  380. * Remove a parameter keyvalue pair from a URL.
  381. * @param string $href URL to remove the parm from
  382. * @param string $pname Name of the parameter
  383. */
  384. function href_delparm($href, $pname) {
  385. if ($href != "") {
  386. $urlbits = explode("?", $href);
  387. $baseurl = $urlbits[0];
  388. $query = (isset($urlbits[1]) ? $urlbits[1] : "");
  389. parse_str($query, $qvars);
  390. if (isset($qvars[$pname])) {
  391. unset($qvars[$pname]);
  392. }
  393. $q = array();
  394. foreach ($qvars as $name => $val) {
  395. $q[] = "$name=$val";
  396. }
  397. $query = implode("&", $q);
  398. $href = $baseurl . (($query != "") ? "?$query" : "");
  399. }
  400. return $href;
  401. } // href_delparm
  402. // -----------------------------------------------------
  403.  
  404. /**
  405. * Returns the name in the form SURNAME, Firstname.
  406. * @param string $firstname First name
  407. * @param string $lastname Last name(s)
  408. * @return string The name in format SURNAME, Firstname
  409. */
  410. function format_name($firstname, $lastname) {
  411. return strtoupper($lastname) . ", " . ucfirst($firstname);
  412. } // format_name
  413. // -----------------------------------------------------
  414.  
  415. /**
  416. * Returns a value inside quotes. The type of quotes (single or
  417. * double) are determined from the value content. If the content
  418. * already has a double quote in it, then single quotes are used,
  419. * else (default) double quotes are used.
  420. *
  421. * @return string The value string with appropriate quotes around it.
  422. */
  423. function quoted_valuestring($val) {
  424. // Default the delimiter to double quote..
  425. $delim = chr(34);
  426.  
  427. // Check content for quotes..
  428. $dq = strchr($val, chr(34)); // Double quote(s) in value
  429. $sq = strchr($val, chr(39)); // Single quote(s) in value
  430. // Both present in value, sanitise..
  431. if ($dq && $sq) {
  432. $val = str_replace(chr(34), chr(39), $val);
  433. }
  434. // Only double quotes in value, swap..
  435. elseif ($dq) {
  436. $delim = chr(39);
  437. }
  438. return $delim . $val . $delim;
  439. } // quoted_valuestring
  440. // -----------------------------------------------------
  441.  
  442. /**
  443. * Returns a nicely formatted time string in '3d 12h 14m 33s'
  444. * format, given a number of seconds. Leading elements are suppressed
  445. * if they are zero.
  446. *
  447. * @param integer Number of seconds to convert to time string
  448. * @return string A formatted time string eg: '12h 14m 33s'
  449. */
  450. function nicetime($secs) {
  451. $days = (int) ($secs / 86400);
  452. $secs = $secs % 86400;
  453. $hrs = (int) ($secs / 3600);
  454. $secs = $secs % 3600;
  455. $mins = (int) ($secs / 60);
  456. $secs = $secs % 60;
  457. $s = "";
  458. if ($days > 0) $s .= $days . "d ";
  459. if ($hrs > 0) $s .= $hrs . "h ";
  460. if ($mins > 0) $s .= $mins . "m ";
  461. $s .= $secs . "s";
  462. return $s;
  463. } // nicetime
  464. // -----------------------------------------------------
  465.  
  466. /**
  467. * Returns a nicely formatted size string for displaying
  468. * byte sizes. Eg. 1024 returns '1Kb', etc. Obviously this
  469. * is a display-only string, not a number. You can specify
  470. * the number of decimal places, and the thousands separator
  471. * if you for example want nullstring instead of a comma.
  472. *
  473. * @param integer $bytes Number of bytes.
  474. * @param integer $decimals Number of decimal places to report
  475. * @param string $thousep Thousands separator
  476. * @return string A formatted bytesize eg.
  477. */
  478. function nicebytesize($bytes, $decimals=0, $thousep=",") {
  479. if ($bytes > GIGABYTE) {
  480. $s = number_format( ($bytes / GIGABYTE), $decimals, ".", $thousep) . "GB";
  481. }
  482. elseif ($bytes > MEGABYTE) {
  483. $s = number_format( ($bytes / MEGABYTE), $decimals, ".", $thousep) . "MB";
  484. }
  485. elseif ($bytes > KILOBYTE) {
  486. $s = number_format( ($bytes / KILOBYTE), $decimals, ".", $thousep) . "KB";
  487. }
  488. else {
  489. $s = number_format( $bytes, $decimals, ".", $thousep);
  490. }
  491. return $s;
  492. } // nicebytesize
  493. // -----------------------------------------------------
  494.  
  495. ?>

Documentation generated by phpDocumentor 1.3.0RC3