<?php
/**
 * @package linea21.utils
 * @subpackage lib
 * @author linea21 <info@linea21.com>
 * @version $id SVN
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

/**
 * optimize()
 * callback method
 * to ob_start()
 * @param string $buffer
 * @return string
 */
function optimize($buffer) {

  $title = implode(' - ', $GLOBALS['current_title']);


  return str_replace('##TITLE##', $title, $buffer);
}

/**
 * implode_with_keys()
 * implode avec clefs associées renvoyées
 * sous forme de chaîne de caractères
 * @param string $glue
 * @param string $array
 * @return string
 */
function implode_with_keys($glue, $array) {
  $output = array();
  foreach( $array as $key => $item )
  $output[] = $key . "=" . $item;

  return implode($glue, $output);
}

/**
 * getHttpParameters()
 * Renvoie les paramètres HTTP
 * sous forme de chaîne de caractères
 * @return string
 */
function getHttpParameters($prefix = '?') {

  return $prefix. (string) implode_with_keys('&', $_REQUEST);
}

/**
 * strip_input()
 * Remove PHP and HTML code
 * @param string $str
 * @param string $exceptions
 * @return string
 */
function strip_input($str, $exceptions = false) {

  if(defined('RICH_TEXT_EDITOR') && RICH_TEXT_EDITOR != (string) 0) {
    return $str;
  }
  else {
    if($exceptions)  {
      return strip_tags($str, ALLOWABLE_TAGS);
    }
    else {
      return strip_tags($str);
    }
  }

}

/**
 * IncludeTimeline()
 * Include SIMILE Timeline JS code
 * if needed
 * @return void
 */
