Code

Much better now, Top ten filtered
[gosa.git] / html / helpviewer.php
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2003  Cajus Pollmeier
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  */
21 /* Basic setup, remove eventually registered sessions */
22 require_once ("../include/php_setup.inc");
23 require_once ("../include/functions.inc");
24 session_start ();
25 error_reporting(E_ALL);
26 /* Logged in? Simple security check */
27 if (!isset($_SESSION['ui'])){
28   gosa_log ("Error: helpviewer.php called without session");
29   echo "<b>"._("Help is not available if you are not logged in.")."</b>";
30   exit;
31 }
34 /* Set template compile directory */
35 $config= $_SESSION['config'];
36 if (isset ($config->data['MAIN']['COMPILE'])){
37   $smarty->compile_dir= $config->data['MAIN']['COMPILE'];
38 } else {
39   $smarty->compile_dir= '/var/spool/gosa/';
40 }
42 /* Language setup */
43 if ($config->data['MAIN']['LANG'] == ""){
44   $lang= get_browser_language();
45 } else {
46   $lang= $config->data['MAIN']['LANG'];
47 }
48 $lang.=".UTF-8";
49 putenv("LANGUAGE=");
50 putenv("LANG=$lang");
51 setlocale(LC_ALL, $lang);
52 $GLOBALS['t_language']= $lang;
53 $GLOBALS['t_gettext_message_dir'] = $BASE_DIR.'/locale/';
55 /* Set the text domain as 'messages' */
56 $domain = 'messages';
57 bindtextdomain($domain, "$BASE_DIR/locale");
58 textdomain($domain);
59 @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, $lang, "Setting language to");
61 /* Get plugin list */
62 $plist= $_SESSION['plist'];
64 /*
65 ##################
66 My PART ^^
67 ##################
69  */
70 //set_error_handler("myone");
71 $helpdir      = "../doc/guide/admin/en/manual_gosa_en/";
72 $defaultpage  = "index.html";
73 $prefix       = "node";
74 $suffix       = ".html";
75 $maxresults   = 10;
76 $minwordlength= 3;
79 function myone($par1,$par2,$par3,$par3)
80 {
81   print "<br>Seite : ".$par1."<br>Name : ".$par2."<br>Seite : ".$par3."<br>Zeile : ".$par3;
82 }
84 /* Define which tags musst be delete, header, navigation, banner */
85 $i=0;
86 $replacements=array();
87 $replacements['range'][$i]['from']    = "/<!DOC.*<BODY >/";
88 $replacements['range'][$i]['to']      = "";
89 $i++;
90 $replacements['range'][$i]['from']  = "@<DIV[^>]*?>.*?DIV>@si";
91 $replacements['range'][$i]['to']      = "";
92 $i++;
93 $replacements['range'][$i]['from']  = "/<HR>/";
94 $replacements['range'][$i]['to']      = "";
95 $i++;
96 $replacements['range'][$i]['from']  = "@<ADDRESS[^>]*?>.*?ADDRESS>@si";
97 $replacements['range'][$i]['to']      = "";
98 $i++;
99 $replacements['range'][$i]['from']  = "/<\/BODY.*>/";
100 $replacements['range'][$i]['to']      = "";
101 $i++;
103 /* Bsp . : Replace  Table Head to specified tableheader */ 
104 $replacements['range'][$i]['from']  = "@<TABLE[^>]*?>.*?>@si";
105 $replacements['range'][$i]['to']    = "<table border=0 cellspacing=1 bgcolor=\"#999999\" width=\"95%\" align=\"center\" >" ;
107 /* Default pages */
108 $backward =$defaultpage;
109 $index    =$defaultpage;
110 $forward  ="node1.html";
112 /*
113    Here it begins, the real function, above only definitions
114  */
115 /* We prepare to search, all Document for the given keyword */
116 if(isset($_POST['search'])){
118   /* Get Keyword */
119   $keyword = $_POST['search_string'];  
120   
121   /* Save Keyword to be able to show last searched word in template */
122   $_SESSION['search_string']= $keyword;
124   /* Read all files with contents*/
125   /*               |Folder="/var/ww...", 
126                    |        |Fileprefix="node"
127                    |        |       |Filesuffix=".html"
128                    |        |       |       |WithoutContent=false(This means : read content)
129                    |        |       |       |     |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
130   $arr = readfiles($helpdir,$prefix,$suffix,false,$singlepage=false);
132   /* Create Searchresult for our Keyword(s) */
133   $res = search($arr,$keyword); 
135   /* Tell smarty which pages to use for backward forwa.. */
136   $smarty->assign("backward",$backward);
137   $smarty->assign("index"   ,$index);
138   $smarty->assign("forward" ,$forward);
140   /* Tell smarty the Keyword, to show it in the input field again */
141   $smarty->assign("search_string",$keyword);
143   /* Create result list */
144   $smarty->assign("help_contents",searchlist($arr,$res,$maxresults));
145   
146   /* Output html ...*/
147   $header= "<!-- headers.tpl-->".$smarty->fetch(get_template_path('headers.tpl'));
148   $display= $header.$smarty->fetch(get_template_path('help.tpl'));
149   echo $display;
151 /*
152   Don't search, only show selected page
153 */
154 }else{
156   /* present last searched word(s)*/
157   $smarty->assign("search_string",$_SESSION['search_string']);
159   /* Read all files, prepare to serach */
160   $helppages = readfiles("../doc/guide/admin/en/manual_gosa_en/",$prefix,$suffix,true);
162   /* Get transmitted page */
163   if(isset($_GET['pg'])){
164     $page = $_GET['pg'];
165   }
166   
167   /* test if this page exists, in our array of files */
168   if((!isset($helppages[$page]))&&($page!=$defaultpage))
169   {
170     print "Requested helppage is unknown, redirekted to index";
171     $page = $defaultpage;
172   }
174   /* Check forward backward, funtionality*/
175   if($page != $defaultpage)
176   {
177     /* Extract Number of node page */
178     $number = str_replace($prefix,"",str_replace($suffix,"",$page));
180     /* Check if we can switch forward and/or backward*/ 
181     $bck = $prefix.($number-1).$suffix;
182     $fck = $prefix.($number+1).$suffix;
184     /* backward page exists ?, so allow it*/
185     if((isset($helppages[$bck]))) {
186       $backward = $bck;
187     }
189     /* forward exists ?*/
190     if((isset($helppages[$fck])))  {
191       $forward  = $fck;
192     }
193   }
195   $help_contents=readfiles($helpdir,$prefix,$suffix,false,$page);
197   /* Mark last searched words */
198   if($_GET['mark']){
199     $marks = ($_SESSION['lastresults']) ; 
200     $help_contents = markup_page($help_contents[$page]['content'],$marks[$page]);
201     $help_contents=remove_unwanted_tags($help_contents,$replacements);  
202   }else{
203     $help_contents=remove_unwanted_tags($help_contents[$page]['content'],$replacements);
204   }
207   $smarty->assign("help_contents",$help_contents);
209   /* Define our own navigation pages */
210   $smarty->assign("backward",$backward);
211   $smarty->assign("index"   ,$index);
212   $smarty->assign("forward" ,$forward);
214   /* Fill page */
215   $header= "<!-- headers.tpl-->".$smarty->fetch(get_template_path('headers.tpl'));
216   $display= $header.$smarty->fetch(get_template_path('help.tpl'));
217   echo $display;
222 /* 
223    Only function definition will follow here
224 /*
228 /* Reads all files in specified directory with contents an some inforations about the file */
229   /* Read all files with contents*/
230   /*               |Folder="/var/ww...",
231                    |        |Fileprefix="node"
232                    |        |       |Filesuffix=".html"
233                    |        |       |       |WithoutContent=false(This means : read content)
234                    |        |       |       |          |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
235 function readfiles($basedir,$prefix,$suffix,$onlyIndex,$singlepage=false)
237   global $replacements;
239   $str    = array();  // Temporary variable
240   $cnt    = 0;        // Array index creation
241   $file   = "";       // Contains Filename
243   $dir = opendir($basedir);
245   $str['global']['start']       = $cnt;     // collect basic informations - Startpage
246   $str['global']['basedir']     = $basedir; // collect basic informations - Basedirectory
248   /* Startime for Benchmark */ 
249   $start =   (time()+microtime());
251   /* if singlepage == false -> Get all pages, */
252   if(!$singlepage) {
254     /* While theres is an unreaded file in our resource */
255     while (($file = readdir($dir)) !== false) {
256       
257       /* Filter all files which arn't intressting */
258       if((strstr($file,$suffix))&&($file!=".")&&($file!="..")&&(strstr($file,$prefix))){
259        
260         /* Collect informations */
261         $str[$file]=array();
262         $str[$file]['name']   = $file;
263         $str[$file]['size']   = filesize($basedir.$file);
264       
265         /* Readfile conent too ? */
266         if(!$onlyIndex){
267           $str[$file]['content']= remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
268         }
270         /* Include file status, for debugging, not used in script yet */
271         $str[$file]['stat']   = stat($basedir.$file);
272         $cnt++;
273       }
274     }
276   /* Only get on file*/
277   }else{
278     /* Pages read = 1 */       
279     $cnt = 1;
281     /* Prepare result*/
282     $file                 = $singlepage;
283     $str[$file]           = array();
284     $str[$file]['name']   = $file;
285     $str[$file]['size']   = filesize($basedir.$file);
286   
287     /* If onlyIndex == true skip reading content */
288     if(!$onlyIndex){
289       $str[$file]['content']= remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
290     }
291     
292     /* Include file status, for debugging, not used in script yet */
293     $str[$file]['stat']   = stat($basedir.$file);
294   }
296   /* Sort to  right order */
297   asort($str);
299   /* Endtime for Benchmark*/
300   $end = (time()+microtime());
301   $str['global']['cmptime'] = $end-$start;
303   /* Number of pages readed */
304   $str['global']['numpages']= $cnt;
305   closedir($dir);
306   return($str);
309 /* Read filecontent */
310 function getcontents($file)
312   $str = "" ;   // Temporary variable for file contents 
313   $tmp = "" ;   // Temporary varibale for partitial file contents
314   
315   /* open file and read*/
316   $fp = fopen($file,"r");
317   if($fp) {
318     while($tmp = fread($fp,512))
319     {
320       $str.=  $tmp;
321     }
322   }else{
323     return(false);
324   }
325   return($str);
328 /*Remove tags */
329 function remove_unwanted_tags($str,$replacements)
331   #fixme This solution is ....
332   $str=str_replace("\n","||WasBr||",$str);
333   foreach($replacements['range'] as $var)
334   {
335     $str=preg_replace($var['from'],$var['to'],$str);
336   }
338   $str=str_replace("||WasBr||","\n",$str);
339   return($str);
342 /*Converts the all links to specified path, is needed to get simple navigation */
343 function linkwrapper($str,$link)
345   $str=str_replace("HREF=\"","href=\"".$link."?pg=",$str);  
346   return($str);
351 function search($arr,$word)
353   global $minwordlength;
354   /* Prepare Vars */ 
355   $result                     =array(); // Search result, filename, + hits + hits per word + matches 
356   $words                      =array(); // Temporary searchword handling
357   $useablewords               =array(); // Temporary searchword handling
358   $tryword                    = "";     // Temporary searchword handling
359   $result['global']['maxhit'] = 0;
360   unset($_SESSION['lastresults']);
361   unset($_SESSION['parsed_search_keyword']);
363   /* prepare searchwords */
364   $word   = trim($word);
366   /* Filter all unusable chars */
367   $word   = preg_replace("[^a-z0-9_+% ]","",$word);
368   $words  = split(" ",str_replace("+"," ",$word));
370   
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   
385   /* Use words to search the content */
386   foreach($arr as $key=>$val)
387   {
388     /* overallhits counts hits per page */
389     $overallhits=0;
390   
391     /* Search all words */
392     foreach($useablewords as $word)
393     {
394       /* Skip key global, it contains no file data - it is a summary info*/
395       if($key!="global")
396       {
397         /* Get all hits for the word in $matches*/
398         preg_match_all("/".$word."/i",$arr[$key]['content'], $matches,PREG_OFFSET_CAPTURE);
400         /* Count matches */
401         $overallhits=$overallhits + count($matches[0]);    
403         /* Save collected data */
404         $result[$key]['hits'][$word]    = count($matches[0]); 
405         $result[$key]['hits']['overall']= $overallhits;  
407         /* Save max hits for page */
408         if($overallhits > $result['global']['maxhit']){
409           $result['global']['maxhit']=$overallhits;  
410         }
411   
412         /* Add results for word to return value*/
413         $result[$key]['match'][$word]=array();
414         $result[$key]['match'][$word]=$matches[0];
415       }
416     }
417   }
418   
419   /* Save result in Session, so we can mark words later, or go back to search, without searching again*/
420   $_SESSION['lastresults'] = $result;
421   return($result);
424 /* Detect 10 Best result entries, sort and call createResultEntry to create HTML output for  complete list */
425 function searchlist($arr,$res,$maxresults)
427   $global = $res['global'];
428   $topten = array();        // To detect 10 best solutions
429   $ret    = "";             // return value
430   unset($res['global']);
432   /* Detect 10 best Sites */
433   foreach($res as $key=>$val){
434     
435     /* Skip results with no hits */
436     if($val['hits']['overall']>0){
437       $topten[$key] = $val['hits']['overall']; 
438     }
439   }
441   /* Sort by hit position in content, to easier mark words */
442   asort($topten);
443   $topten = array_reverse($topten);
444   $topten = (array_slice($topten,0,$maxresults));
446   /* We have a result, an array with all content, an array with hits and position and we have the 10 best hits */
447   /* Foreach */  
448   foreach($topten as $name => $hits)  {
449     $ret.= createResultEntry($arr[$name],$res[$name],$name,$global['maxhit']);    
450   }
451   
452   /* appending footer message for resultlist */
453   $ret.= "<br> ".count($topten)." Results for your search with the keyword <b>".$_SESSION['search_string']."</b> it is interpreted as <b>".$_SESSION['parsed_search_keyword']."</b>";
454   
455   return($ret);
458 /* This function marks a string with the given search result for this string*/
459 function markup_page($arr,$res)
461   $ret    = "";             // return value
462   $pre    = "<b><u><i>" ;
463   $suf    = "</i></u></b>"; 
464   $repl   = array();
465   $posadd = 0;
467   foreach($res['match'] as $word => $matches)   {
468     foreach($matches as $matchnr=>$match)   {
469       $repl[$match[1]]=$match[0];
470     }
471   }
473   ksort($repl);
475   foreach($repl as $position=>$word)  {
476     $pos1 = strlen($arr);
477     $arr= markword($arr,($position+$posadd),$word,$pre,$suf);
478     $pos2 = strlen($arr);
479     $posadd =$posadd + ($pos2 - $pos1);
480   }
481   return($arr); 
484 /* This function marks a single word with the specified prefix and suffix */
485 function markword($string,$position,$word,$prefix,$suffix)
487   $wordlength   = strlen($word);
488   $wholelength  = strlen($string); 
490   $first = substr($string,0,$position);
491   $last  = substr($string,($position+$wordlength),$wholelength);  
493   return($first.$prefix.$word.$suffix.$last);
494
497 /* Creates HTML output for a single search result entry */
498 function createResultEntry($entry,$res,$name,$max)
501   $percentage = (int)(($res['hits']['overall'] / $max) * 100) ;
503   $str =  "<b><a href=\"?pg=".$name."&mark=1\">With ".$percentage."% hit in file ".$name."</a></b><br>" ;
504   $str.=  substr(strip_tags($entry['content']),0,200);
505   $str.=  "<hr>";
507   return($str);
509 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
510 ?>