view common-functions.inc @ 83:ff5fc61aa5ea

Throw only specific exceptions, eg. non of type Exception base.
author Tom Fredrik "BFG" Klaussen <bfg@blenning.no>
date Mon, 15 Oct 2012 16:52:28 +0200
parents 947d53f95ccd
children 7a9c45b53866
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 "<div id=\"page\"><h1>${errorText}</h1></div>";
  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;
}

/**
 * Queries a URL for headers
 *
 * @param $url the url to query
 * @return an associative array of all headers returned
 */
function getHeaders($url)
{
  $response = http_head($url, array("timeout" => 1), $info);
  $headers = array();
  $response = trim($response);
  $str = explode("\n", $response);
  $headers[''] = trim($str[0]);
  foreach($str as $kv) {
    $p = strpos($kv, ":");
    if ($p) {
      $key = substr($kv, 0, $p);
      $value = trim(substr($kv, $p + 1));
      $headers[$key] = $value;
    }
  }
  return $headers;
}

/**
 * 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;
}
?>