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


/**
 * 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(is_string($exceptions))  {
			return strip_tags($str, $exceptions);
		}
		if($exceptions === true)  {
			return strip_tags($str, ALLOWABLE_TAGS);
		}
		return strip_tags($str);
	}

}

/**
 * IncludeTimeline()
 * Include SIMILE Timeline JS code
 * if needed
 * @return void
 */
function IncludeTimeline() {
	if(defined('TIMELINE_DISPLAY') && TIMELINE_DISPLAY == 1) {
		if(isset($_REQUEST['rub']) && $_REQUEST['rub']=="project" && (!isset($_REQUEST['todo']) || $_REQUEST['todo'] == 'list')) {
			echo '<script src="' .SITE_ROOT_URL. 'lib/js/timeline/timeline_ajax/simile-ajax-api.js" type="text/javascript"></script>'.END_LINE;
			echo '<script type="text/javascript">
			Timeline_urlPrefix=\'' .SITE_ROOT_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_ROOT_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;
		}
	}
}

/**
 * IncludeLightRte()
 * Include nicEdit as light RTE
 * param : array $a
 * @return void
 */
function IncludeLightRte($a) {

	echo "<script type=\"text/javascript\">
					var nicEditorLang = '".U_L."';
				</script>".END_LINE;
	echo '<script type="text/javascript" src="../lib/js/nicEdit/lang.js"></script>'.END_LINE;
	echo '<script type="text/javascript" src="../lib/js/nicEdit/nicEdit.min.js"></script>'.END_LINE;
	echo "<script type=\"text/javascript\">
					bkLib.onDomLoaded(function() {
					new nicEditor({iconsPath : '../lib/js/nicEdit/nicEditorIcons.gif', buttonList : ['bold','italic','underline','subscript','superscript', 'link','unlink','image','upload']}).panelInstance('".$a['id']."');
				});
				</script>".END_LINE;
}

/**
 * IncludePHPDebug()
 * Include Js & css for PHP_DEBUG
 * @return void
 */
function IncludePHPDebug() {
	if(defined('MOD_DEBUG') && MOD_DEBUG == true) {
		echo '<script type="text/javascript" src="../lib/vendor/PHP_Debug/js/html_div.js"></script>'.END_LINE;
		echo '<link type="text/css" rel="stylesheet" href="../lib/vendor/PHP_Debug/css/html_div.css" />'.END_LINE;
	}
}
/**
 * IncludeTooltipJs()
 * Include jQuery tooltip plugin
 * @param string $selector
 * @return void
 */
function IncludeTooltipJs($selector) {
	$str='';
	if(is_string($selector)) {
		$str .= '$("'.$selector.'").tooltip({ effect: "slide", opacity: 0.8});';
	} else {
		foreach($selector as $sel) {
			$str .= '$("'.$sel.'").tooltip({ effect: "slide", opacity: 0.8});'.END_LINE;
		}
	}
	echo '<script type="text/javascript" src="../lib/js/jquery.tools.min.js"></script>'.END_LINE;
	echo '<script type="text/javascript">
	$(document).ready(function() {
	'.$str.'
})
</script>'.END_LINE;
}

/**
 * extRegex()
 * Transform a list given in the form "jpg,png,gif"
 * into "(jpg)|(png)|(gif)" format
 * @return string
 */
function extRegex($list) {
	$a = explode(',', $list);
	$b = array();
	foreach($a as $el) {
		array_push($b, '('.$el.')');
	}
	return implode('|', $b);
}

/**
 * IncludeFancyUploadJs()
 * Include jQuery Fancy Upload
 * @return void
 */
function IncludeFancyUploadJs() {
	$rub = isset($_REQUEST['rub']) ? $_REQUEST['rub'] : '';
	if(ActiveItemKey($rub)) $rub = ActiveItemKey($rub);

	$a = $GLOBALS['fancyUpload_includes'];

	// security check here because uploadify is not able to handle cookie
	if(in_array($rub, $a) && $GLOBALS['l21auth']->isWorkgroupUser($_REQUEST['id'], $GLOBALS['sql_object'])) {

		$fileDesc = str_replace(',', ', ', MEDIA_ALLOWED_EXT);
		echo '<script type="text/javascript">
		var rooturl = "' . SITE_ROOT_URL. '";
		var upbutton = "' . _t('divers', 'up').'";
		var delbutton = "'. _t('divers', 'delqueue').'";
		var addfiles = "' . _t('upload', 'addfiles').'";
		var succeed = "' . _t('upload', 'confirmed').'";
		var error = "' . _t('upload', 'error').'";
		var notallowed_msg = "'.sprintf(_t('upload', 'wrong_ext'), $fileDesc).'";
		var size_msg = "'.sprintf(_t('upload','upload_size'), formatBytes(MEDIA_ALLOWED_SIZE)).'";
		var maxsize = "' . MEDIA_ALLOWED_SIZE.'";
		var regexpattern = "' . extRegex(MEDIA_ALLOWED_EXT).'";
		var fileReplace = "' . _t('divers', 'replace_file').'";
		var cbText = "'._t('workshop', 'share_files').'";
		</script>
		<link type="text/css" rel="stylesheet" href="../lib/js/jquery-ui/css/ui-lightness/jquery-ui-1.8.16.custom.css" id="theme" />
		<link type="text/css" rel="stylesheet" href="../lib/vendor/jQuery-File-Upload/jquery.fileupload-ui-l21.css" media="screen" />
		<script type="text/javascript" src="../lib/js/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
		<script type="text/javascript" src="../lib/vendor/jQuery-File-Upload/jquery.fileupload.js"></script>
		<script type="text/javascript" src="../lib/vendor/jQuery-File-Upload/jquery.fileupload-ui.js"></script>
		<script type="text/javascript" src="../lib/vendor/jQuery-File-Upload/public-settings.js"></script>'.END_LINE;
	}
}

