view common-functions.inc @ 94:2370f4450983

Document functions and move a few functions to more appropriate places.
author Tom Fredrik Blenning Klaussen <bfg@blenning.no>
date Thu, 18 Oct 2012 17:33:34 +0200
parents 8aadd7a23b68
children 6b882fb6ea46
line wrap: on
line source

<?php
/**
 * @file
 * Functionality which doesn't belong anywhere else
 */
include_once 'ScriptIncludeCache.inc';

/// @cond
$baseDir = dirname(__FILE__);

$cache = ScriptIncludeCache::instance(__FILE__);
$cache->includeOnce('StatusCodes.inc', $baseDir);
/// @endcond

/**
 * Generates a representation for an array of key => value pairs
 *
 * @note Behaviour is undefined if value is a composite structure.
 *
 * @param $map the input array
 * @return a string representation that may be eval'ed
 */
function repMapString($map)
{
  $opt = 'array(';
  $start = True;

  foreach($map as $param => $value) {
    if ($start) {
      $start = False;
      $opt .= "\"${param}\" => \"${value}\"";
    }
    else {
      $opt .= ", \"${param}\" => \"${value}\"";
    }
  }
  $opt .= ')';
  return $opt;
}

/**
 * Get the location on the server where the top level script is
 * located
 *
 * @return directory
 */
function basePath()
{
  $l = strrpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['SCRIPT_NAME']);
  return substr($_SERVER['SCRIPT_FILENAME'], 0, $l);
}

/**
 * Loads a file
 *
 * @param $sFilename name of the file to load
 * @param $sCharset the character encoding of the file
 *
 * @todo make this function throw instead of returning codes
 *
 * @return the contents of the file, or a status code (-3 if file does
 * not exists, if file could not be opened -2)
 */
function loadFile($sFilename, $sCharset = 'UTF-8')
{
  if (floatval(phpversion()) >= 4.3) {
    if (!file_exists($sFilename))
      return -3;
    $sData = file_get_contents($sFilename);
  }
  else {
    if (!file_exists($sFilename))
      return -3;
    $rHandle = fopen($sFilename, 'r');
    if (!$rHandle)
      return -2;

    $sData = '';
    while(!feof($rHandle))
      $sData .= fread($rHandle, filesize($sFilename));
    fclose($rHandle);
  }
  if ($sEncoding = mb_detect_encoding($sData, 'auto', true) != $sCharset) {
    if ($sEncoding != 1) {
      $sData = mb_convert_encoding($sData, $sCharset, $sEncoding);
    }
  }
  return $sData;
}

/**
 * Generate a status page and exit
 *
 * @param $errorText the text to be displayed in the body
 * @param $errorCode the status code to be served
 */
function errorPage($errorText, $errorCode = 403)
{
  header(StatusCodes::httpHeaderFor($errorCode));
  print '<?xml version="1.0" encoding="UTF-8"?>';
  print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>';

  print '<title>' . StatusCodes::httpHeaderFor($errorCode) . '</title>';
  print '</head><body>';
  print "<div id=\"page\"><h1>${errorText}</h1></div>";
  print '</body></html>';

  exit;
}

/**
 * Generates an URL for the specified parameters
 *
 * @param $urlParams an associative array of the values already set
 * @param $keys a set of values to override $urlParams
 *
 * @param $nonQueryParams a list of keys, where values should be in
 * the URL, rather than the query part, note that the order is
 * important
 */
function genUrl($urlParams, $keys = array(), $nonQueryParams = array()) {
  $out = '';
  $first = 1;
  $new_params = $urlParams;
  foreach($keys as $param => $val) {
    $new_params[$param] = $val;
  }

  foreach($nonQueryParams as $nqp) {
    if (array_key_exists($nqp, $new_params)) {
      $val = $new_params[$nqp];
      if ($val)
	$out .= "/${val}";
      unset($new_params[$nqp]);
    }
  }

  foreach($new_params as $param => $val) {
    if ($val) {
      if($first) {
	$first = 0;
	$out .= "?";
      }
      else
	$out .= "&amp;";
      $out .= urlencode($param) . '=' . urlencode($val);
    }
  }

  return $out;
}

/**
 * Retrieves a single subelement
 * @throw Exception if number of elements are different from 1
 *
 * @todo Throw more specific exception
 *
 * @param $obj the xml element to search in
 * @param $name the name of the element to search for
 */
function getElementByTagName($obj, $name) {
  $elems = $obj->getElementsByTagName($name);
  if ($elems->length != 1) {
    throw new UnexpectedValueException("More than one tag with name \"${name}\"");
  }
  $elem = $elems->item(0);
  return $elem;
}

/**
 * Checks if one string start with another string
 *
 * @param $haystack the string to search
 * @param $needle the string to search for
 *
 * @return bool if match
 */
function startswith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0;
}

/**
 * Checks if one string ends with another string
 *
 * @param $haystack the string to search
 * @param $needle the string to search for
 *
 * @return bool if match
 */
function endsWith($haystack, $needle)
{
  $l = strlen($haystack) - strlen($needle);
  return strrpos($haystack, $needle) === $l;
}

/**
 * Generates the query part of an URI
 *
 * @param $opts an associative array of options
 * @return a string that can be used for the query part of an URI
 */
function opttostring($opts)
{
  $str = '';
  foreach (array_keys($opts) as $key) {
    $value = $opts[$key];
    if ($str) {
      $str .= "&${key}=${value}";
    }
    else {
      $str = "?${key}=${value}";
    }
  }
  return $str;
}
?>