Code

- Correcting bashism debian bug #530093
[gosa.git] / include / functions_helpviewer.inc
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2005, 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  */
21 /* Simple class to parse the xml help file */
22 class parseXml
23 {
24   var $parser;
25   var $filename;
26   var $entries;
28   function parseXml($file)
29   {
30     $this->parser   = xml_parser_create();
31     $this->filename = $file;
32     xml_set_object($this->parser, $this);
33     xml_set_element_handler($this->parser, "tag_open", "tag_close");
34     return($this->entries);
35   }
36   function parse()
37   {
38     $this->entries = array();
39     $fh= fopen($this->filename, "r");
40     $xmldata= fread($fh, 100000);
41     fclose($fh);
42     if(!xml_parse($this->parser, chop($xmldata))){
43         print(sprintf(_("XML error in guide.xml: %s at line %d"),
44             xml_error_string(xml_get_error_code($this->parser)),
45             xml_get_current_line_number($this->parser)));
46         exit;
47     }
48     return($this->entries);
49   }
50   function tag_open($parser,$tag,$attrs)
51   {
52     @$this->entries[$attrs['NAME']]=$attrs;
53   }
54   function tag_close(){; }
56 }
59 /* This function genereates the Index */
60 function genIndex()
61 {
62   global $helpobject;
63   $str = "";
64   $test = new pluglist($_SESSION['config'],NULL);
65   $current_hl = "";
66   foreach($_SESSION['helpobject']['helpconf'] as $id => $attrs){
67     $path = $test -> get_path($id);
68     $exists = true;
69     $helpdir = "../doc/guide/user/".$helpobject['lang']."/html/".preg_replace("/^.*\//i","",$path)."/";
70     if(!is_dir($helpdir)){
71       $exists = false;
72     }
73     $print_hl = false;
74     if($current_hl != $attrs['HEADLINE']){
75       $current_hl = $attrs['HEADLINE'];
76       $str .= "<h1>"._($current_hl)."</h1>";
77     }
78     $name = $attrs['NAME'];
79     $file = "index.html";
80     //$path = $plug;
81     if($exists){
82       $str .= "<p style='padding-left:20px;'><a href='?plug=".$id."'><b>"._($name)."</b></a></p>";
83     }else{
84       $str .= "<p style='padding-left:20px;'><b>"._($name)."</b> ("._("No help available for this plugin.").")</p>";
85     }
86   }
87   return (utf8_decode($str));
88 }
91 /* Some replacements */
92 $backwardlink  = "<a href=\"?pg=%s\"  class=\"maintitlebar\">
93                   <img src='images/back.png' align=\"middle\" alt=\""._("previous")."\" border=\"0\">
94                  </a>";
96 $forwardlink   = "<a href=\"?pg=%s\"  class=\"maintitlebar\">
97                   <img src='images/forward.png' align=\"middle\" alt=\""._("next")."\" border=\"0\">
98                  </a>";
100 $pre_mark                     = "<span style=\"background-color: #FFFC35;\">" ;                       // Sign words with this
101 $suf_mark                     = "</span>";                          //  and this
104 /* Define which tags musst be delete, header, navigation, banner */
105 $replacements=array();
106 $replacements['from']=array("@<!DOC.*<BODY >@si",
107     "/border=\".*\"/i",
108     "'<code.*code>'",
109 //    "/alt=\".*\"/i",
110     "/<HR>/",
111     "@<ADDRESS[^>]*?>.*?ADDRESS>@si",
112     "@<\/BODY[^>]*?>.*?HTML>@si",
113     "'<TABLE.*>'",
114     "/src.*icons/i",
115     "/src=\"/i",
116     "/<H1 ALIGN=\"CENTER\">/",
117  /* picture replacements */
118  //  "",
119     );
121 $replacements['to']=array("",
122     " border=\"0\" ",
123     "",
124   //  "",
125     "",
126     "",
127     "",
128     "<table border=1 cellspacing=0 bgcolor=\"#E0E0E0\" width=\"95%\" align=\"center\" cellpadding=\"3\" summary=\"\">",
129     "src=\"",
130     "src=\"images/",
131     "<H1>",
132  /* picture replacements */
133 //    "",
134   );
137 /* Reads all files in specified directory with contents an some inforations about the file */
138 /* Read all files with contents*/
139 /*                 |Folder="/var/ww...",
140                    |        |Fileprefix="node"
141                    |        |       |Filesuffix=".html"
142                    |        |       |       |WithoutContent=false(This means : read content)
143                    |        |       |       |          |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
144 function readfiles($basedir,$prefix,$suffix,$onlyIndex,$singlepage=false)
146   global $replacements;
148   $str    = array();  // Temporary variable
149   $cnt    = 0;        // Array index creation
150   $file   = "";       // Contains Filename
152   $dir = opendir($basedir);
154   $str['global']['start']       = $cnt;     // collect basic informations - Startpage
155   $str['global']['basedir']     = $basedir; // collect basic informations - Basedirectory
157   /* Startime for Benchmark */ 
158   $start =   (time()+microtime());
160   /* if singlepage == false -> Get all pages, */
161   if(!$singlepage) {
163     /* While theres is an unreaded file in our resource */
164     while (($file = readdir($dir)) !== false) {
165       
166       if((is_dir($basedir."/".$file))&&($file != "..")&&($file[0]!=".")){
167         $str[$file]=(readfiles($basedir."/".$file."/",$prefix,$suffix,$onlyIndex,false));
168       }
170       /* Filter all files which arn't intressting */
171       if((strstr($file,$suffix))&&($file!=".")&&($file!="..")&&(strstr($file,$prefix))){
173         /* Collect informations */
174         $str[$file]=array();
175         $str[$file]['name']   = $file;
176         $str[$file]['size']   = filesize($basedir.$file);
178         /* Readfile conent too ? */
179         if(!$onlyIndex){
180           $str[$file]['content']  = remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
181           $str[$file]['headline'] = getheader_from_content($str[$file]['content']);
182         }
184         /* Include file status, for debugging, not used in script yet */
185         $str[$file]['stat']   = stat($basedir.$file);
186         $cnt++;
187       }
188     }
190     /* Only get on file*/
191   }else{
192     /* Pages read = 1 */       
193     $cnt = 1;
195     /* Prepare result*/
196     $file                 = $singlepage;
197     $str[$file]           = array();
198     $str[$file]['name']   = $file;
199     $str[$file]['size']   = filesize($basedir.$file);
201     /* If onlyIndex == true skip reading content */
202     if(!$onlyIndex){
203       $str[$file]['content']  = remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
204       $str[$file]['headline'] = getheader_from_content($str[$file]['content']);
205     }
207     /* Include file status, for debugging, not used in script yet */
208     $str[$file]['stat']   = stat($basedir.$file);
209   }
211   /* Sort to  right order */
212   asort($str);
214   /* Endtime for Benchmark*/
215   $end = (time()+microtime());
216   $str['global']['cmptime'] = $end-$start;
218   /* Number of pages readed */
219   $str['global']['numpages']= $cnt;
220   closedir($dir);
221   return($str);
225 /* Read filecontent */
226 function getcontents($file)
228   $str = "" ;   // Temporary variable for file contents 
229   $tmp = "" ;   // Temporary varibale for partitial file contents
231   /* open file and read*/
232   $fp = fopen($file,"r");
233   if($fp) {
234     while($tmp = fread($fp,512))
235     {
236       $str.=  $tmp;
237     }
238   }else{
239     return(false);
240   }
241   return($str);
245 /*Remove tags */
246 function remove_unwanted_tags($str,$replacements)
248   $str=preg_replace($replacements['from'],$replacements['to'],$str);
249   return($str);
253 /*Converts the all links to specified path, is needed to get simple navigation */
254 function linkwrapper($str,$link)
256   $str = preg_replace("/HREF=\"http/i","target=\"_blank\" href=\"http",$str);
257   $str = preg_replace("/HREF=\"/","href=\"".$link."?pg=",$str);
258   $str=str_replace("HREF=\"","href=\"".$link."?pg=",$str);  
259   return($str);
263 /* Search content */
264 function search($arr,$word)
266   global $minwordlength,$allowed_chars_in_searchword;
267   /* Prepare Vars */ 
268   $result                     =array(); // Search result, filename, + hits + hits per word + matches 
269   $words                      =array(); // Temporary searchword handling
270   $useablewords               =array(); // Temporary searchword handling
271   $tryword                    = "";     // Temporary searchword handling
272   $result['global']['maxhit'] = 0;
273   unset($_SESSION['lastresults']);
274   unset($_SESSION['parsed_search_keyword']);
275   $_SESSION['parsed_search_keyword']="";
277   error_reporting(E_ALL);
279   /* prepare searchwords */
280   $word   = trim($word);
282   /* Filter all unusable chars */
283   $word   = preg_replace($allowed_chars_in_searchword,"",$word);
284   $words  = split(" ",str_replace("+"," ",$word));
286   /* Check all wordlengths */
287   foreach($words as $tryword){
288     $tryword = trim($tryword);
290     /* Filter words smaler than 3 chars */
291     if(strlen($tryword)>=$minwordlength) {
292       $_SESSION['parsed_search_keyword'].=$tryword." ";
293       $useablewords[]=$tryword;
294     }
295   }
297   /* Use words to search the content */
298   foreach($arr as $keys=>$vals)
299   {
300     foreach($vals as $key=>$val){
301       /* overallhits counts hits per page */
302       $overallhits=0;
304       /* Search all words */
305       foreach($useablewords as $word)
306       {
307         /* Skip key global, it contains no file data - it is a summary info*/
308         if($key!="global")
309         {
311           /* Get all hits for the word in $matches*/
312           preg_match_all("/".$word."/i",$arr[$keys][$key]['content'], $matches,PREG_OFFSET_CAPTURE);
314           /* Filter in Tag results*/
315           if(count($matches[0])){
316             foreach($matches[0] as $num=>$hit){
317               if(isset($arr[$keys][$key]['content']) && (is_in_tag($arr[$keys][$key]['content'],$hit[1]))){
318                 unset($matches[0][$num]);    
319               }    
320             }
321           }
323           /* Count matches */
324           $overallhits=$overallhits + count($matches[0]);    
326           /* Save collected data */
327           $result[$keys][$key]['hits'][$word]    = count($matches[0]); 
328           $result[$keys][$key]['hits']['overall']= $overallhits;  
330           /* Save max hits for page */
331           if($overallhits > $result['global']['maxhit']){
332             $result['global']['maxhit']=$overallhits;  
333           }
335           /* Add results for word to return value*/
336           $result[$keys][$key]['match'][$word]=array();
337           $result[$keys][$key]['match'][$word]=$matches[0];
338         }
339       }
340     }
341   }
343   /* Save result in Session, so we can mark words later, or go back to search, without searching again*/
344   $_SESSION['lastresults'] = $result;
345   return($result);
349 /* Detect 10 Best result entries, sort and call createResultEntry to create HTML output for  complete list */
350 function searchlist($arr,$res,$maxresults)
352   $global = $res['global'];
353   $topten = array();        // To detect 10 best solutions
354   $ret    = "";             // return value
355   unset($res['global']);
357   /* Detect 10 best Sites */
358   foreach($res as $key=>$resa)
359   foreach($resa as $keya=>$val){
360     /* Skip results with no hits */
361     if($val['hits']['overall']>0){
362       $topten[$key."/".$keya] = $val['hits']['overall'];
363     }
364   }
366   /* Sort by hit position in content, to easier mark words */
367   asort($topten);
368   $topten = array_reverse($topten);
369   $topten = (array_slice($topten,0,$maxresults));
372   /* We have a result, an array with all content, an array with hits and position and we have the 10 best hits */
373   /* Foreach */  
374   foreach($topten as $key => $hits)  {
376     $ks = split("\/",$key);
377     $k1 = $ks[0];
378     $k2 = $ks[1];
379     
380     $ret.= createResultEntry($arr[$k1][$k2],$res[$k1][$k2],$key,$global['maxhit']);    
381   }
383   /* appending footer message for resultlist */
384   $ret.= "<br>
385               ".sprintf(_("%s results for your search with the keyword %s"), 
386                             "<b>".count($topten)."</b>", 
387                             "<b>".$_SESSION['parsed_search_keyword']."</b>");
388   $ret.="<br>
389         <br>";
390   return($ret);
394 /* This function marks a string with the given search result for this string*/
395 function markup_page($arr,$res)
397   global $pre_mark,$suf_mark;
398   
399   $ret    = "";             // return value
400   $repl   = array();
401   $posadd = 0;
403   foreach($res['match'] as $word => $matches)   {
404     foreach($matches as $matchnr=>$match)   {
405       $repl[$match[1]]=$match[0];
406     }
407   }
409   ksort($repl);
410   
411   foreach($repl as $position=>$word)  {
412     $pos1 = strlen($arr);
413     $arr= markword($arr,($position+$posadd),$word,$pre_mark,$suf_mark);
414     $pos2 = strlen($arr);
415     $posadd =$posadd + ($pos2 - $pos1);
416   }
417   return($arr); 
421 /* This function marks a single word with the specified prefix and suffix */
422 function markword($string,$position,$word,$prefix,$suffix)
424   $wordlength   = strlen($word);
425   $wholelength  = strlen($string); 
427   $first = substr($string,0,$position);
428   $last  = substr($string,($position+$wordlength),$wholelength);  
430   return($first.$prefix.$word.$suffix.$last);
431
433 /* Creates HTML output for a single search result entry */
434 function createResultEntry($entry,$res,$name,$max)
436   $percentage = (int)(($res['hits']['overall'] / $max) * 100) ;
437   $color  = dechex($percentage+150);
438   $color2 = dechex(150 - $percentage);
440   $entry['content'] = preg_replace("\"".$entry['headline']."\"","",$entry['content'],1);
442   if(strlen($color)==1) $color = "0".$color;
446   /* the object tag is needed for W3c */
447   $str =  "<a href=\"?pg=".$name."&amp;mark=1\" title=\"".$percentage."% ".$entry['headline']."\">
448           <object>
449           <table summary=\"\"  width=\"98%\" align=\"center\">
450             <tr>
451               <td height=15>
452                 <b>".utf8_encode($entry['headline'])."</b> -".utf8_encode(substr(strip_tags($entry['content']),0,120))."...
453               </td>
454               <td width=50 valign=\"top\">".progressbar($percentage,50,8)."</td>
455              </tr>
456              <tr>
457               <td colspan=2>
458                 <b>
459                   ".(sprintf(_("%s%% hit rate in file %s"),$percentage,$name))."
460                 </b>
461               </td>
462             </tr>
463           </table>
464           </object></a>
465           ";
466   $str.=  "<hr size=\"1\">";
468   return($str);
472 /*Simple function to detect if we prepare to change a tag or visible text */
473 function is_in_tag($string,$pos)
475   $pos1 = $pos2 = 0;
476   if(preg_match("/</",$string)){
477     $pos1 = strpos($string,"<",$pos);
478   }
479   if(preg_match("/>/",$string)){
480     $pos2 = strpos($string,">",$pos);
481   }
482   if ($pos1 > $pos2)  {
483     return(true);
484   }else{
485     return(false);
486   }
489 /*Returns frist line of readable text, it should be the headline */
490 function getheader_from_content($str)
492   $str = strip_tags($str);
493   $pos = 0;
494   $arr = split("\n",$str);
495   foreach($arr as $possibleheadline){
496     if(strlen($possibleheadline)>=3){
497       return $possibleheadline; 
498     }
499   }
502 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
503 ?>