/**
 * dragTableSettings()
 * Include jQuery DragTable plugin settings
 * @return void
 */
function dragTableSettings() {

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

	echo '<script type="text/javascript">
	$(document).ready(function(){
	$("table.sortable thead tr").prepend("<td>&nbsp;<\/td>");
	$("table.sortable tfoot tr").prepend("<td>&nbsp;<\/td>");
	$("table.sortable tbody tr").prepend("<td class=\"dragHandle\">&nbsp;<\/td>");
	$("table.sortable").tableDnD({
	onDrop: function(table, row) {
	$.get("../admin/_ajax_sort.php?rub='.$rub.'&" + $.tableDnD.serialize(), function(data) {
	// replacing data.class by data["class"] for IE8 bug fix
	if(data["class"] == "succeed") {
	humane.success(data.msg);
} else {
humane.error(data.msg);
}
},
"json")
},
dragHandle: "dragHandle"
});
});
</script>'.END_LINE;
}

/**
 * IncludeTreeJs()
 * Include jQuery tree plugin
 * @return void
 */
function IncludeTreeJs() {
	$str = '<ul id="cMenu" class="contextMenu"><li class="edit"><a href="#edit">'. _t('divers','modify').'<\/a><\/li><li class="delete separator"><a href="#delete">'. _t('divers','delete').'<\/a><\/li><\/ul>';
	echo '<script type="text/javascript" src="../lib/js/jquery.contextMenu/jquery.contextMenu.js"></script>'.END_LINE;
	echo '<link type="text/css" rel="stylesheet" href="../lib/js/jquery.contextMenu/jquery.contextMenu-l21.css" media="screen" />'.END_LINE;
	echo '<script type="text/javascript" src="../lib/js/jquery.treeview/jquery.treeview.js"></script>'.END_LINE;
	echo '<link type="text/css" rel="stylesheet" href="../lib/js/jquery.treeview/jquery.treeview.css" media="screen" />'.END_LINE;
	echo '<script type="text/javascript">
	$(document).ready(function(){
	$("#tree").after(\''.$str.'\');
	$("#tree").treeview({
	animated: "fast",
	collapsed: false,
	unique: false
});

$("#tree ul li.contextual-menu").contextMenu({
menu: "cMenu"
}, function(action, el, pos) {
if(action=="edit") {
if(typeof $(el).children("a.ico_mod").attr("href") == "undefined") {
// not used anymore bu we keep it in case of
humane.error("'._t('msg', 'action_not_allowed').'");
return 0;
} else {
document.location.href = $(el).children("a.ico_mod").attr("href");
}
}
if(action=="delete") {
if(typeof $(el).children("a.ico_sup").attr("href") == "undefined") {
// used for level - which does not have delete action
humane.error("'._t('msg', 'action_not_allowed').'");
return 0;
} else {
document.location.href = $(el).children("a.ico_sup").attr("href");
}
}

});
$("#tree li a.ico_mod, #tree li a.ico_sup").css("display", "none");

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

function IncludeRichTextEditor() {

	if(defined('RICH_TEXT_EDITOR') && RICH_TEXT_EDITOR != (string) 0 )  {
		if(strtolower(RICH_TEXT_EDITOR) == 'tinymce')
		{
			echo '<script type="text/javascript" src="'.override('../lib/js/tinymce/jscripts/tiny_mce/tiny_mce.js', THEME_ADMIN_PATH).'"></script>'.END_LINE;
			echo '<script type="text/javascript" src="'.override('../lib/js/tinymce/jscripts/tiny_mce/config.js', THEME_ADMIN_PATH).'"></script>'.END_LINE;
		}
		if(strtolower(RICH_TEXT_EDITOR) == 'cke')
		{
			
			include('../lib/js/ckeditor/ckeditor.php');
			$CKEditor = new CKEditor();
			$CKEditor->basePath = SITE_ROOT_URL.'lib/js/ckeditor/';
			$CKEditor->config['customConfig'] = 'l21_config.js';

			if(CURRENT_APP == 'admin') {
				if(isset($_REQUEST['rub']) && $_REQUEST['rub'] == 'newsletter' && file_exists(THEME_PUBLIC_PATH. 'css/newsletter.css')) {
					$CKEditor->config['contentsCss'] = THEME_PUBLIC_PATH. 'css/newsletter.css';
				}
			}

			if(defined('CKFINDER_ENABLED') && CKFINDER_ENABLED == true) {
				require_once '../lib/vendor/ckfinder/ckfinder.php';
				CKFinder::SetupCKEditor( $CKEditor, '../lib/vendor/ckfinder/' ) ;
			} else {
				$CKEditor->config['filebrowserBrowseUrl'] = '../library/access.php';
				$CKEditor->config['filebrowserImageBrowseUrl'] = '../library/access.php?type=images';
				$CKEditor->config['filebrowserWindowWidth'] = '80%';
				$CKEditor->config['filebrowserWindowHeight'] = '80%';
			}

			$CKEditor->replaceAll('largetextfield');
				
		}
	}

}


/**
 * IncludeColorboxJs()
 * Include Colorbox jQuery plugin
 * @param string £selector
 * @return void
 */
function IncludeColorboxJs($selector) {
	$str='';
	if(is_string($selector)) {
		$str .= '$("'.$selector.'").colorbox({transition:"fade"});'.END_LINE;
	} else {
		foreach($selector as $sel) {
			$str .= '$("'.$sel.'").colorbox({transition:"fade"});'.END_LINE;
		}
	}
	echo '<script type="text/javascript" src="../lib/js/colorbox/colorbox/jquery.colorbox-min.js"></script>'.END_LINE;
	echo '<link type="text/css" rel="stylesheet" href="../lib/js/colorbox/colorbox.css" />'.END_LINE;
	echo '<script type="text/javascript">
				$(document).ready(function() {
				'.$str.'
			});
</script>'. END_LINE;

}

/**
 * IncludeLightboxJs()
 * Include Lightbox jQuery plugin
 * @param string £selector
 * @return void
 * @todo Remove function - Already replaced by colorbox
 */
function IncludeLightboxJs($selector) {

	echo '
	<script type="text/javascript">
	alert("Please, replace IncludeLightboxJs() call by IncludeColorboxJs() into your template.")
	</script>'. END_LINE;

}

/**
 * IncludeTextBoxListJs()
 * Include jQuery TextBoxList plugin
 * if needed
 * @return void
 */
function IncludeTextBoxListJs() {

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

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

	if(in_array($s, $a)) {
		echo '<link type="text/css" rel="stylesheet" href="'.THEME_ADMIN_PATH.'css/TextboxList.css" media="screen" />'.END_LINE;
		echo '<link type="text/css" rel="stylesheet" href="'.THEME_ADMIN_PATH.'css/TextboxList.Autocomplete.css" media="screen" />'.END_LINE;
		echo '<script type="text/javascript" src="../lib/js/jquery.textboxList/GrowingInput.js"></script>'.END_LINE;
		echo '<script type="text/javascript" src="../lib/js/jquery.textboxList/TextboxList.js"></script>'.END_LINE;
		echo '<script type="text/javascript" src="../lib/js/jquery.textboxList/TextboxList.Autocomplete.js"></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-ui-multiselect/src/jquery.multiselect.min.js"></script>'.END_LINE;
		echo '<script type="text/javascript" src="../lib/js/jquery-ui-multiselect/src/jquery.multiselect.filter.min.js"></script>'.END_LINE;
		echo '<script type="text/javascript" src="../lib/js/jquery-ui-multiselect/i18n/jquery.multiselect.'.U_L.'.js"></script>'.END_LINE;
		echo '<script type="text/javascript" src="../lib/js/jquery-ui-multiselect/i18n/jquery.multiselect.filter.'.U_L.'.js"></script>'.END_LINE;
		echo '<link type="text/css" rel="stylesheet" href="../lib/js/jquery-ui-multiselect/jquery.multiselect.css" />'.END_LINE;
		echo '<link type="text/css" rel="stylesheet" href="../lib/js/jquery-ui-multiselect/jquery.multiselect.filter.css" />'.END_LINE;
	}
}

/**
 * IncludeMappingLibraryJs()
 * Include the current mapping library
 * if needed
 * @todo not used - Gmaps is used instead
 * @return void
 */
function IncludeMappingLibraryJs() {

	// @todo remove from here and insert into /config/define.php if used
	$GLOBALS['mapping_includes'] = array('directory-detail|');
	//

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

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

	if(in_array($s, $a)) {
		echo '<script type="text/javascript" src="../lib/vendor/leaflet/dist/leaflet.js" /></script>'.END_LINE;
		echo '<link rel="stylesheet" type="text/css" href="../lib/vendor/leaflet/dist/leaflet.css" />'.END_LINE;
		echo '<!--[if lte IE 8]><link rel="stylesheet" href="../lib/vendor/leaflet/dist/leaflet.ie.css" /><![endif]-->'.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;
}

/** mb_ucfirst()
 * UTF-8 ucfirst function
 * @param string $string
 * @param string $encoding
 * @return string
 */
function mb_ucfirst($string, $encoding = CHARSET)
{
	if(function_exists('mb_strlen')) {
		$strlen = mb_strlen($string, $encoding);
		$firstChar = mb_substr($string, 0, 1, $encoding);
		$then = mb_substr($string, 1, $strlen - 1, $encoding);
		return mb_strtoupper($firstChar, $encoding) . $then;
	} else {
		_debug('mb_string module not loaded');
		return ucfirst($string);
	}
}

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

/**
 * error_redirect()
 * Redirect to error page
 */
function error_redirect($file ='error.php') {

	header("Location: " . CURRENT_APP_URL . $file);
  exit();
}

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

/**
 * removeEmptyP()
 * Remove empty P tags
 *
 * @param string $text
 * @return array $body
 */
function removeEmptyP($str) {
	$str = preg_replace('#<p[^>]*>(\s|&nbsp;?)*</p>#', '', $str);

	return $str;
}

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

/**
 * isRawText()
 * check if raw text or html text
 *
 * @param string $t
 * @return bool
 */
function isRawText($t) {
	if(preg_match('/<[a-z0-9]>/i', $t) == 0) {
		return true;
	} else {
		return false;
	}
}

/**
 * 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':
			if(RICH_TEXT_EDITOR === 0 || isRawText($content)) $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(html_entity_decode ($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). '.' . U_L. '.' .$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('distInclude() file Inclusion : '.$l10n_file);
		include_once($l10n_file);

	} elseif(file_exists($l10n_file_dist))  {
		_debug('distInclude() file Inclusion : '.$l10n_file_dist);
		include_once($l10n_file_dist);
	}
	elseif(file_exists($file)) {
		_debug('distInclude() file Inclusion : '.$file);
		include_once($file);
	}
	elseif(file_exists($l10n_file_dist_default)) {
		_debug('distInclude() file Inclusion : '.$l10n_file_dist_default);
		include_once($l10n_file_dist_default);
	}
	elseif(file_exists($file_dist_default)) {
		_debug('distInclude() file Inclusion : '.$file_dist_default);
		include_once($file_dist_default);
	}
	else {
		_debug('distInclude() file Inclusion : '.dirname($file).'/dist/'.basename($file));
		include_once(dirname($file).'/dist/'.basename($file));
	}

}

/**
 * getOverridePluginsFiles()
 * return an array of paths
 * corresponding to the given filename
 * and matching the array of given plugins 
 *
 * @param array $a
 * @param string $filename
 * @return array
 */
function getOverridePluginsFiles($a, $filename) {

	$o = array();
	if(count($a) == 0) return $o;

	foreach ($a as &$v) {
		$path = '../plugins/'.$v.'/override/'.str_replace('../', '', $filename);

		if(is_file($path) && file_exists($path)) {
			array_push($o, $path);
		}
	}
	return $o;

}

/**
 * override()
 * check if ovveride version exists for the whole app
 * then if a template file version exists or not
 * finally, if no user file is found in theme,
 * return the default module version file.
 *
 * @param string $file
 * @param string $path
 * @return string
 */
function override($file, $path = null, $default = true)
{
	// we first check if file is handled by a plugin
	$paths = getOverridePluginsFiles(enabledPlugins(), $file);
	
	if(count($paths) > 0) {
		if(count($paths) > 1 && is_file($file)) {
			_debug('[plugins override] possible conflicts : '.count($paths). ' occurences of the same file. Loaded from '. $paths[0]);
		}
		_debug('[plugins override] : '.$paths[0]);
		return $paths[0];
	}

	// if not, we check if file exists in OVERRIDE_FOLDER
	$filename = OVERRIDE_FOLDER.str_replace('../', '', $file);
	if(file_exists($filename)) {
		_debug('[general override] : '.$filename);
		return $filename;

	}

	// if not again we are checking into themes folders
	if(is_null($path)) {
		$path = THEME_PUBLIC_PATH;
	}

	$theme_file = $path.'override/'.str_replace('../', '', $file);

	if(file_exists($theme_file)) {
		_debug('[thematic override] : '.$theme_file);
		return $theme_file;

		// finally we include the default one if asked
	}
	if($default) {
		_debug('[no override] : '.$file);
		return $file;
	}

	return true;

}


/**
 * 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(substr($date, 0, 10) == '0001-01-01' || substr($date, 0, 10) == '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 ($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= '')
{

	if(empty($date)) return _t('date','do_provide');
	
	$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;
}

/**
 * sortItems()
 * Return an array with key and value
 * with ID as key and RANGE as value
 * @return array
 */
function sortItems($rub, $data) {

	$a = array();

	for($i=0; $i<count($data); $i++) {
		$v = $data[$i];
		$a[$v]= $i+1;
	}

	return $a;

}

/**
 * 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
 * @todo not used anymore (verify) - can be removed
 */
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
 * @todo can be removed later / still used in class.upload.php
 */
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
 * @todo - Remove in 1.6 if not use anymore
 */
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="pagination">'.END_LINE;
		$link .= '« ';
		$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 .= ' »';
		$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="pagination">';
		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 mb_ucfirst($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/index.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);
}


/**
 * availablePlugins()
 * Return available plugins
 * @return array
 **/
function availablePlugins() {
	$a = array();
	if ($handle = opendir('../plugins/')) {
		while (false !== ($file = readdir($handle))) {
			if (substr($file, 0, 4) == 'l21_' ) {
				array_push($a, $file);
			}
		}
		closedir($handle);
	}

	return $a;
}

/**
 * enabledPlugins()
 * Return available plugins
 * @return array
 **/
function enabledPlugins() {
	$a = array();
	if ($handle = opendir('../plugins/')) {
		while (false !== ($file = readdir($handle))) {
			if (substr($file, 0, 4) == 'l21_' && file_exists('../plugins/'.$file.'/.active')) {
				array_push($a, $file);
			}
		}
		closedir($handle);
	}

	return $a;
}



/**
 * sql_dump2array()
 * @param $url
 * @param $a
 * @return array
 * @link http://fr2.php.net/manual/fr/function.mysql-query.php
 */
function sql_dump2array($url, $a = -1) {

	$handle = @fopen($url, "r");
	$query = "";
	if($a == -1) $a = array();

	while(!feof($handle)) {
		$sql_line = fgets($handle);
		if (trim($sql_line) != "" && strpos($sql_line, "--") === false && strpos($sql_line, "#") === false) {
			array_push($a, $sql_line);
		}
	}
	return $a;
}

/**
 * sql_status_filter()
 * @param $fieldname 
 * @param $a array
 * @return string
 */
function sql_status_filter($fieldname, $a) {
	
	$str = '';
	$sep = '';
	
	foreach ($a as $value) {
		$str.= $sep. $fieldname . " = '". $value ."'";
		$sep = " OR ";
	}
	if(count($a) > 1) $str ='('. $str .')';
	
	return $str;
}

/**
 * getProgressbar()
 * Return a graphic progress bar
 * @param $value integer
 * @param $max integer
 * @param $unit string
 * @return string
 */
function getProgressbar($value, $max, $unit) {

	$step = $max / PROJECT_STEP;
	$threshold = $value / PROJECT_STEP;

	$str   = 	'<div class="progressbar" title="'.$value.' '.$unit.'">'.END_LINE;

	for($i=1; $i<=$step; $i++) {
		($i <= $threshold) ? $class = 'class="completed"' : $class = '';
		$str .='<span '.$class.'>&nbsp;</span>';
	}
	$str  .=	'</div>'.END_LINE;

	return $str;
}

/**
 * geocode()
 * get Long/Latitude coordinates
 * @param $address string
 * @return object
 */
function geocode($address) {

	$o->{'status'} = 'geocoder_disabled';

	if(!defined('GEOCODER_ENABLED') || GEOCODER_ENABLED == 0)
		return $o->{'status'};

	$address=str_replace(" ","+",$address);
	if ($address) {
		$json = file_get_contents(GEOCODER_URL.'address='.$address.'&sensor=false');

		$o = json_decode($json);
	}

	return $o;
}

/**
 * placeholderReplace()
 * format '{$key}'
 * @param $array
 * @param $input
 * @return array
 */
function placeholderReplace($array, $input) {
	foreach ($input as $key => $value)
	{
		$array = preg_replace("/{{$key}}/i", $value, $array);
	}
	return $array;
}

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


	$page  = '<?xml version="1.0" encoding="' . CHARSET . '" xml:lang="' . U_L . '"?>' . 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="' . U_L . '">' . 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_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;
}

/**
 * _debug()
 * Display a debug message
 * @param string
 * @return void
 **/
function _debug($string)
{
	if(isset($GLOBALS['Dbg']))
	{
		global $Dbg;

		$Dbg->add(htmlentities($string));
		$Dbg->stopTimer();
	}
}

/**
 * headerAddCSS()
 * Add CSS into header
 * @param string
 * @param string
 * @return boolean
 **/
function headerAddCSS($path, $pos = 'default')
{
	if(!fopen($path, 'r')) {
		_debug('<b>Problem loading CSS file</b> : '.$path . ' (position : '.$pos.')');
		return false;
	}

	$str = '<link type="text/css" rel="stylesheet" href="'.$path.'" />'.END_LINE;

	if(isset($GLOBALS['CSSheader']))
	{
		if($pos == 'first') {
			$GLOBALS['CSSheader'] = $str . $GLOBALS['CSSheader'];
		} else {
			$GLOBALS['CSSheader'] .= $str . END_LINE ;
		}
	} else {
		$GLOBALS['CSSheader'] = $str;
	}
	_debug('Loading <b>CSS file</b> : '.$path . ' (position : '.$pos.')');

	return true;
}

/**
 * headerAddJS()
 * Add JS into header
 * @param string
 * @param string
 * @return boolean
 **/
function headerAddJS($path, $pos = 'default')
{
	if(!fopen($path, 'r')) {
		_debug('<b>Problem loading JS file</b> : '.$path . ' (position : '.$pos.')');
		return false;
	}

	$str= '<script type="text/javascript" src="'.$path .'"></script>'.END_LINE;

	if(isset($GLOBALS['JSheader']))
	{
		if($pos == 'first') {
			$GLOBALS['JSheader'] = $str . $GLOBALS['JSheader'];
		}
		else {
			$GLOBALS['JSheader'] .= $str . END_LINE ;
		}
	} else {
		$GLOBALS['JSheader'] = $str;
	}
	_debug('Loading <b>JS file</b> : '.$path . ' (position : '.$pos.')');

	return true;
}

/**
 * footerAddInlineJS()
 * Add inline JS into footer
 * the resulting js is wrapped with <script> tags and jQuery .ready() function if $wrap == true
 * @param string
 * @param string
 * @return boolean
 **/
function footerAddInlineJS($str, $pos = 'default', $wrap = true)
{
if($wrap == true) {
	if(isset($GLOBALS['JSInlinefooter']))
	{
		if($pos == 'first') {
			$GLOBALS['JSInlinefooter'] = $str . END_LINE. $GLOBALS['JSInlinefooter'];
		}
		else {
			$GLOBALS['JSInlinefooter'] .= $str . END_LINE ;
		}
	} else {
		$GLOBALS['JSInlinefooter'] = $str. END_LINE;
	}
} else {
	if(isset($GLOBALS['JSInlinefooter_nowrap']))
	{
		if($pos == 'first') {
			$GLOBALS['JSInlinefooter_nowrap'] = $str . END_LINE. $GLOBALS['JSInlinefooter_nowrap'];
		}
		else {
			$GLOBALS['JSInlinefooter_nowrap'] .= $str . END_LINE ;
		}
	} else {
		$GLOBALS['JSInlinefooter_nowrap'] = $str. END_LINE;
	}
}
	_debug('Loading <b>inline JS</b> : '.cutText($str, 90) . ' (position : '.$pos.')');

	return true;
}

/**
 * footerAddJS()
 * Add JS into footer
 * @param string
 * @param string
 * @return boolean
 **/
function footerAddJS($path, $pos = 'default')
{
	if(!fopen($path, 'r')) {
		_debug('<b>Problem loading JS file</b> : '.$path . ' (position : '.$pos.')');
		return false;
	}

	$str= '<script type="text/javascript" src="'.$path .'"></script>'.END_LINE;

	if(isset($GLOBALS['JSfooter']))
	{
		if($pos == 'first') {
			$GLOBALS['JSfooter'] = $str . $GLOBALS['JSheader'];
		}
		else {
			$GLOBALS['JSfooter'] .= $str . END_LINE ;
		}
	} else {
		$GLOBALS['JSfooter'] = $str . END_LINE ;
	}
	_debug('Loading <b>JS file</b> : '.$path . ' (position : '.$pos.')');

	return true;
}

/**
 * AddDynamicHeader()
 * Display JS and CSS header
 * @return void
 **/
function AddDynamicHeader() {
	if(isset($GLOBALS['JSheader'])) echo $GLOBALS['JSheader'];
	if(isset($GLOBALS['CSSheader']))  echo $GLOBALS['CSSheader'];
}

/**
 * AddDynamicFooter()
 * Display JS footer
 * @return void
 **/
function AddDynamicFooter() {
	if(isset($GLOBALS['JSfooter'])) echo $GLOBALS['JSfooter'];
	if(isset($GLOBALS['JSInlinefooter_nowrap'])) echo $GLOBALS['JSInlinefooter_nowrap'];
	if(isset($GLOBALS['JSInlinefooter'])) {
		echo '<script type="text/javascript">'.END_LINE;
		echo '	$(document).ready(function() {'.END_LINE;
		echo $GLOBALS['JSInlinefooter'];
		echo '  });'.END_LINE;
		echo '</script>'.END_LINE;
	}
}

/**
 * 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');
		}
		$current_version = preg_replace("/([^0-9])/",'', LINEA_VERSION); // remove letter (if dev version)
		// _debug('current ver : '.$current_version);
		$latest_version = str_pad(str_replace('.', '', $rss->num), 4, '0');
		$current_version = str_pad(str_replace('.', '', $current_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;
}

/**
 * loadThemeInfo()
 * Load theme info
 * @param string
 * @param string
 * @return string
 **/
function loadThemeInfo($type, $name) {
	$a = array();
	try{
		if(!@$flow=simplexml_load_file(SITE_PATH.'templates/'.$type.'/'.$name.'/theme.xml')){
			throw new Exception($name.' plugin : xml file was not found');
		}
		$a['name'] = $flow->themename;
		$a['description'] = $flow->description;
		$a['version'] = $flow->version;
		$a['date'] = $flow->date;
		$a['compatibility'] = $flow->compatibility;
		$a['author'] = $flow->author;
		$a['homepage'] = $flow->homepage;

		return $a;
	}
	catch(Exception $e){
		return $e->getMessage();
	}
}
/**
 * For compatibility with PHP < 5.2
 * json_decode
 */
if ( !function_exists('json_decode') ){
	function json_decode($content, $assoc=false){
		require_once __DIR__ .'/vendor/JSON/JSON.php';
		if ( $assoc ){
			$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
		} else {
			$json = new Services_JSON;
		}
		return $json->decode($content);
	}
}

/**
 * For compatibility with PHP < 5.2
 * json_encode
 */
if ( !function_exists('json_encode') ){
	function json_encode($content){
		require_once __DIR__ .'/vendor/JSON/JSON.php';
		$json = new Services_JSON;
			
		return $json->encode($content);
	}
}

/**
 Validate an email address.
 Provide email address (raw input)
 Returns true if the email address has the email
 address format and the domain exists.
 @link http://www.linuxjournal.com/article/9585
 */
function validEmail($email)
{
	$isValid = true;
	$atIndex = strrpos($email, "@");
	if (is_bool($atIndex) && !$atIndex)
	{
		$isValid = false;
	}
	else
	{
		$domain = substr($email, $atIndex+1);
		$local = substr($email, 0, $atIndex);
		$localLen = strlen($local);
		$domainLen = strlen($domain);
		if ($localLen < 1 || $localLen > 64)
		{
			// local part length exceeded
			$isValid = false;
		}
		else if ($domainLen < 1 || $domainLen > 255)
		{
			// domain part length exceeded
			$isValid = false;
		}
		else if ($local[0] == '.' || $local[$localLen-1] == '.')
		{
			// local part starts or ends with '.'
			$isValid = false;
		}
		else if (preg_match('/\\.\\./', $local))
		{
			// local part has two consecutive dots
			$isValid = false;
		}
		else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
		{
			// character not valid in domain part
			$isValid = false;
		}
		else if (preg_match('/\\.\\./', $domain))
		{
			// domain part has two consecutive dots
			$isValid = false;
		}
		else if
		(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
				str_replace("\\\\","",$local)))
		{
			// character not valid in local part unless
			// local part is quoted
			if (!preg_match('/^"(\\\\"|[^"])+"$/',
					str_replace("\\\\","",$local)))
			{
				$isValid = false;
			}
		}
		if(CHECK_LINK == 1) {
			if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
			{
				// domain not found in DNS
				$isValid = false;
			}
		}
	}
	return $isValid;
}

/**
 * commentEnabled($m)
 * Check if comment is enabled on
 * given module
 * @param string
 * @return boolean
 **/
function commentEnabled($m)
{
	if(!defined('MOD_COMMENT') || MOD_COMMENT == 0) {
		return false;
	} else {
		if(is_numeric(strpos(COMMENT_MODULES, $m))) return true;
		else return false;
	}
}

/**
 * setBreadcrumb()
 * Set breadcrumb content
 * @param array
 * @return void
 **/
function setBreadcrumb($array)
{
	if(!isset($GLOBALS['breadcrumb'])) $GLOBALS['breadcrumb']= array();
	$GLOBALS['breadcrumb'] = array_merge($GLOBALS['breadcrumb'], $array);
}

/**
 * getBreadcrumb()
 * get the Breadcrumb for displaying
 * @param string (optional)
 * @return string
 **/
function getBreadcrumb($sep = '»')
{
	$str = '<div id="breadcrumb">'.END_LINE;
	$str.= '<ul>'.END_LINE;
	$str.= '<li>'.$sep.' <a href="'.SITE_ROOT_URL.'public/">'._t('way', 'home').'</a></li>'.END_LINE;
	foreach($GLOBALS['breadcrumb'] as $key => $value) {

		if($value!=false) $str.= '<li>'.$sep.' <a href="'.$value.'">'.$key.'</a></li>'.END_LINE;
		else $str.= '<li>'.$sep.' '.$key.'</li>'.END_LINE;
	}
	$str.= '</ul>'.END_LINE;
	$str.= '</div>'.END_LINE;

	return $str;
}

/**
 * GetAllFiles()
 * Return an arry of filenames
 * @param string
 * @param array
 * @param boolean
 * @return array
 **/
function GetAllFiles($folder,$ext=array('txt'),$recursif=true) {

	$files = array();
	$dir=opendir($folder);
	while ($file = readdir($dir)) {
		if ($file == '.' || $file == '..') continue;
		if (is_dir($folder.'/'.$file)) {
			if ($recursif==true)
				$files=array_merge($files, GetAllFiles($folder.'/'.$file, $ext));
		} else {
			foreach ($ext as $v) {
				if (strtolower($v)==strtolower(substr($file,-strlen($v)))) {
					$files[] = $folder.'/'.$file;
					break;
				}
			}
		}
	}
	closedir($dir);
	return $files;
}


/**
 * ListDir()
 * Return an HTML list for a given folder
 * @param int
 * @param string
 * @param string
 * @param boolean
 * @return string
 **/
function ListDir($dir_handle,$path, $url) {

	$i= 0;
	$dirFiles = array();

	// we prepare files
	while (false !== ($file = readdir($dir_handle))) {
		$dir = $path . $file;
		if(is_dir($dir) && $file != '.' && $file !='..' ) {
			$handle = @opendir($dir) or die("Unable to open file $file");
			ListDir($handle, $dir.'/', $url);
		} elseif($file != '.' && $file !='..' && $file !='.htaccess') {
			array_push($dirFiles, $dir);
		}
	}
	closedir($dir_handle);

	// sort by name
	sort($dirFiles);

	// uncomment to reverse array
	// $dirFiles= array_reverse($dirFiles);

	// uncomment to sort on latest modification
	//    array_multisort(
	//      array_map( 'filemtime', $dirFiles ),
	//      SORT_NUMERIC,
	//      SORT_DESC,
	//      $dirFiles
	//    );

	echo "<ul>";
	foreach($dirFiles as $dir)
	{
		$size= formatBytes(filesize($dir), 2);
		$class = ($i++ & 1) ? '' : 'class="odd"';
		$dir = str_replace('../', '', $dir);
		$dir = str_replace('//', '/', $dir);
		$dir = dirname($dir).'/'. rawurlencode(basename($dir));
		$file = basename(rawurldecode($dir));

		if(MOD_COMMENT == 1 && commentEnabled('files')) {
			$id = str_replace('library/userfiles/', '', $dir);
			$nb = getFileComments($id);
			$comment_actions  = '<span class="comment_actions">';
			$comment_actions .= '<a class="comment_see" href="../comment/_ajax_view.php?id='.$id.'&amp;module=files&amp;order_by=ASC" title="' . $file . ' - ' . _t('comment','go_to') . ' / ' . _t('comment','add') .'"><span class="cc">' . $nb . '</span><span class="textcc"> ' . _t('comment','comments').' - ' . _t('comment','add') .'</span></a>';
			$comment_actions .= '</span>';
		}

		echo '<li '.$class.'><a href="'. $url . $dir .'">'.$file.'</a> <em>('.$size.')</em> '.$comment_actions.'<a  class="dlfile" href="'. $url .'library/dl.php?file='. $dir .'" title="'._t('divers','dl'). ' ' . $file.'"><span>' ._t('divers','dl'). '</span></a></li>';
	}


	if($i==0) echo '<li>'._t('divers','no_files').'</li>';
	echo "</ul>";
}

/**
 * formatBytes()
 * Make File size readable
 * @param int
 * @param int (optional)
 * @return string
 **/
function formatBytes($bytes, $precision = 2) {
	$units = array('o', 'Ko', 'Mo', 'Go', 'To');

	$bytes = max($bytes, 0);
	$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
	$pow = min($pow, count($units) - 1);

	$bytes /= pow(1024, $pow);

	return round($bytes, $precision) . ' ' . $units[$pow];
}

/**
 * logfile()
 * Log into file
 * @param string
 * @param array
 * @return void
 **/
function logfile($src, $a) {

	$sep = '##';
	$fp = @fopen($src, 'a');

	foreach($a as $value) {
		@fwrite($fp, $value . $sep);
	}

	@fwrite($fp, date('[d-m-y H:i:s]' . $sep. END_LINE));
	@fclose($fp);

	return true;
}

/**
 * getThemes()
 * Return installed themes
 * into an array
 * @param string
 * @return array
 **/
function getThemes($f) {

	$a = array();

	if ($handle = opendir('../templates/'.$f)) {
		$sep='';
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != ".." && $file != ".svn") {
				array_push($a, $file);
			}
		}
		closedir($handle);
	}

	return $a;
}

