1<?php
2/**
3* Web based SQLite management
4* Some functions
5* @package SQLiteManager
6* @author Fr�d�ric HENNINOT
7* @version $Id: common.lib.php,v 1.126 2006/04/18 07:18:52 freddy78 Exp $ $Revision: 1.126 $
8*/
9
10/**
11* check if SQLite extension is loaded, and if not load it.
12*/
13function CheckExtension($extName) {
14
15	$SQL_SERVER_OS = strtoupper(substr(PHP_OS, 0, 3));
16	if($SQL_SERVER_OS == 'WIN') { $preffix= 'php_'; $suffix = '.dll'; }
17	elseif($SQL_SERVER_OS == 'NET') { $preffix= 'php_'; $suffix = '.nlm'; }
18	elseif(($SQL_SERVER_OS == 'LIN') || ($SQL_SERVER_OS == 'DAR')) { $preffix= ''; $suffix = '.so'; }
19
20	$extensions = get_loaded_extensions();
21	foreach ($extensions as $key=>$ext) $extensions[$key] = strtolower($ext);
22	if (!extension_loaded($extName) && !in_array($extName, $extensions)) {
23		if(DEBUG) {
24			$oldLevel = error_reporting();
25			error_reporting(E_ERROR);
26			$extensionLoaded = dl($preffix.$extName.$suffix);
27			error_reporting($oldLevel);
28		} else {
29			$extensionLoaded = @dl($preffix.$extName.$suffix);
30		}
31    		return ($extensionLoaded);
32	}
33	else return true;
34
35}
36
37/**
38* Display error message
39*
40* @param string $message
41*/
42function displayError($message){
43	echo '
44	<center>
45		<table width="80%" style="border: 1px solid red;" class="error">
46			<tr><td align="center"><b>'.$GLOBALS['traduct']->get(9).' :</b></td></tr>
47			<tr><td align="left"><span style="color: red"><b>'.$message.'</b></span></td></tr>
48		</table>
49	</center>';
50	return;
51}
52
53/**
54* return the condition
55*/
56function displayCondition($authType){
57	global $SQLiteManagerAuth;
58	return (!WITH_AUTH || (
59							isset($SQLiteManagerAuth) &&  $SQLiteManagerAuth->getAccess($authType)
60							));
61 }
62
63/**
64* Get plugins array
65*/
66function getPlugins(){
67	$res = array();
68	if ($dir = @opendir('plugins')) {
69		while ($element = readdir($dir)) {
70			if (substr($element,0,1) != '.' && $element!='CVS')
71				if (is_dir('plugins/'.$element))
72					$res[] = 'plugins/'.$element.'/';
73		}
74		closedir($dir);
75	}
76	return $res;
77}
78
79/**
80* Display the global menu on the right pan, it' dependant of context
81*/
82function displayMenuTitle(){
83	global $SQLiteManagerAuth, $workDb;
84	$linkBase = 'main.php?dbsel='.$GLOBALS['dbsel'];
85	foreach($GLOBALS['dbItems'] as $Items) if(isset($GLOBALS[strtolower($Items)])) $linkBase .= '&'.strtolower($Items).'='.$GLOBALS[strtolower($Items)];
86	$out = '';
87
88	$menuItems[] = array('txt'=> $GLOBALS['traduct']->get(72),'url'=> $linkBase.'&action=properties');
89	if(isset($GLOBALS['table']) && ($GLOBALS['table']!='')){
90
91		if(isset($_REQUEST['currentPage'])) $valCurrent = $_REQUEST['currentPage'];
92		else $valCurrent = $GLOBALS['action'];
93
94		$Context='Table';
95		//Items : txt:Text, url:Link, enabled, type, hint, confirm, ...
96		$menuItems[] = array('txt'=> $GLOBALS['traduct']->get(73),'url'=> $linkBase.'&action=browseItem');
97	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(74),'url'=> $linkBase.'&action=sql', 'enabled'=> (displayCondition('execSQL')));
98	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(206),'url'=> $linkBase.'&action=select');
99	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(75),'url'=> $linkBase.'&action=insertElement&currentPage='.$valCurrent, 'enabled'=> (displayCondition('data') &&  !$workDb->isReadOnly()));
100	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(222),'url'=> $linkBase.'&action=operation', 'enabled'=> (displayCondition('properties')));
101	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(76),'url'=> $linkBase.'&action=export', 'enabled'=> (displayCondition('export')));
102	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(77),'url'=> $linkBase.'&action=empty', 'confirm'=> $GLOBALS['traduct']->get(79), 'enabled'=> (displayCondition('empty') &&  !$workDb->isReadOnly()));
103	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(15),'url'=> $linkBase.'&action=delete', 'confirm'=> $GLOBALS['traduct']->get(80), 'enabled'=> (displayCondition('del') &&  !$workDb->isReadOnly()));
104
105	} elseif(isset($GLOBALS['view']) && ($GLOBALS['view']!='')) {
106
107		$Context='View';
108		$menuItems[] = array('txt'=> $GLOBALS['traduct']->get(73),'url'=> $linkBase.'&action=browseItem');
109	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(74),'url'=> $linkBase.'&action=sql', 'enabled'=> (displayCondition('execSQL')));
110	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(206,'Select'),'url'=> $linkBase.'&action=select', 'enabled'=> (displayCondition('execSQL')));
111	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(76),'url'=> $linkBase.'&action=export', 'enabled'=> (displayCondition('export')));
112	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(81),'url'=> $linkBase.'&action=add', 'enabled'=> (displayCondition('properties')));
113	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(15),'url'=> $linkBase.'&action=delete', 'confirm'=> $GLOBALS['traduct']->get(82), 'enabled'=> (displayCondition('del') &&  !$workDb->isReadOnly()));
114
115	} elseif(isset($GLOBALS['function']) && ($GLOBALS['function']!='')) {
116
117		$Context='Function';
118	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(74),'url'=> $linkBase.'&action=sql', 'enabled'=> (displayCondition('execSQL')));
119	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(76),'url'=> $linkBase.'&action=export', 'enabled'=> (displayCondition('export')));
120	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(81),'url'=> $linkBase.'&action=add', 'enabled'=> (displayCondition('properties')));
121	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(15),'url'=> $linkBase.'&action=delete', 'confirm'=> $GLOBALS['traduct']->get(78), 'enabled'=> (displayCondition('del') &&  !$workDb->isReadOnly()));
122
123	} elseif(isset($GLOBALS['trigger']) && ($GLOBALS['trigger']!='')) {
124
125		$Context='Trigger';
126	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(74),'url'=> $linkBase.'&action=sql', 'enabled'=> (displayCondition('execSQL')));
127	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(81),'url'=> $linkBase.'&action=add', 'enabled'=> (displayCondition('properties')));
128	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(15),'url'=> $linkBase.'&action=delete', 'confirm'=> $GLOBALS['traduct']->get(83), 'enabled'=> (displayCondition('del') &&  !$workDb->isReadOnly()));
129
130	} else {
131
132		$Context='Database';
133		$hintContext = html_entity_decode($GLOBALS['traduct']->get(131), ENT_NOQUOTES, $GLOBALS['charset']);
134		$menuItems[] = array('txt'=> $GLOBALS['traduct']->get(84),'url'=> $linkBase.'&action=options');
135	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(74),'url'=> $linkBase.'&action=sql', 'enabled'=> (displayCondition('execSQL')));
136	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(76),'url'=> $linkBase.'&action=export', 'enabled'=> (displayCondition('export')));
137	    $menuItems[] = array('txt'=> $GLOBALS['traduct']->get(15),'url'=> $linkBase.'&action=del', 'confirm'=> $GLOBALS['traduct']->get(85), 'enabled'=> (displayCondition('del')));
138
139	}
140	if (!isset($hintContext)) $hintContext = $GLOBALS['itemTranslated'][$Context];
141
142	if(ALLOW_EXEC_PLUGIN){
143		$plugins = getPlugins();
144		foreach($plugins as $plugin_path) {
145			$plugin_menu = array();
146		    include_once($plugin_path.'plugin.php');
147			if (@$plugin_menu[$Context]) {
148				$menu = 'plugin_'.$Context.'Menu';
149				$pluginItems = @$$menu;
150				if (isset($pluginsItems) && @count($pluginsItems))
151					foreach ($pluginsItems as $key=>$item)
152						if (array_key_exists('hint',$item))
153							$pluginItems[$key]['hint'] = $hintContext.' : '.$plugin_name.' : '.$item['hint'];
154						elseif (isset($item['txt']))
155							$pluginItems[$key]['hint'] = $hintContext.' : '.$plugin_name.' : '.$item['txt'];
156				if (isset($pluginItems))
157					foreach ($pluginItems as $item) $pluginsItems[] = $item;
158			}
159		}
160
161		if (isset($pluginsItems)) {
162			$menuItems[] = array('type'=>'_cmSplit');
163			$menuItems[] = array('type'=>'folder', 'txt'=> $GLOBALS['traduct']->get(211,'Plugins'), 'url'=>'#');
164			foreach ($pluginsItems as $item) $menuItems[] = $item;
165			$menuItems[] = array('type'=>'endfolder');
166		}
167		$menuItems[] = array('type'=>'_cmSplit');
168
169	}
170/* Javascript Menu */
171	$out .= "\n\t\t\t".'<script type="text/javascript">'.
172          "\n\t\t\t\t".'var jsMenu = [';
173  $icon=''; $inFolder='';
174	$target='main';
175	foreach ($menuItems as $item) {
176	  $confirm = '';
177	  $title = (isset($item['txt']))? $item['txt'] : '';
178    $icon = (array_key_exists('icon',$item))?'<img class="seq1" src="'.$item['icon'].'"><img class="seq2" src="'.$item['icon'].'">':'&nbsp;';
179    $description = (array_key_exists('hint',$item))? $item['hint'] : $hintContext.' : '.$title;
180    $description = addslashes(html_entity_decode($description, ENT_NOQUOTES, $GLOBALS['charset']));
181		if (!array_key_exists('enabled',$item) || @$item['enabled']) {
182			$url = (isset($item['url']))? $item['url'] : '';
183			if (isset($item['confirm'])) {
184				$confirm = addslashes(html_entity_decode($item['confirm'], ENT_NOQUOTES, $GLOBALS['charset']));
185			}
186		} else {
187			$url = '';
188			$title = '<i>'.$title.'</i>';
189			$description = '[DISABLED] '.$description;
190		}
191
192		if ($url=='') $url='#';
193		$line = "\n\t\t\t\t".$inFolder."['$icon', '$title', '$url', '$target', '$description', '$confirm'";
194
195		if (!isset($item['type'])) {
196			$line .= '],';
197		}
198		else
199			if ($item['type']=='endfolder') {
200				$out = substr($out,0,strlen($out)-1);
201				$line = "\n\t\t\t\t".'],';
202				$inFolder='';
203			} elseif ($item['type']=='folder')
204			{
205				$line .= ',';
206				$inFolder .= "\t";
207			} else {
208				$line = "\n\t\t\t\t".$item['type'].',';
209			}
210
211		$out .= $line;
212	}
213	$out = substr($out,0,strlen($out)-1);
214	global $jsmenu_style;
215	if (!isset($jsmenu_style)) $jsmenu_style = 'hbr';
216
217	$out .= "\n\t\t\t\t"."];".
218  "\n\t\t\t\t"."cmDraw ('CommandMenu', jsMenu, '$jsmenu_style', cmThemeOffice, 'ThemeOffice');".
219  "\n\t\t\t"."</script>"."\n\t\t";
220/* */
221
222  echo '<!-- common.lib.php : displayMenuTitle() -->'."\n";
223	echo '	<div align="center">
224		<table class="menu" cellspacing="0" cellpadding="0">
225		<tr><td>
226		<div id="CommandMenu">'.$out.'</div>
227		</td></tr>
228		</table>
229	</div>';
230}
231
232/**
233* Display pan header
234*
235* @param string $frame target where the header will be display
236* @param bool $withTitle display title
237*/
238function displayHeader($frame, $withTitle=true){
239	global $workDb;
240	$GlobalTheme = $GLOBALS['localtheme'].'/'.$frame;
241	if(is_readable('theme/'.$GLOBALS['localtheme'].'/menu/theme.css'))
242		$menuTheme = $GLOBALS['localtheme'];
243  else
244  	$menuTheme = 'default';
245	?>
246<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
247<html>
248	<head>
249	<title><?php echo $GLOBALS['traduct']->get(3)." ".$GLOBALS['SQLiteVersion'] ?></title>
250	<meta http-equiv="Pragma" content="no-cache">
251	<meta http-equiv="expires" content="0">
252	<meta http-equiv="content-type" content="text/html;charset=<?php echo $GLOBALS['charset'] ?>">
253	<style type="text/css">
254	/* to add later in all themes, now can be supersed by theme*/
255	table.menu { border-bottom: 1px solid black; width: 80%;}
256	table.menuButtons { width: 70%; }
257	td.viewPropTitle { border: 1px solid white; }
258	td.viewProp {	border: 1px solid white; }
259	table.home { width: 90%; text-align: center; }
260	td.boxtitle { width: 49%; text-align: center; }
261	td.boxtitlespace { width: 2%; font-size:0px; padding:0px; }
262	h5 { margin-bottom: 3px; font-size: 12px; }
263	table.query { width: 60%; margin-top: 10px; }
264	div.BrowseOptions { text-align:left; }
265	table.BrowseOption { text-align:left; }
266	div.TableOptions { text-align: left; }
267	table.Indexes { margin: 5px; width: 70%; border: thin grey solid; text-align: center; }
268	body { font-size: 12px; }
269  .Tip { font-size: 10px; background-color : Silver; }
270  .time { font-size: 10px; float: center }
271  div.Rights { border: 1px solid blue; }
272	</style>
273	<link href="theme/<?php echo $menuTheme?>/menu/theme.css" rel="stylesheet" type="text/css">
274	<link href="theme/<?php echo $GlobalTheme?>.css" rel="stylesheet" type="text/css">
275	<script src="include/function.js" type="text/javascript" language="javascript"></script>
276	<script src="include/JSCookMenu.js" type="text/javascript" language="javascript"></script>
277	<script src="theme/<?php echo $menuTheme?>/menu/theme.js" type="text/javascript" language="javascript"></script>
278<?php
279if(isset($GLOBALS['GlobalCalendar'])) echo $GLOBALS['GlobalCalendar']->get_load_files_code() . "\n";
280?>
281	</head>
282
283	<body>
284	<?php
285	if( ($frame == 'main') && ($withTitle) && ($GLOBALS['dbsel']) ){
286		echo '<h2 class="sqlmVersion">'.$GLOBALS['traduct']->get(131).' : <a href="main.php?dbsel='.$GLOBALS['dbsel'].'" style="text-decoration: none;"><span style="color: red;">'.$GLOBALS['tabInfoDb']['name'].'</span></a>';
287		foreach($GLOBALS['dbItems'] as $Items) {
288			if(!empty($GLOBALS[strtolower($Items)])) echo ' - '.$GLOBALS['itemTranslated'][$Items].' <a href="main.php?dbsel='.$GLOBALS['dbsel'].'&amp;'.strtolower($Items).'='.$GLOBALS[strtolower($Items)].'" style="text-decoration: none;" target="main"><span style="color: blue;">'.$GLOBALS[strtolower($Items)].'</span></a>';
289		}
290		echo '</h2>'."\n";
291		if($workDb->isReadOnly()){
292			if($workDb->isReadable()) $message = $GLOBALS['traduct']->get(155);
293			else $message = $GLOBALS['traduct']->get(232);
294			echo '<table width="80%" align="center"><tr><td style="font-size: 10px; border: 1px solid red; color: red; align: center;">'.$message.'</td></tr></table>';
295		}
296	}
297}
298
299/**
300* Display add form dependent of context
301*
302* @param string $type represent the context
303*/
304function formAddItem($type){
305	switch($type){
306		case 'Table':
307			echo '	<form name="add'.$type.'" action="main.php" method="POST" target="main">
308					<span style="font-size: 12px;">'.$GLOBALS['traduct']->get(43).' ==>&nbsp;'.$GLOBALS['traduct']->get(19).
309					' : <input type="text" name="TableName" size="20" class="small-input"> -
310					<input type="text" name="nbChamps" size="3" class="small-input">&nbsp;'.$GLOBALS['traduct']->get(44).'&nbsp;
311					<input class="button" type="submit" value="'.$GLOBALS['traduct']->get(69).'">
312					<input type="hidden" name="dbsel" value="'.$GLOBALS['dbsel'].'">
313					<input type="hidden" name="action" value="add_'.strtolower($type).'">
314					</span>
315					</form>';
316			break;
317		case 'View':
318			echo '<a href="main.php?dbsel='.$GLOBALS['dbsel'].'&amp;action=add_view" class="propItemTitle" target="main">&nbsp;&raquo;&nbsp;'.$GLOBALS['traduct']->get(87).'</a>';
319			break;
320		case 'Trigger':
321			echo '<a href="main.php?dbsel='.$GLOBALS['dbsel'].'&amp;action=add_trigger" class="propItemTitle" target="main">&nbsp;&raquo;&nbsp;'.$GLOBALS['traduct']->get(88).'</a>';
322			break;
323		case 'Function':
324			echo '<a href="main.php?dbsel='.$GLOBALS['dbsel'].'&amp;action=add_function" class="propItemTitle" target="main">&nbsp;&raquo;&nbsp;'.$GLOBALS['traduct']->get(89).'</a>';
325			break;
326	}
327}
328
329/**
330* Display query has been execute
331*
332* @param string $query
333* @param bool $withLink if true some links will be display
334*/
335function displayQuery($query, $withLink=true, $changesLines=''){
336	global $SQLiteManagerAuth;
337	if(empty($query) && isset($GLOBALS['DisplayQuery'])) $query = $GLOBALS['DisplayQuery'];
338	$linkBase = 'main.php?dbsel='.$GLOBALS['dbsel'].'&amp;table='.$GLOBALS['table'];
339	if($posLim = strpos($query, 'LIMIT')) {
340		$queryLink = substr($query, 0, ($posLim-1));
341	} else $queryLink = $query;
342	if(isset($GLOBALS['DbGrid']) && is_object($GLOBALS['DbGrid'])){
343		if(!empty($GLOBALS['DbGrid']->infoNav['start']) || !empty($GLOBALS['DbGrid']->infoNav['end']) || !empty($GLOBALS['DbGrid']->infoNav['all'])){
344			$infoNav = '<span style="font-size: 12px">'.$GLOBALS['traduct']->get(136).' '.$GLOBALS['DbGrid']->infoNav['start'].'-'.$GLOBALS['DbGrid']->infoNav['end'].'/'.$GLOBALS['DbGrid']->infoNav['all'].'&nbsp;&nbsp;</span>';
345		}
346	}
347	if(!isset($infoNav)) $infoNav = '';
348	if(WITH_AUTH && isset($SQLiteManagerAuth) &&  !$SQLiteManagerAuth->getAccess('execSQL')) $withLink = false;
349	$modifyLink 	= '[<a href="'.$linkBase.'&amp;action=sql&amp;sql_action=modify&amp;displayResult=&amp;DisplayQuery='.urlencode($queryLink).'" class="titleHeader" target="main">'.$GLOBALS['traduct']->get(14).'</a>]';
350	$explainLink 	= '[<a href="'.$linkBase.'&amp;action=sql&amp;sql_action=explain&amp;displayResult=1&amp;DisplayQuery='.urlencode($queryLink).'" class="titleHeader" target="main">'.$GLOBALS['traduct']->get(145).'</a>]';
351	$replayLink		= '[<a href="'.$linkBase.'&amp;action=sql&amp;displayResult=1&amp;DisplayQuery='.urlencode($queryLink).'" class="titleHeader" target="main">'.$GLOBALS['traduct']->get(223).'</a>]';
352	echo '
353		<table class="query" cellspacing="0" align="center">';
354	if($changesLines != '') echo '<tr><td bgcolor="#CCCCCC"><span class="sqlsyntaxe">&nbsp;'.$changesLines.' '.$GLOBALS['traduct']->get(71).'</span></td></tr>';
355	echo '		<tr>
356				<td class="queryTitle" bgcolor="'.$GLOBALS['displayQueryTitleColor'].'"  style="white-space: nowrap">
357					'.$GLOBALS['traduct']->get(90).' : '.(($withLink)? '&nbsp;&nbsp;'.$infoNav.$modifyLink.'&nbsp;'.$explainLink.'&nbsp;'.$replayLink : '' ).'</td></tr>
358			<tr><td class="queryBody" bgcolor="'.$GLOBALS['displayQueryBgColor'].'" style="white-space: nowrap"><div class="sqlsyntaxe">'.highlight_query($query).'</div></td></tr>
359		</table><br/>
360		';
361}
362
363/**
364* highlight query for a proch future!!
365*
366* @param string $query SQL command string
367*/
368function highlight_query($query){
369	include_once INCLUDE_LIB.'ParsingQuery.class.php';
370	$Colorize = new ParsingQuery($query, 1);
371	$Colorize->explodeQuery();
372	$Colorize->colorWordList();
373	return $Colorize->highlightQuery();
374}
375
376/**
377* Display function list for the insert / modify form
378*
379* @param string $champ name of the current champ
380*/
381function SQLiteFunctionList($champ, $userDefine=""){
382	$out = '<select name="funcs['.$champ.']">'."\n".'
383				<option value="" />'."\n";
384	foreach($GLOBALS['SQLfunction'] as $funct) $out .= '<option value="'.$funct.'">'.$funct.'</option>'."\n";
385	$tabUDF = $GLOBALS["workDb"]->functInfo;
386	$out .= '<option value="" />'."\n";
387	if(is_array($tabUDF)) foreach($tabUDF as $udfInfo) if($udfInfo['funct_type']==1) $out .= '<option value="'.$udfInfo['funct_name'].'">'.$udfInfo['funct_name'].'</option>';
388	$out .= '</select>';
389	return $out;
390}
391
392/**
393* Display operator list for the select form
394* @author Maur�cio M. Maia <mauricio.maia@gmail.com>
395*
396* @param string $champ name of the current champ
397*/
398function SQLiteSelectList($champ, $userDefine=""){
399	$out = '<select name="operats['.$champ.']">'."\n".'
400				<option value="" />'."\n";
401	foreach($GLOBALS['SQLselect'] as $operat) {
402		if(($operat != "fulltextsearch") || ALLOW_FULLSEARCH)
403		$out .= '<option value="'.$operat.'">'.$operat.'</option>'."\n";
404	}
405	$out .= '</select>';
406	return $out;
407}
408
409/**
410* Display input TYPE for the insert / modify form
411*
412* @param array $info data info for the current champ
413* @param mixed $data current value of the champ
414*/
415function SQLiteInputType($info, $data, $allowDefault=true, $allow_advanced=true){
416	static $tabIndex;
417	$allowBigger=false;
418	if(empty($tabIndex)) $tabIndex = 1;
419	if (!$allowBigger)
420		if(preg_match('#CHAR|TEXT|LOB#i', $info['type'])) {
421			preg_match('#\((.*)\)#', $info['type'], $length);
422			if(isset($length[1]) && $length[1]){
423				$maxlength = ' maxlength="'.$length[1].'"';
424				if($length[1]<=20) $maxlength = ' size="'.($length[1]+1).'" '.$maxlength;
425			} else $maxlength = ' size="20"';
426		} else $maxlength = ' size="20"';
427
428	if($allowDefault && $info['notnull'] && ($data == '')){
429		if(strstr($info['type'], '(')) {
430			$localType = trim(preg_replace('#\(.*\)#', '', $info['type']));
431		} else {
432			$localType = $info['type'];
433		}
434		if($info['dflt_value']!= '') $data = $info['dflt_value'];
435		elseif(isset($GLOBALS['SQLiteType'][$localType])) $data=$GLOBALS['SQLiteType'][$localType];
436	}
437	if((strtoupper(substr($info['type'],0,4))!='TEXT') && (strtoupper(substr($info['type'],0,4))!='BLOB')) {
438		if(JSCALENDAR_PATH && isset($GLOBALS['GlobalCalendar']) && (($info['type'] == 'DATE') || ($info['type'] == 'DATETIME'))) {
439	        $id = $GLOBALS['GlobalCalendar']->_gen_id();
440			$out = "<input size=\"15\"
441							id=\"".$GLOBALS['GlobalCalendar']->_field_id($id)."\"
442							type=\"text\"
443							class=\"text\"
444							name=\"valField[".$info['name']."]\"
445							value=\"".htmlentities($data, ENT_COMPAT, $GLOBALS['charset'])."\"".
446							$maxlength."
447							tabindex=".($tabIndex++).((!$info['notnull'])? "
448							onChange=\"if(this.value!='') setCheckBox('editElement', 'nullField[".$info['name']."]', false); else setCheckBox('editElement', 'nullField[".$info['name']."]', true);\"" : '' ).">";
449	        $out .= '<a href="#" id="'. $GLOBALS['GlobalCalendar']->_trigger_id($id) . '">' . '<img align="middle" border="0" src="' . $GLOBALS['GlobalCalendar']->calendar_lib_path . 'img.gif" alt="" /></a>';
450
451	        $options = array(	'inputField' => $GLOBALS['GlobalCalendar']->_field_id($id),
452	                            'button'     => $GLOBALS['GlobalCalendar']->_trigger_id($id));
453	        if($info['type'] == 'DATETIME') {
454	        	$GLOBALS['GlobalCalendar']->calendar_options['ifFormat'] = '%Y-%m-%d %H:%M';
455	        	$GLOBALS['GlobalCalendar']->calendar_options['daFormat'] = '%Y-%m-%d %H:%M';
456	        } else {
457	        	$GLOBALS['GlobalCalendar']->calendar_options['ifFormat'] = '%Y-%m-%d';
458	        	$GLOBALS['GlobalCalendar']->calendar_options['daFormat'] = '%Y-%m-%d';
459	        }
460	        $out .= $GLOBALS['GlobalCalendar']->_make_calendar($options);
461		} else {
462			$out = "<input type=\"text\" class=\"text\" name=\"valField[".$info['name']."]\" value=\"".htmlentities($data, ENT_COMPAT, $GLOBALS['charset'])."\"".$maxlength." tabindex=".($tabIndex++).((!$info['notnull'])? " onChange=\"if(this.value!='') setCheckBox('editElement', 'nullField[".$info['name']."]', false); else setCheckBox('editElement', 'nullField[".$info['name']."]', true);\"" : '' ).">";
463		}
464	} else {
465		if(ADVANCED_EDITOR && $allow_advanced && isset($GLOBALS['spaw_dir'])
466				&& (isset($_COOKIE["SQLiteManager_HTMLon"]) && !$_COOKIE["SQLiteManager_HTMLon"])){
467			$GLOBALS["spawEditorByName"][$info['name']] = new SPAW_Wysiwyg("valField[".$info['name']."]", $data, $GLOBALS["langSuffix"], SPAW_TOOLBAR_STYLE, '', (TEXTAREA_NB_COLS*6), (TEXAREA_NB_ROWS*16));
468			// Show SPAW Editor
469			$out = $GLOBALS["spawEditorByName"][$info['name']]->show();
470		} else {
471			$out = "<textarea name=\"valField[".$info['name']."]\" cols=".TEXTAREA_NB_COLS." rows=".TEXAREA_NB_ROWS." tabindex=".($tabIndex++).((!$info['notnull'])? " onChange=\"if(this.value!='') setCheckBox('editElement', 'nullField[".$info['name']."]', false); else setCheckBox('editElement', 'nullField[\'".$info['name']."\']', true);\"" : "" ).">".
472        		   htmlentities($data, ENT_NOQUOTES, $GLOBALS['charset']).
473		    		'</textarea>';
474		}
475
476	}
477	if(isset($out)) return $out;
478}
479
480/**
481* Return Available language
482*/
483function getAvailableLanguage(){
484	$out = "";
485	$listLangue = $GLOBALS['langueTranslated'];
486	natsort($listLangue);
487	while(list($lgId, $lgLib) = each($listLangue)){
488		$out .= '<option value="'.$lgId.'"'.(($GLOBALS['currentLangue']==$lgId)? ' selected="selected"' : '' ).'>'.(($GLOBALS['langueTranslated'][$lgId])? $GLOBALS['langueTranslated'][$lgId] : $lgLib).'</option>'."\n";
489	}
490	return $out;
491}
492
493/**
494* Return available theme
495*/
496function getAvailableTheme(){
497	$out = "";
498	//natsort($GLOBALS['themeTranslated']);
499	while(list($key,$themeId) = each($GLOBALS['availableTheme'])){
500		$themeLib = ($GLOBALS['themeTranslated'][$themeId])? $GLOBALS['themeTranslated'][$themeId] : $themeId;
501		$out .= '<option value="'.$themeId.'"'.(($GLOBALS['localtheme']==$themeId)? ' selected="selected"' : '' ).'>'.$themeLib.'</option>'."\n";
502	}
503	return $out;
504}
505
506/**
507* Apply a function from record form
508*
509* @param string $function the function name
510* @param mixed $value paramaters to apply function
511*/
512function applyFunction($function, $value){
513	$newValue = $value;
514	if(in_array($function, $GLOBALS['SQLfunction'])){
515		if($function == 'MD5') $newValue = "php('md5', $value)";
516		elseif($function == 'NOW') $newValue = "php('date', 'Y-m-d')";
517		else $newValue = strtolower($function)."($value)";
518	} else {
519		foreach($GLOBALS['workDb']->functInfo as $functInfo) {
520			if($function == $functInfo['funct_name']) $newValue = $function."('$value')";
521		}
522	}
523	return $newValue;
524}
525
526/**
527* Convert a hash table to GET url string
528*
529* @param array $tab table of key=>value
530*/
531function arrayToGet($tab){
532	$strOut = array();
533	while(list($var, $value) = each($tab)) $strOut[] = $var."=".$value;
534	return implode("&", $strOut);
535}
536
537/**
538* Cleaning field name, remove non authorized caractere
539*
540* @param string string is the field name
541* @param string $allow PCRE representation of caract�re authorized
542*/
543function cleanFieldName($string, $allow = 'a-z_0-9[[:space:]]'){
544	return preg_replace('#[^'.$allow.']#i', '', trim($string));
545}
546
547/**
548* Return a tab with all position of a caractere
549*
550* @param string $string haystack string
551* @param char $seperation needle string to find
552*/
553function strpos_all($string, $separator){
554	static $tabPos=array();
555	$pos = strpos($string, $separator);
556	if((string)$pos!=""){
557	if(count($tabPos)>=1) $addPrec = ($tabPos[count($tabPos)-1] +1);
558	else $addPrec = 0;
559		array_push($tabPos, ($pos + $addPrec));
560		$substring = substr($string, ($pos + 1), (strlen($string) - ($pos+1)) );
561		strpos_all($substring, $separator);
562	}
563	return $tabPos;
564}
565
566/**
567* Function for error handling
568* return PHP error from SQLite error to enhancement error displaying
569*/
570function phpSQLiteErrorHandling($errno, $errstr, $errfile, $errline){
571	preg_match('/:(.*)/', $errstr, $errorResult);
572	if(isset($errorResult[1])) $GLOBALS['phpSQLiteError'] = $errorResult[1];
573}
574
575/**
576* Create SELECT from array value
577*
578* @param array $tabData array("ID"=>"VALUE", ...)
579* @param string form $varNamevar name
580* @param int $varValue value to selected
581* @return string HTML out
582*/
583function createSelect($tabData, $varName, $varValue){
584	$out = '';
585	if(isset($tabData) && !empty($tabData)){
586		$out .= '<SELECT name="'.$varName.'">'."\n".'<option value="" />'."\n";
587		foreach($tabData as $id=>$value) $out .= '<option value="'.$id.'"'.(($id==$varValue)? ' selected="selected"' : '' ).'>'.$value.'</option>'."\n";
588		$out .='</SELECT>'."\n";
589	}
590	return $out;
591}
592
593/**
594* Send image HTML!
595* if exist img filename in theme, this is display also the './pics/'.$filename is display
596*
597* @param string $src filename
598* @param sring $alt string is display when mouse over
599* @param int $border image border size in px
600* @param int $width width size in px
601* @param int height heigh size in px
602* @return string img HTML tag
603*/
604function displayPics($src, $alt="", $border=0, $width="", $height=""){
605	$filename = basename($src);
606	if(file_exists('./theme/'.$GLOBALS['localtheme'].'/pics/'.$filename)){
607		$imgSrc = './theme/'.$GLOBALS['localtheme'].'/pics/'.$filename;
608	} else {
609		$imgSrc = './theme/default/pics/'.$filename;
610	}
611	return '<img src="'.$imgSrc.'" border="'.$border.'" alt="'.$alt.'" title="'.$alt.'"'.(($width)? ' width='.$width : '' ).(($height)? ' height='.$height : '' ).'>';
612}
613
614/**
615*  Add brackets when spaces in objects, remove existing ones for concatenations [table].[col] > [table.col]
616*
617* @param string $object object with or without bracket
618* @return string object with brackets
619*/
620function brackets($object,$quotes=true){
621	$object = preg_replace('#\[|\]#','',$object);
622	if (strstr($object,' ')) {
623		$object = "[$object]";
624	}
625	if($quotes)
626	    $object = quotes($object);
627
628	return $object;
629}
630
631/**
632*  Add quotes on values, and support for Like '%text%'
633*
634* @param string $text string value
635* @param string $like string add like %
636* @return escaped string with quotes
637*/
638function quotes($text,$like=''){
639	if (substr($like,0,1)=='%') $text  = '%'+$text;
640	if (substr($like,1,1)=='%') $text .= '%';
641	$out = "'".$GLOBALS['db']->escape($text)."'";
642	return $out;
643}
644
645function SQLiteStripSlashes($str) {
646    if (get_magic_quotes_gpc())
647        $str = stripslashes($str);
648
649    return $str;
650}
651
652function unquote($s, $quotes = "''``", &$left_quote=null) {
653    if (strlen($s) < 2) {
654        $left_quote = false;
655        return $s;
656    }
657    $q = substr($s, 0, 1);
658    $qleft = strpos($quotes, $q);
659    if ($qleft === false) {
660        $left_quote = false;
661        return $s;
662    }
663    $qright = $quotes{$qleft + 1};
664    if (substr($s, -1) === $qright) {
665        $left_quote = $quotes{$qleft};
666        return substr($s, 1, -1);
667    }
668    return $s;
669}
670?>
671