1 <?php
2 /*
3 This code is part of GOsa (https://gosa.gonicus.de)
4 Copyright (C) 2003 Cajus Pollmeier, Fabian Hickert
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
24 /* Basic setup, remove eventually registered sessions */
25 require_once ("../include/php_setup.inc");
26 require_once ("../include/functions.inc");
27 session_start ();
28 error_reporting(E_ALL);
29 /* Logged in? Simple security check */
30 if (!isset($_SESSION['ui'])){
31 gosa_log ("Error: helpviewer.php called without session");
32 echo "<b>"._("Help is not available if you are not logged in.")."</b>";
33 exit;
34 }
37 /* Set template compile directory */
38 $config= $_SESSION['config'];
39 if (isset ($config->data['MAIN']['COMPILE'])){
40 $smarty->compile_dir= $config->data['MAIN']['COMPILE'];
41 } else {
42 $smarty->compile_dir= '/var/spool/gosa/';
43 }
45 /* Language setup */
46 if ($config->data['MAIN']['LANG'] == ""){
47 $lang= get_browser_language();
48 } else {
49 $lang= $config->data['MAIN']['LANG'];
50 }
51 $lang.=".UTF-8";
52 putenv("LANGUAGE=");
53 putenv("LANG=$lang");
54 setlocale(LC_ALL, $lang);
55 $GLOBALS['t_language']= $lang;
56 $GLOBALS['t_gettext_message_dir'] = $BASE_DIR.'/locale/';
58 /* Set the text domain as 'messages' */
59 $domain = 'messages';
60 bindtextdomain($domain, "$BASE_DIR/locale");
61 textdomain($domain);
62 @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, $lang, "Setting language to");
64 /* Get plugin list */
65 $plist= $_SESSION['plist'];
67 /*
68 ##################
69 My PART ^^
70 ##################
71 */
73 //set_error_handler("myone");
74 $helpdir = "../doc/guide/admin/en/manual_gosa_en/"; // Folder to use for help files
75 $defaultpage = "index.html"; // alternative file, shown on error, or on first call
76 $prefix = "node"; // Prefix of the generated help files
77 $suffix = ".html"; // Suffix of the generated helpfiles
78 $maxresults = 10; // max number of results shown in result list
79 $minwordlength = 3; // Word less than 3 chars will be dropped in search
80 $allowed_chars_in_searchword = "'[^a-z0-9 %_-]'i"; // Remove all chars that would disturb our search like < or > ...
81 $pre_mark = "<b><u><i>" ; // Sign words with this
82 $suf_mark = "</i></u></b>"; // and this
84 // Only for testing delete this if everything works fine
85 function myone($par1,$par2,$par3,$par3)
86 {
87 print "<br>Seite : ".$par1."<br>Name : ".$par2."<br>Seite : ".$par3."<br>Zeile : ".$par3;
88 }
90 /* Define which tags musst be delete, header, navigation, banner */
91 #fixme Theres a better method to handle replacment , preg_replace can handle arrays , this, would be little easier
92 $i=0;
93 $replacements=array();
94 $replacements['range'][$i]['from'] = "@<!DOC.*<BODY >@si";
95 $replacements['range'][$i]['to'] = "";
96 $i++;
97 $replacements['range'][$i]['from'] = "@<DIV[^>]*?>.*?DIV>@si";
98 $replacements['range'][$i]['to'] = "";
99 $i++;
100 $replacements['range'][$i]['from'] = "'<code.*code>'";
101 $replacements['range'][$i]['to'] = "";
102 $i++;
103 $replacements['range'][$i]['from'] = "/<HR>/";
104 $replacements['range'][$i]['to'] = "";
105 $i++;
106 $replacements['range'][$i]['from'] = "@<ADDRESS[^>]*?>.*?ADDRESS>@si";
107 $replacements['range'][$i]['to'] = "";
108 $i++;
109 $replacements['range'][$i]['from'] = "@<\/BODY[^>]*?>.*?HTML>@si";
110 $replacements['range'][$i]['to'] = "";
111 $i++;
112 /* Bsp . : Replace Table Head to specified tableheader */
113 $replacements['range'][$i]['from'] = "'<TABLE.*>'";
114 $replacements['range'][$i]['to'] = "<table border=0 cellspacing=1 bgcolor=\"#999999\" width=\"95%\" align=\"center\" >" ;
116 /* Default pages */
117 $backward =$defaultpage;
118 $index =$defaultpage;
119 $forward ="node1.html";
121 /*
122 Here it begins, the real function, above only definitions
123 */
124 /* We prepare to search, all Document for the given keyword */
125 if(isset($_POST['search'])){
127 /* Get Keyword */
128 $keyword = $_POST['search_string'];
130 /* Save Keyword to be able to show last searched word in template */
131 $_SESSION['search_string']= $keyword;
133 /* Read all files with contents*/
134 /* |Folder="/var/ww...",
135 | |Fileprefix="node"
136 | | |Filesuffix=".html"
137 | | | |WithoutContent=false(This means : read content)
138 | | | | |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
139 $arr = readfiles($helpdir,$prefix,$suffix,false,$singlepage=false);
141 /* Create Searchresult for our Keyword(s) */
142 $res = search($arr,$keyword);
144 /* Tell smarty which pages to use for backward forwa.. */
145 $smarty->assign("backward",$backward);
146 $smarty->assign("index" ,$index);
147 $smarty->assign("forward" ,$forward);
149 /* Tell smarty the Keyword, to show it in the input field again */
150 $smarty->assign("search_string",$keyword);
152 /* Create result list */
153 $smarty->assign("help_contents",searchlist($arr,$res,$maxresults));
155 /* Output html ...*/
156 $header= "<!-- headers.tpl-->".$smarty->fetch(get_template_path('headers.tpl'));
157 $display= $header.$smarty->fetch(get_template_path('help.tpl'));
158 echo $display;
160 /*
161 Don't search, only show selected page
162 */
163 }else{
165 /* present last searched word(s)*/
166 $smarty->assign("search_string",$_SESSION['search_string']);
168 /* Read all files, prepare to serach */
169 $helppages = readfiles("../doc/guide/admin/en/manual_gosa_en/",$prefix,$suffix,true);
171 /* Get transmitted page */
172 if(isset($_GET['pg'])){
173 $page = $_GET['pg'];
174 }
176 /* test if this page exists, in our array of files */
177 if((!isset($helppages[$page]))&&($page!=$defaultpage))
178 {
179 //print "Requested helppage is unknown, redirekted to index"; // For debugging only
180 $page = $defaultpage;
181 }
183 /* Check forward backward, funtionality*/
184 if($page != $defaultpage)
185 {
186 /* Extract Number of node page */
187 $number = str_replace($prefix,"",str_replace($suffix,"",$page));
189 /* Check if we can switch forward and/or backward*/
190 $bck = $prefix.($number-1).$suffix;
191 $fck = $prefix.($number+1).$suffix;
193 /* backward page exists ?, so allow it*/
194 if((isset($helppages[$bck]))) {
195 $backward = $bck;
196 }
198 /* forward exists ?*/
199 if((isset($helppages[$fck]))) {
200 $forward = $fck;
201 }
202 }
204 $help_contents=readfiles($helpdir,$prefix,$suffix,false,$page);
206 /* Mark last searched words */
207 if($_GET['mark']){
208 $marks = ($_SESSION['lastresults']) ;
209 $help_contents = markup_page($help_contents[$page]['content'],$marks[$page]);
210 $help_contents=remove_unwanted_tags($help_contents,$replacements);
211 }else{
212 $help_contents=remove_unwanted_tags($help_contents[$page]['content'],$replacements);
213 }
216 $smarty->assign("help_contents",$help_contents);
218 /* Define our own navigation pages */
219 $smarty->assign("backward",$backward);
220 $smarty->assign("index" ,$index);
221 $smarty->assign("forward" ,$forward);
223 /* Fill page */
224 $header= "<!-- headers.tpl-->".$smarty->fetch(get_template_path('headers.tpl'));
225 $display= $header.$smarty->fetch(get_template_path('help.tpl'));
226 echo $display;
227 }
229 /*******************************************
230 Only function definition will follow here
231 #fixme Exclude function to seperate file
232 /*******************************************
234 /* Reads all files in specified directory with contents an some inforations about the file */
235 /* Read all files with contents*/
236 /* |Folder="/var/ww...",
237 | |Fileprefix="node"
238 | | |Filesuffix=".html"
239 | | | |WithoutContent=false(This means : read content)
240 | | | | |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
241 function readfiles($basedir,$prefix,$suffix,$onlyIndex,$singlepage=false)
242 {
243 global $replacements;
245 $str = array(); // Temporary variable
246 $cnt = 0; // Array index creation
247 $file = ""; // Contains Filename
249 $dir = opendir($basedir);
251 $str['global']['start'] = $cnt; // collect basic informations - Startpage
252 $str['global']['basedir'] = $basedir; // collect basic informations - Basedirectory
254 /* Startime for Benchmark */
255 $start = (time()+microtime());
257 /* if singlepage == false -> Get all pages, */
258 if(!$singlepage) {
260 /* While theres is an unreaded file in our resource */
261 while (($file = readdir($dir)) !== false) {
263 /* Filter all files which arn't intressting */
264 if((strstr($file,$suffix))&&($file!=".")&&($file!="..")&&(strstr($file,$prefix))){
266 /* Collect informations */
267 $str[$file]=array();
268 $str[$file]['name'] = $file;
269 $str[$file]['size'] = filesize($basedir.$file);
271 /* Readfile conent too ? */
272 if(!$onlyIndex){
273 $str[$file]['content']= remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
274 }
276 /* Include file status, for debugging, not used in script yet */
277 $str[$file]['stat'] = stat($basedir.$file);
278 $cnt++;
279 }
280 }
282 /* Only get on file*/
283 }else{
284 /* Pages read = 1 */
285 $cnt = 1;
287 /* Prepare result*/
288 $file = $singlepage;
289 $str[$file] = array();
290 $str[$file]['name'] = $file;
291 $str[$file]['size'] = filesize($basedir.$file);
293 /* If onlyIndex == true skip reading content */
294 if(!$onlyIndex){
295 $str[$file]['content']= remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
296 }
298 /* Include file status, for debugging, not used in script yet */
299 $str[$file]['stat'] = stat($basedir.$file);
300 }
302 /* Sort to right order */
303 asort($str);
305 /* Endtime for Benchmark*/
306 $end = (time()+microtime());
307 $str['global']['cmptime'] = $end-$start;
309 /* Number of pages readed */
310 $str['global']['numpages']= $cnt;
311 closedir($dir);
312 return($str);
313 }
315 /* Read filecontent */
316 function getcontents($file)
317 {
318 $str = "" ; // Temporary variable for file contents
319 $tmp = "" ; // Temporary varibale for partitial file contents
321 /* open file and read*/
322 $fp = fopen($file,"r");
323 if($fp) {
324 while($tmp = fread($fp,512))
325 {
326 $str.= $tmp;
327 }
328 }else{
329 return(false);
330 }
331 return($str);
332 }
334 /*Remove tags */
335 function remove_unwanted_tags($str,$replacements)
336 {
337 #fixme This solution is ... ARRG
338 foreach($replacements['range'] as $var)
339 {
340 $str=preg_replace($var['from'],$var['to'],$str);
341 }
342 return($str);
343 }
345 /*Converts the all links to specified path, is needed to get simple navigation */
346 function linkwrapper($str,$link)
347 {
348 $str=str_replace("HREF=\"","href=\"".$link."?pg=",$str);
349 return($str);
350 }
352 /* Search content */
353 function search($arr,$word)
354 {
355 global $minwordlength,$allowed_chars_in_searchword;
356 /* Prepare Vars */
357 $result =array(); // Search result, filename, + hits + hits per word + matches
358 $words =array(); // Temporary searchword handling
359 $useablewords =array(); // Temporary searchword handling
360 $tryword = ""; // Temporary searchword handling
361 $result['global']['maxhit'] = 0;
362 unset($_SESSION['lastresults']);
363 unset($_SESSION['parsed_search_keyword']);
365 /* prepare searchwords */
366 $word = trim($word);
368 /* Filter all unusable chars */
369 $word = preg_replace($allowed_chars_in_searchword,"",$word);
370 $words = split(" ",str_replace("+"," ",$word));
372 /* Check all wordlengths */
373 foreach($words as $tryword){
374 $tryword = trim($tryword);
376 /* Filter words smaler than 3 chars */
377 if(strlen($tryword)>=$minwordlength) {
378 $_SESSION['parsed_search_keyword'].=$tryword." ";
379 $useablewords[]=$tryword;
380 }
381 }
383 /* Use words to search the content */
384 foreach($arr as $key=>$val)
385 {
386 /* overallhits counts hits per page */
387 $overallhits=0;
389 /* Search all words */
390 foreach($useablewords as $word)
391 {
392 /* Skip key global, it contains no file data - it is a summary info*/
393 if($key!="global")
394 {
395 /* Get all hits for the word in $matches*/
396 preg_match_all("/".$word."/i",$arr[$key]['content'], $matches,PREG_OFFSET_CAPTURE);
398 /* Filter in Tag results*/
399 if(count($matches[0])){
400 foreach($matches[0] as $num=>$hit){
401 if(is_in_tag($arr[$key]['content'],$hit[1])) {
402 unset($matches[0][$num]);
403 }
404 }
405 }
407 /* Count matches */
408 $overallhits=$overallhits + count($matches[0]);
410 /* Save collected data */
411 $result[$key]['hits'][$word] = count($matches[0]);
412 $result[$key]['hits']['overall']= $overallhits;
414 /* Save max hits for page */
415 if($overallhits > $result['global']['maxhit']){
416 $result['global']['maxhit']=$overallhits;
417 }
419 /* Add results for word to return value*/
420 $result[$key]['match'][$word]=array();
421 $result[$key]['match'][$word]=$matches[0];
422 }
423 }
424 }
426 /* Save result in Session, so we can mark words later, or go back to search, without searching again*/
427 $_SESSION['lastresults'] = $result;
428 return($result);
429 }
431 /* Detect 10 Best result entries, sort and call createResultEntry to create HTML output for complete list */
432 function searchlist($arr,$res,$maxresults)
433 {
434 $global = $res['global'];
435 $topten = array(); // To detect 10 best solutions
436 $ret = ""; // return value
437 unset($res['global']);
439 /* Detect 10 best Sites */
440 foreach($res as $key=>$val){
442 /* Skip results with no hits */
443 if($val['hits']['overall']>0){
444 $topten[$key] = $val['hits']['overall'];
445 }
446 }
448 /* Sort by hit position in content, to easier mark words */
449 asort($topten);
450 $topten = array_reverse($topten);
451 $topten = (array_slice($topten,0,$maxresults));
453 /* We have a result, an array with all content, an array with hits and position and we have the 10 best hits */
454 /* Foreach */
455 foreach($topten as $name => $hits) {
456 $ret.= createResultEntry($arr[$name],$res[$name],$name,$global['maxhit']);
457 }
459 /* appending footer message for resultlist */
460 $ret.= "<br> ".count($topten)." - "._("Results for your search with the keyword")." <b>".htmlentities($_SESSION['search_string'])."</b>"._(" interpreted as ")."<b>".$_SESSION['parsed_search_keyword']."</b>";
462 return($ret);
463 }
465 /* This function marks a string with the given search result for this string*/
466 function markup_page($arr,$res)
467 {
468 global $pre_mark,$suf_mark;
469 $ret = ""; // return value
470 $repl = array();
471 $posadd = 0;
473 foreach($res['match'] as $word => $matches) {
474 foreach($matches as $matchnr=>$match) {
475 $repl[$match[1]]=$match[0];
476 }
477 }
479 ksort($repl);
481 foreach($repl as $position=>$word) {
482 $pos1 = strlen($arr);
483 $arr= markword($arr,($position+$posadd),$word,$pre_mark,$suf_mark);
484 $pos2 = strlen($arr);
485 $posadd =$posadd + ($pos2 - $pos1);
486 }
487 return($arr);
488 }
490 /* This function marks a single word with the specified prefix and suffix */
491 function markword($string,$position,$word,$prefix,$suffix)
492 {
493 $wordlength = strlen($word);
494 $wholelength = strlen($string);
496 $first = substr($string,0,$position);
497 $last = substr($string,($position+$wordlength),$wholelength);
499 return($first.$prefix.$word.$suffix.$last);
500 }
503 /* Creates HTML output for a single search result entry */
504 function createResultEntry($entry,$res,$name,$max)
505 {
506 $percentage = (int)(($res['hits']['overall'] / $max) * 100) ;
508 $str = "<b><a href=\"?pg=".$name."&mark=1\">".$percentage."% "._("hit rate in following file ").$name."</a></b><br>" ;
509 $str.= substr(strip_tags($entry['content']),0,200);
510 $str.= "<hr>";
512 return($str);
513 }
515 /*Simple function to detect if we prepare to change a tag or visible text */
516 function is_in_tag($string,$pos)
517 {
518 $pos1 = strpos($string,"<",$pos);
519 $pos2 = strpos($string,">",$pos);
521 if ($pos1 > $pos2) {
522 return(true);
523 }else{
524 return(false);
525 }
526 }
528 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
529 ?>