/**
 * notifyUsersMsg()
 * @access public
 * @param array $a
 * $a['owner'] : item owner
 * $a['user'] : the one who posted the item (can be an adminsitrator or animator)
 * @return boolean
 */
function notifyUsersMsg($a) {

    if($a['action'] == 'post_alert') {
      if(ALERT_NEWPOST == 0) return true;
      if(ALERT_NEWPOST == 1) $m = array('O');
      if(ALERT_NEWPOST == 2) $m = array('O', 'U');

      $wg = $a['parentid'];
      $data = $GLOBALS['sql_object']->DBSelect(SQL_getWorkshopDenomination($a['parentid']));
      if(count($data)==1) $wname =$data[0]['workshop_denomination'];
      $wlinkforum= array('rub'=> $GLOBALS['links'][U_L]['topic']['linkvalue'],'id'=> $a['tid'], 'parentid' => $a['parentid'], 'name' => $wname, '#' => 'msg-'.$a['id']);
      $users = $GLOBALS['sql_object'] -> DBSelect(SQL_getWorkshopUsersforNotification($a['parentid'], 'post'), 'OBJECT');
    }

    if($a['action'] == 'topic_alert') {
      if(ALERT_NEWTOPIC == 0) return true;
      if(ALERT_NEWTOPIC == 1) $m = array('O');
      if(ALERT_NEWTOPIC == 2) $m = array('O', 'U');

      $data = $GLOBALS['sql_object']->DBSelect(SQL_getWorkshopDenomination($a['id']));
      if(count($data)==1) $wname =$data[0]['workshop_denomination'];
      $wlinkfiles = array('rub'=> $GLOBALS['links'][U_L]['files']['linkvalue'],'id'=> $a['id'], 'name' => $wname);
      $wlinkforum= array('rub'=> $GLOBALS['links'][U_L]['topic-list']['linkvalue'],'id'=> $a['id'], 'name' => $wname);
      $users = $GLOBALS['sql_object'] -> DBSelect(SQL_getWorkshopUsersforNotification($a['id'], 'topic'), 'OBJECT');
    }

    if($a['action'] == 'file_alert') {
      if(ALERT_NEWFILE == 0) return true;
      if(ALERT_NEWFILE == 1) $m = array('O');
      if(ALERT_NEWFILE == 2) $m = array('O', 'U');

      $data = $GLOBALS['sql_object']->DBSelect(SQL_getWorkshopDenomination($a['id']));
      if(count($data)==1) $wname =$data[0]['workshop_denomination'];
      $wlinkfiles = array('rub'=> $GLOBALS['links'][U_L]['files']['linkvalue'],'id'=> $a['id'], 'name' => $wname);
      $wlinkforum= array('rub'=> $GLOBALS['links'][U_L]['topic-list']['linkvalue'],'id'=> $a['id'], 'name' => $wname);
      $users = $GLOBALS['sql_object']->DBSelect(SQL_getWorkshopUsersforNotification($a['id'], 'file'), 'OBJECT');
    }
    
    if($a['action'] == 'event_alert') {
    	if(ALERT_NEWEVENT == 0) return true;
    	if(ALERT_NEWEVENT == 1) $m = array('O');
    	if(ALERT_NEWEVENT == 2) $m = array('O', 'U');
    
    	$data = $GLOBALS['sql_object']->DBSelect(SQL_getWorkshopDenomination($a['id']));
    	if(count($data)==1) $wname =$data[0]['workshop_denomination'];
    	$wlinkcalendar = array('rub'=> $GLOBALS['links'][U_L]['calendar']['linkvalue'],'id'=> $a['id'], 'name' => $wname);
    	$users = $GLOBALS['sql_object']->DBSelect(SQL_getWorkshopUsersforNotification($a['id'], 'file'), 'OBJECT');
    }

    foreach($users as $user) {
      if($user->user_login != $a['user']) {
        if(in_array($user->jwu_user_right, $m)) {
          include(override('../workshop/mail_actions.php'));
          include('../mail/template.php');
        }
      }
    }
    return true;
  }