function IncludeTimeline() {
  if(defined('TIMELINE_DISPLAY') && TIMELINE_DISPLAY == 1 && (MOD_DEBUG != 1 || MOD_DEBUG_HIDDEN != 0)) {
    if(isset($_REQUEST['rub']) && $_REQUEST['rub']=="project" && (!isset($_REQUEST['todo']) || $_REQUEST['todo'] == 'list')) {
        echo '<script src="' .SITE_CITY_URL. '../lib/js/timeline/timeline_ajax/simile-ajax-api.js" type="text/javascript"></script>'.END_LINE; 
        echo '<script type="text/javascript">
             Timeline_urlPrefix=\'' .SITE_CITY_URL. '../lib/js/timeline/timeline_js/\';       
             Timeline_parameters=\'bundle=true\';
             $(function() {
             $("#content").prepend(\'<div id="my-timeline" style="height: 250px; border-bottom: 1px solid #aaa"></div>\');
             });
             
          </script>';
        echo '<script src="' .SITE_CITY_URL. '../lib/js/timeline/timeline_js/timeline-api.js" type="text/javascript"></script>'.END_LINE; 
        echo '<script type="text/javascript" src="../lib/js/timeline.js"></script>'. END_LINE;
    }
  }
}

/**
 * IncludeTextResizerJs()
 * Include jQuery text-resizer plugin
 * if no js wysiwyg are enabled
 * @return void
 */
function IncludeTextResizerJs() {

  if(!defined('RICH_TEXT_EDITOR') || RICH_TEXT_EDITOR == (string) 0 )
  {
    echo '<script type="text/javascript" src="../lib/js/jquery.textarearesizer.compressed.js"></script>';
    echo '<script type="text/javascript">
	  		$(document).ready(function() {
    			$(\'textarea.largetextfield:not(.processed)\').TextAreaResizer();
    		})
	  		</script>'.END_LINE;
  }
}

/**
 * IncludeTextCornerJs()
 * Include jQuery text-corner plugin
 * if no js wysiwyg are enabled
 * @return void
 */
function IncludeTextCornerJs() {
  echo '<script type="text/javascript" src="../lib/js/jquery.corner.js"></script>'.END_LINE;
  echo '<script type="text/javascript" src="../lib/js/jquery.corner.config.js"></script>'.END_LINE;
}
/**
 * IncludeJsTreeJs()
 * Include jQuery Jstree plugin
 * @return void
 */
function IncludeJsTreeJs() {
  echo '<script type="text/javascript" src="../lib/js/jstree/jquery.tree.min.js"></script>'.END_LINE;
  echo '<script type="text/javascript" src="../lib/js/jstree/plugins/jquery.tree.contextmenu.js"></script>'.END_LINE;
  echo '<script type="text/javascript">
	  		msg_mod = "'. _t('divers','modify').'";
	  		msg_del = "'. _t('divers','delete').'";
	  		</script>'.END_LINE;
  echo '<script type="text/javascript" src="../lib/js/jstree/config.js"></script>'.END_LINE;
}

/**
 * IncludeRichTextEditor()
 * Include RichTextEditor if enabled
 * @return void
 */
function IncludeRichTextEditor() {

  if(defined('RICH_TEXT_EDITOR') && RICH_TEXT_EDITOR != (string) 0 )  {
    if(strtolower(RICH_TEXT_EDITOR) == 'tinymce')
    {
      echo '<script type="text/javascript" src="'.themePath('../lib/js/tinymce/jscripts/tiny_mce/tiny_mce.js', THEME_ADMIN_PATH).'"></script>'.END_LINE;
      echo '<script type="text/javascript" src="'.themePath('../lib/js/tinymce/jscripts/tiny_mce/config.js', THEME_ADMIN_PATH).'"></script>'.END_LINE;
    }
    if(strtolower(RICH_TEXT_EDITOR) == 'fck')
    {
       
      echo '<script type="text/javascript" src="../lib/js/fckeditor/fckeditor.js"></script>'.END_LINE;
      echo '<script type="text/javascript">
      		$(document).ready(function(){
    		
      		FCKeditor.BasePath = "../lib/js/fckeditor/";
      		FCKeditor.MinWidth = "300px";
			FCKeditor.ReplaceAllTextareas(\'largetextfield\');
    

 			 });
      		</script>'.END_LINE;
    }
  }

}


/**
 * IncludeLightboxJs()
 * Include Lightbox jQuery plugin
 * if needed
 * @return void
 */
function IncludeLightboxJs() {

  echo '<script type="text/javascript" src="../lib/js/jquery.lightbox-0.5.pack.js"></script>'.END_LINE;
  echo '<link type="text/css" rel="stylesheet" href="'.THEME_ADMIN_PATH.'css/jquery.lightbox-0.5.css" />'.END_LINE;
  echo '
        <script type="text/javascript">
    $(function() {
    	$("a.lightbox").lightBox();
    });
    </script>'. END_LINE;

}

/**
 * IncludeMultiSelectJs()
 * Include jQuery multiSelect plugin
 * if needed
 * @return void
 */
function IncludeMultiSelectJs() {

  $rub = isset($_REQUEST['rub']) ? $_REQUEST['rub'] : '';
  $todo = isset($_REQUEST['todo']) ? $_REQUEST['todo'] : '';

  if(ActiveItemKey($rub)) $rub = ActiveItemKey($rub);
  $s = $rub . '|' . $todo;
  $a = $GLOBALS['multiSelect_includes'];

  if(in_array($s, $a)) {
    echo '<script type="text/javascript" src="../lib/js/jquery.multiSelect/jquery.multiSelect.js"></script>'.END_LINE;
    echo '<script type="text/javascript" src="../lib/js/jquery.multiSelect/jquery.bgiframe.min.js"></script>'.END_LINE;
    echo '<link type="text/css" rel="stylesheet" href="'.THEME_ADMIN_PATH.'/css/jquery.multiSelect.css" />'.END_LINE;
  }
}

/**
 * IncludedatePickerJs()
 * Include jQuery date Picker
 * if needed
 * @return void
 */
function IncludedatePickerJs() {

  $rub = isset($_REQUEST['rub']) ? $_REQUEST['rub'] : '';
  $todo = isset($_REQUEST['todo']) ? $_REQUEST['todo'] : '';

  if(ActiveItemKey($rub)) $rub = ActiveItemKey($rub);
  $s = $rub . '|' . $todo;
  $a = $GLOBALS['datePicker_includes'];

  if(in_array($s, $a)) {
    echo '<script type="text/javascript" src="../lib/js/jquery.datePicker.js"></script>'.END_LINE;
    echo '<link type="text/css" rel="stylesheet" href="'.THEME_ADMIN_PATH.'/css/datePicker.css" />'.END_LINE;
    echo '<script type="text/javascript" src="../lib/js/date.js"></script>'.END_LINE;
    if(LANGUAGE != 'en') {
      echo '<script type="text/javascript" src="'.themePath('../lib/js/date_'. strtolower(LANGUAGE).'.js', THEME_ADMIN_PATH).'"></script>'. END_LINE;
    }
  }
}

/**
 * SureCreateDir()
 * Créer un dossier s'il n'existe pas.
 * @param string $pathname
 * @param integer $perms
 * @return integer $ver_num
 */
function SureCreateDir($pathname, $perms) {
  if(!file_exists($pathname)) {
    return mkdir ($pathname, $perms, true);
  } else {
    return true;
  }
}


/**
 * SureRemoveDir()
 * Supprime le contenu d'un dossier et le dossier lui-même si précisé.
 *
 * @return integer $ver_num
 */
function SureRemoveDir($dir, $DeleteMe) {
  if(!$dh = @opendir($dir)) return;
  while (($obj = readdir($dh))) {
    if($obj=='.' || $obj=='..') continue;
    if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
  }
  if ($DeleteMe){
    closedir($dh);
    @rmdir($dir);
  }
}

/**
 * num_phpversion()
 * Retourne un entier comme numéro de version PHP
 *
 * @return integer $ver_num
 */
function num_phpversion() {
  $ver = explode( '.', phpversion() );
  $ver_num = $ver[0] . $ver[1] . $ver[2];

  return $ver_num;
}

/**
 * cutText()
 * Découpe un texte à une longeur donnée.
 *
 * @param string $content
 * @param integer $length
 * @param integer $abbr
 * @param string $end
 * @return
 */
function cutText($content, $length, $abbr = 0, $end = '...')
{
  // fix bug #16
  if(function_exists('mb_substr')) $substr = mb_substr($content, 0, $length, CHARSET);
  else  $substr = substr($content, 0, $length);
  if (strlen($content) > $length) {
    if ($abbr == 1) $content_light = "<abbr title=\"" . $content . "\">" . $substr . $end . "</abbr>\n";
    else $content_light = $substr . $end;
  } else $content_light = $content;
  return $content_light;
}

/**
 * cutBody()
 * Renvoie un texte en 2 parties dans un tableau
 *
 * @param string $text
 * @return array $body
 */
function cutBody($text)
{
  $middle = (strlen($text) / 2);
  $end = strlen($text);
  $body[0] = substr($text, 0, $middle);
  $body[1] = substr($text, $middle, $end);
  $chaine = preg_split("/(\.(<br \/>| ))/", $body[1], 2);

  $body[0] .= $chaine[0] . ".";
  $body[1] = @trim($chaine[1]);

  return $body;
}

/**
 * EnlargeImage()
 * Miniatures; agrandissement onclick
 *
 * @param string $uri
 * @param string $style
 * @param string $alt_desc
 * @return string $img_link
 */
function EnlargeImage($uri, $style = '', $alt_desc = '')
{
  list($width, $height, $type, $attr) = getimagesize($uri);
  //$img_link = '<a href="' . $uri . '" title="' . _t('divers','enlarge_photo') . '" onclick="displayImage(\'' . $uri . '\', \'\', \'' . $width . '\', \'' . $height . '\'); return false;">' . END_LINE;
  $img_link = '<a href="' . $uri . '" title="' . _t('divers','enlarge_photo') . '" class="lightbox">' . END_LINE;

  $img_link .= '<img src="' . get_min_name($uri) . '" alt="' . _t('divers','enlarge_photo') . ' ' . $alt_desc . '"' . $style . ' />' . END_LINE;
  $img_link .= '</a>' . END_LINE;

  return $img_link;
}

/**
 * formatNavTitle()
 * Formatage des titres ( interface admin )
 *
 * @param string $content
 * @return string $content
 */
function formatNavTitle($content)
{
  $content = formatText($content, '2HTML');
  $content = cutText($content, 70, 1);

  return $content;
}

/**
 * formatTextli()
 * Formatage des listes ( interface admin )
 *
 * @param string $content
 * @return string $content
 */
function formatTextli($content)
{
  $content = formatText($content, '2HTML');
  $content = cutText($content, 65, 1);
  return $content;
}

/**
 * formatTitleh2()
 * Formatage des titres h2 ( interface admin )
 *
 * @param string $content
 * @return string $content
 */
function formatTitleh2($content)
{
  $content = formatText($content, '2HTML');
  return $content;
}

/**
 * formatText()
 * Formatage de texte pour affichage
 *
 * @param  $content
 * @param string $format
 * @return string $content
 */
function formatText($content, $format = -1)
{
  $content = stripslashes(trim($content));
  switch ($format) {
    case '2HTML':
      $content = nl2br($content);
      break;
    case '2FIELD':
      $content = htmlentities($content, ENT_QUOTES, 'utf-8');
      break;
    case '2ATT':
      $content = htmlentities($content, ENT_QUOTES, 'utf-8');
      break;
    case '2XML':
      $content = strip_tags($content);
      break;
    case '2FILE':
      //$content = addslashes(trim($content));
      $content = htmlspecialchars($content, ENT_QUOTES, 'utf-8');
      break;
    default:
  }
  return $content;
}

/**
 * ReplaceInvalidChars()
 * Remplacement des caractères invalides  par leurs entités HTML
 *
 * @param string $str
 * @return string $valid_string
 */
function ReplaceInvalidChars($str)
{
  $htmlentities_chars = array('å' => '&#338;', 'ú' => '&#339;',
        'ä' => '&#352;', 'ö' => '&#353;',
        'ü' => '&#376;', 'à' => '&#710;',
        'ò' => '&#732;', 'ñ' => '&#8211;',
        'ó' => '&#8212;', 'ë' => '&#8216;',
        'í' => '&#8217;', 'Ç' => '&#8218;',
        'ì' => '&#8220;', 'î' => '&#8221;',
        'Ñ' => '&#8222;', 'Ü' => '&#8224;',
        'á' => '&#8225;', 'Ö' => '&#8230;',
        'â' => '&#8240;', 'É' => '&#402;',
        'ã' => '&#8249;', 'õ' => '&#8250;',
        'Ä' => '&#8364;', 'ô' => '&#8482;',
        'ï' => '&#8226;', 'ò' => '&#732;',
        'ô' => '&#8482;');

  //$valid_string = str_replace(array_keys($htmlentities_chars), array_values($htmlentities_chars), $str);
  //return $valid_string;
  return $str;
}

function stripAccents($string) {

  $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
  $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");

  return str_replace($search, $replace, $string);


}

function stripText($text) {

  $text = strtolower($text);

  // strip all non word chars
  $text = preg_replace('/\W/', ' ', $text);
  // replace all white space sections with a dash
  $text = preg_replace('/\ +/', '-', $text);
  // trim dashes
  $text = preg_replace('/\-$/', '', $text);
  $text = preg_replace('/^\-/', '', $text);

  return $text;
}

/**
 * toStringSqlDate()
 * Renvoie la date au format SQL
 *
 * @param string $format
 * @return string $s
 */
function toStringSqlDate($format = 'short')
{
  $date_format =   array(
                   'dd-mm-yyyy' => array(
                      	'mysql' => array('short'=> '%d-%m-%Y', 'long'=> 
  array('12' => '%d-%m-%Y  %r', '24' => '%d-%m-%Y  %T')),
                    	'pgsql' => array('short'=> 'DD-MM-YYYY', 'long'=> 
  array('12' => 'DD-MM-YYYY HH12:MI:SS', '24' => 'DD-MM-YYYY HH24:MI:SS'))),
                    'yyyy-mm-dd' => array(
                      	'mysql' => array('short'=> '%Y-%m-%d', 'long'=> 
  array('12' => '%Y-%m-%d  %r', '24' => '%Y-%m-%d  %T')),
                    	'pgsql' => array('short'=> 'YYYY-MM-DD', 'long'=> 
  array('12' => 'YYYY-MM-DD HH12:MI:SS', '24' => 'YYYY-MM-DD HH24:MI:SS'))),

  );
   
  if($format == 'long') $s = $date_format[DATE_FORMAT][SQL][$format][TIME_FORMAT];
  else $s = $date_format[DATE_FORMAT][SQL][$format];

  return $s;
}


/**
 * date_compare()
 * Compare 2 dates with a given operator.
 * @param  $date1
 * @param  $date2
 * @param  $op
 * @return boolean
 */
function date_compare($date1, $date2, $op) {

  $date1= strtotime(formatDate($date1, true));
  $date2= strtotime(formatDate($date2, true));

  switch($op) {
    case '>':
      if($date1 > $date2) return true;
      else return false;
      break;
    case '<':
      if($date1 < $date2) return true;
      else return false;
    case '>=':
      if($date1 >= $date2) return true;
      else return false;
      break;
    case '<=':
      if($date1 <= $date2) return true;
      else return false;
    case '==':
      if($date1 == $date2) return true;
      else return false;
    default:
      return false;
  }
}

/**
 * ln10filename()
 * Build a localized filename
 * according to the cuurent language
 *
 * @param string $file
 * @return string
 */
function ln10filename($file)
{

  $tmp=@explode(".", $file);
  $total = count($tmp) - 1;
  $ext = $tmp[$total];
  unset($tmp[$total]);

  return @implode(".", $tmp). '.' . LANGUAGE. '.' .$ext;
}


/**
 * distInclude()
 * Include the required file
 * if no user file is found,
 * includes the dist/ version file.
 * Localized files have the priority
 *
 * @param string $file
 * @return void
 */
function distInclude($file, $default_dist)
{
  $l10n_file = ln10filename($file);
  $l10n_file_dist =  dirname($l10n_file).'/dist/'.basename($l10n_file);

  $file_dist_default =  $default_dist.'dist/'.basename($file);
  $l10n_file_dist_default = $default_dist.'dist/'.basename($l10n_file);

  if(file_exists($l10n_file)) {
    _debug($l10n_file, "override");
    include_once($l10n_file);

  } elseif(file_exists($l10n_file_dist))  {
    _debug($l10n_file_dist, "override");
    include_once($l10n_file_dist);
  }
  elseif(file_exists($file)) {
    _debug($file, "override");
    include_once($file);
  }
  elseif(file_exists($l10n_file_dist_default)) {
    _debug($l10n_file_dist_default, "override");
    include_once($l10n_file_dist_default);
  }
  elseif(file_exists($file_dist_default)) {
    _debug($file_dist_default, "override");
    include_once($file_dist_default);
  }
  else {
    _debug(dirname($file).'/dist/'.basename($file), "override");
    include_once(dirname($file).'/dist/'.basename($file));
  }

}

/**
 * themeInclude()
 * Include the required file
 * if no user file is found in theme,
 * includes the default module version file.
 *
 * @param string $file
 * @param string $path
 * @return void
 */
function themeInclude($file, $path= 0)
{
  if($path == 0) $path = THEME_PUBLIC_PATH;
  $theme_file = $path.'override/'.str_replace('../', '', $file);

  if(file_exists($theme_file)) {
    _debug($theme_file, "override");
    include_once($theme_file);

  } else {
    _debug($file, "override");
    include_once($file);
  }

}

/**
 * themePath()
 * check if a template file version exists or not
 * if no user file is found in theme,
 * return the default module version file.
 *
 * @param string $file
 * @param string $path
 * @return string
 */
function themePath($file, $path= 0)
{
  if($path == 0) $path = THEME_PUBLIC_PATH;
  $theme_file = $path.'override/'.str_replace('../', '', $file);
  if(file_exists($theme_file)) {
    _debug($theme_file, "override");
    return $theme_file;

  } else {
    _debug($file, "override");
    return $file;
  }

}

/**
 * formatDate()
 * Renvoie la date aux formats yyyy-mm-dd ou dd-mm-yyyy suivant le cas de départ
 * Si $db == true renvoie toujours la date au format yyyy-mm-dd
 *
 * @param string $date
 * @param boolean $db
 * @return string $new_date
 */
function formatDate($date, $db = false)
{
  @list($part1, $part2, $part3) = explode('-', $date);
  if(strlen($part1) == 2) {
    $new_date = $part3 . '-' . $part2 . '-' . $part1;
  } else {
    $new_date = $part1 . '-' . $part2 . '-' . $part3;
  }
  if($db == true) {
    // always return yyyy-mm-dd format
    if(strlen($part1) == 2) {
      $new_date = $part3 . '-' . $part2 . '-' . $part1;
    } else {
      $new_date = $part1 . '-' . $part2 . '-' . $part3;
    }
  }

  return $new_date;
}


/**
 * date_rfc2822()
 * Format date to RFC 2822 date format
 * @param string $date
 * @return string (exemple : Thu, 21 Dec 2000 16:01:07 +0200)
 */
function date_rfc2822($date) {
  if(!isNullDate($date)) {
    $tmp_date = formatDate($date, true);
    @list($y, $m, $d) = explode('-', $tmp_date);
    return date("r", mktime(3, 0, 0, $m, $d, $y));
  } else {
    return false;
  }
}


function isNullDate($date)
{
  if($date == '0001-01-01' || $date == '01-01-0001') {
    return true;
  } else return false;

}

/**
 * empty_nc()
 * retourne le contenu ou N.C
 *
 * @param string $content
 * @return string $content
 */
function empty_nc($content)
{
  $content = trim($content);
  if (empty($content) || isNullDate($content)) $content = _t('divers','nc');

  return $content;
}

/**
 * empty_none()
 * retourne le contenu ou 'aucun'
 *
 * @param string $content
 * @return string $content
 */
function empty_none($content)
{
  $content = trim($content);
  if (empty($content)) $content = _t('divers','none');

  return $content;
}

/**
 * empty_none()
 * retourne le contenu ou 0
 *
 * @param string $content
 * @return string $content
 */
function empty_numeric($content)
{
  $content = trim($content);
  if (empty($content)) $content = 0;

  return $content;
}

/**
 * checkdate_validity()
 * Vérifie la validité d'une date
 *
 * @param string $date
 * @param string $msg (optionnal)
 * @return boolean true or error message (string)
 */
function checkdate_validity($date, $msg= '')
{

  $date=formatDate($date, true);
  @list($year, $month, $day) = explode('-', $date);

  if(!preg_match('/^\d{4}-\d\d-\d\d$/', $date)) {
    $msg .= _t('date','not_valid');
    return $msg;
  }

  if (!@checkdate($month , $day , $year)) return $msg . _t('date','date_do_not_exist');
  return true;
}

/**
 * display_errors()
 * Affichage d'un message d'erreur utilisateur
 *
 * @param string $msg
 * @return void (echo)
 */
function display_errors($msg)
{
  $display_it = "<div class=\"error\">\n";
  $display_it .= $msg;
  $display_it .= "</div>\n";
  echo $display_it;
}

/**
 * system_error()
 * Affichage d'un message d'erreur syst�me
 *
 * @param string $msg
 * @return void (echo)
 */
function system_error($msg = ERROR_SYSTEM)
{
  $display_it = "<div class=\"systemerror\">\n";
  $display_it .= $msg;
  $display_it .= "</div>\n";
  echo $display_it;
  exit;
}

/**
 * get_temp_name()
 * obtenir le nom temporaire d'un fichier
 *
 * @param string $path
 * @return string $temp_path
 */
function get_temp_name($path)
{
  $short_path = dirname($path);
  $filename = basename($path);
  $temp_path = $short_path . "/temp_" . $filename;
  return $temp_path;
}

/**
 * get_min_name()
 * obtenir le nom de la miniature d'un fichier
 *
 * @param string $path
 * @return string $min_path
 */
function get_min_name($path)
{
  $short_path = dirname($path);
  $filename = basename($path);
  $min_path = $short_path . "/min_" . $filename;
  return $min_path;
}

/**
 * ExcedMaxSize()
 * Teste si une image dépasse ou non la taille autorisée (en pixels)
 *
 * @param string $path
 * @param integer $width_max
 * @return boolean
 */
function ExcedMaxSize($path, $width_max)
{
  list($width, $height, $type, $attr) = getimagesize($path);
  if ($width > $width_max || $height > $width_max) return true;
  else return false;
}

/**
 * GetAllPhotoUri()
 * renvoie les paths des photos dans un tableau
 *
 * @param string $path
 * @param string $opt
 * @return array $tab
 */
function GetAllPhotoUri($path, $opt = -1)
{
  if (empty($path)) return false;
  else {
    $tab = explode('|', $path);
    if ($opt == 'min') array_walk($tab, 'get_min_name');
    return $tab;
  }
}

/**
 * cancel_button()
 * génére un bouton de retour
 *
 * @param  $back_uri
 * @return string
 */
function cancel_button($back_uri)
{
  return '<input name="annuler" type="button" value="' . _t('btn','annul') . '" class="button" id="annuler" onclick="window.location=\'' . $back_uri . '\';" />';
}

/**
 * GetDisplayUserRight()
 * renvoie les droits d'un utilisateur
 *
 * @param string $indice
 * @param string $module
 * @return string
 */
function GetDisplayUserRight($indice, $module = -1)
{
  $indice = strtoupper($indice);
  if ($indice == 'U') return _t('user','norights');
  if ($indice == 'A') return _t('user','adminrights');
  if ($indice == 'O' && $module == 'dashboard') return _t('user','managerrights');
  if ($indice == 'O' && $module == 'workshop') return _t('user','animatorrights');
  if ($indice == 'O' && ($module != 'workshop' && $module != 'dashboard')) return _t('user','redactorrights');
}

/**
 * Display_linkin_page()
 *
 * @param array $table_link
 * @param integer $total
 * @param integer $debut
 * @param integer $pas
 * @return void
 **/
function Display_linkin_page($table_link, $total, $debut, $pas = SELECT_LIMIT)
{
  $result = ceil($total / $pas);
  if ($result <= 1) return '&nbsp;';
  else {
    $link = '<div class="lienliste">'.END_LINE;
    $link .= '&lt; &lt; ';
    $sep='';
    for($i = 0; $i < $result; $i++) {
      $current_pos = ($pas * $i);
      if ($debut == $current_pos) $link .= $sep."<span>" . ($i + 1) . "</span> \n";
      else {
        $array_pos = array ('debut' => $current_pos);
        $new_table_link = array_merge ($table_link, $array_pos);
        $link .= $sep.'<a href="'. HrefMaker($new_table_link) . '">' . ($i + 1) . '</a>'.END_LINE;
      }
      $sep=' | ';
    }
    $link .= ' &gt; &gt;';
    $link .= '</div>'.END_LINE;
    echo $link;
  }
}

/**
 * linkin_page()
 * création d'un navigateur de pages numérotées
 *
 * @param string $string_uri
 * @param integer $total
 * @param integer $debut
 * @param integer $pas
 * @return string $link
 */
function linkin_page($string_uri, $total, $debut, $pas = SELECT_LIMIT)
{
  $result = ceil($total / $pas);
  if ($result <= 1) return '&nbsp;';
  else {
    if (strpos($string_uri, '?') === false) $string_uri .= '?';
    else $string_uri .= '&amp;';
    $link = '<div class="lienliste">';
    for($i = 0; $i < $result; $i++) {
      $current_pos = ($pas * $i);
      if ($debut == $current_pos) $link .= "<span>" . ($i + 1) . "</span> \n";
      else $link .= "<a href=\"" . $string_uri . "debut=" . $current_pos . "\">" . ($i + 1) . "</a> \n";
    }
    $link .= '</div>';
    return $link;
  }
}

/**
 * display_statut()
 * renvoie le statut en pleines lettres
 *
 * @param string $statut
 * @return string $result
 */
function display_statut($statut)
{
  switch ($statut) {
    case 'P':
      $result = _t('statut','public');
      break;
    case 'D':
      $result = _t('statut','draft');
      break;
    case 'E':
      $result = _t('statut','E');
      break;
    case 'AA':
      $result = _t('statut','AA');
      break;
    case 'PA':
      $result = _t('statut','PA');
      break;
    case 'C':
      $result = _t('statut','C');
      break;
    case 'U':
      $result = _t('statut','U');
      break;
    case 'O':
      $result = _t('statut','O');
      break;
    case 'A':
      $result = _t('statut','A');
      break;
    case 'W':
      $result = _t('statut','W');
      break;
    default:
      $result = _t('statut','public');
  }
  return $result;
}

/**
 * linkin_content()
 * Cherche les liens et emails dans du contenu -> linkage
 *
 * @param string $content
 * @param string $option
 * @return string $content
 */
function linkin_content($content, $option = 'ALL')
{
  if(defined('AUTO_LINK') && AUTO_LINK == 1)
  {
    if(defined('RICH_TEXT_EDITOR') && RICH_TEXT_EDITOR == (string) 0) {
      if ($option == 'ALL' || $option == 'MAIL') {
        $content = eregi_replace("( |<br />)+([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+)", '\\1<a href="mailto:\\2">\\2</a>', $content);
      }
      if ($option == 'ALL' || $option == 'LINK') {
        $content = eregi_replace("(http|https|ftp|ftps)://([-a-z0-9#?/&=:,_;@%.{}]*)([a-z0-9=]{2,4})", '<a href="\\1://\\2\\3" class="out">\\1://\\2\\3</a>', $content);
      }
    }
  }

  return $content;
}

/**
 * QuickBoxNow()
 * Génération de la quickbox
 *
 * @param string $module
 * @param string $h1
 * @param string $liste
 * @param string $suffixclass
 * @return string $quickbox
 */
function QuickBoxNow($module, $h1, $liste, $suffixclass = '')
{
  $quickbox = "<div class=\"entete\">\n<div class=\"qb_ico\" id=\"qbico" . $suffixclass . "\" title=\"" . $module . "\"></div>\n";
  $quickbox .= "<div class=\"quickbox\" id=\"qbbg" . $suffixclass . "\">\n";
  $quickbox .= "<h1>" . $h1 . "</h1>\n";
  $quickbox .= "<ul>";
  $quickbox .= $liste;
  $quickbox .= "</ul>";
  $quickbox .= "</div>";
  $quickbox .= "</div>";

  return $quickbox;
}

/**
 * ReloadIndex()
 * Chargement de l'index après destruction de sessions
 *
 * @param string $item
 * @return void
 */
function ReloadIndex($item)
{
  switch ($item) {
    case 'public':
      return header("Location: ../public/logout.php");
      break;
    case 'admin':
      return header("Location: ../admin/logout.php");
      break;
  }
}

/**
 * getmicrotime()
 * renvoie le temps en microsecondes
 *
 * @return float
 */
function getmicrotime()
{
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}

/**
 * availableLanguages()
 * Return available languages
 * @return array
 **/
function availableLanguages() {
  $a = array();
  if ($handle = opendir('../languages/')) {
      while (false !== ($file = readdir($handle))) {
          if ($file != "." && $file != ".." && $file != ".svn") {
              array_push($a, $file);
          }
      }
      closedir($handle);
  }

  return $a;
}



/**
 * GenerateXhtmlPage()
 *
 * @param $string
 * @param integer $time
 * @param unknown $redirect
 * @return
 **/
function GenerateXhtmlPage($string, $time = 2, $redirect = SITE_CITY_URL)
{


  $page  = '<?xml version="1.0" encoding="ISO-8859-1" xml:lang="' . LANGUAGE . '"?>' . END_LINE;
  $page .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' . END_LINE;
  $page .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . LANGUAGE . '">' . END_LINE;
  $page .= '<head>' . END_LINE;
  $page .= '<meta http-equiv="content-type" content="text/html;charset=' . CHARSET . '" />' . END_LINE;
  $page .= '<meta http-equiv="content-langage" content="' . CHARSET . '" />' . END_LINE;
  $page .= '<meta http-equiv="refresh" content="' . $time . ';url=' . $redirect . '">' . END_LINE;
  $page .= '<link rel="icon" type="image/gif" href="' .THEME_ADMIN_PATH. 'images/favicon.gif" />' . END_LINE;
  $page .= '<title>'.SITE_CITY_NAME.'</title>' . END_LINE;
  $page .= '</head>' . END_LINE;
  $page .= '<body>' . END_LINE;
  $page .= '<div class="info" style="margin-top:10em">'.$string.END_LINE;
  $page .= '<br />';
  $page .= sprintf( _t('divers','redirect_string'), $redirect, $time);
  $page .= '</div>'. END_LINE;
  $page .= '</body>' . END_LINE;
  $page .= '</html>' . END_LINE;

  return $page;
}

/**
 * debugEnabled
 * Display a debug alert
 * 
 * @return void
 **/
function debugEnabled() {
  if(defined('MOD_DEBUG') && MOD_DEBUG == true) {
    echo '<div id="debug-enabled">DEBUG_MOD '._t('debug', 'enabled') .'</div>';
  }
}

/**
 * _debug()
 * Display a debug message in html code
 * @param $string
 * @return void
 **/
function _debug($string, $mode)
{
  if(defined('MOD_DEBUG') && MOD_DEBUG == true)
  {
    if($mode == 'override' && defined('TYPE_DEBUG') && TYPE_DEBUG == "override")
    {
    if(defined('MOD_DEBUG_HIDDEN') && MOD_DEBUG_HIDDEN == true) echo "<!-- "; else echo "<p class=\"debug\">";
    echo $string;
    if(defined('MOD_DEBUG_HIDDEN') && MOD_DEBUG_HIDDEN == true) echo " -->"; else echo END_LINE."</p>";
    }
    }
}

/**
 * check4newVersion()
 * Display a link to download new version if available
 * @return string
 **/
function check4newVersion() {
  try{
    if(!@$rss=simplexml_load_file(SITE_LINEA_URL.'/linea_version.xml')){
      throw new Exception('Version : xml file was not found');
    }

    $latest_version = str_pad(str_replace('.', '', $rss->num), 4, '0');
    $current_version = str_pad(str_replace('.', '', LINEA_VERSION), 4, '0');

    if((integer)$latest_version > (integer)$current_version) {
      $update = '<div id="version-check">'._t('check_update','search').' : <a href="'.(string)$rss->link.'">'.sprintf(_t('check_update','dl'), $rss->num).'</a></div>';
    } else {
      $update = '<div id="version-check">'._t('check_update','search').' : '._t('check_update','ok').'</div>';
    }
  }
  catch(Exception $e){
    $update = $e->getMessage();
  }
  
  return $update;
}
?>