/**
 * cleanString()
 * Remove exotic characters form string
 * same as used in filemanager
 * @param string
 * @param array
 * @return string
 **/
function cleanString($string, $allowed = array()) {
	$allow = null;

	if (!empty($allowed)) {
		foreach ($allowed as $value) {
			$allow .= "\\$value";
		}
	}

	$mapping = array(
			'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
			'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
			'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
			'Õ'=>'O', 'Ö'=>'O', 'Ő'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ű'=>'U', 'Ý'=>'Y',
			'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
			'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n',
			'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ő'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'ű'=>'u',
			'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r', ' '=>'_', "'"=>'_', '/'=>''
	);

	if (is_array($string)) {

		$cleaned = array();

		foreach ($string as $key => $clean) {
			$clean = strtr($clean, $mapping);
			$clean = preg_replace("/[^{$allow}_a-zA-Z0-9]/", '', $clean);
			$cleaned[$key] = preg_replace('/[_]+/', '_', $clean); // remove double underscore
		}
	} else {
		$string = strtr($string, $mapping);
		$string = preg_replace("/[^{$allow}_a-zA-Z0-9]/", '', $string);
		$cleaned = preg_replace('/[_]+/', '_', $string); // remove double underscore
	}
	return $cleaned;
}

// Returns the real IP address of the user
function i2c_realip()
{
	// No IP found (will be overwritten by for
	// if any IP is found behind a firewall)
	$ip = false;
	// If HTTP_CLIENT_IP is set, then give it priority
	if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	// User is behind a proxy and check that we discard RFC1918 IP addresses
	// if they are behind a proxy then only figure out which IP belongs to the
	// user.  Might not need any more hackin if there is a squid reverse proxy
	// infront of apache.
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		// Put the IP's into an array which we shall work with shortly.
		$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
		if ($ip) {
			array_unshift($ips, $ip);
			$ip = false;
		}

		for ($i = 0; $i < count($ips); $i++) {
			// Skip RFC 1918 IP's 10.0.0.0/8, 172.16.0.0/12 and
			// 192.168.0.0/16 -- jim kill me later with my regexp pattern
			// below.
			if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {
				$ip = $ips[$i];
				break;
			}
		}
	}
	// Return with the found IP or the remote address
	return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

/**
 * securityCheck()
 * Test and sanitize user input
 * from request
 * @return boolean
 **/
function securityCheck() {

	$passed = true;

	// we first sanitize vars
	if(isset($_REQUEST['rub']))
		$_REQUEST['rub']= strip_tags($_REQUEST['rub']);
	if(isset($_REQUEST['name']))
		$_REQUEST['name']= strip_tags($_REQUEST['name']);
	if(isset($_REQUEST['email']))
		$_REQUEST['email']= strip_tags($_REQUEST['email']);
	// then do tests
	if(isset($_REQUEST['id']) && preg_match('/[^0-9A-Za-z]/',$_REQUEST['id']))
		$passed= false;
	if(isset($_REQUEST['parentid']) && !is_numeric($_REQUEST['parentid']))
		$passed= false;
	if(isset($_REQUEST['parentparentid']) && !is_numeric($_REQUEST['parentparentid']))
		$passed= false;
	if(isset($_REQUEST['debut']) && !is_numeric($_REQUEST['debut']))
		$passed= false;

	if($passed == false) die('no way!');
	else return true;
}
?>