Code

Updated help funtions
[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($arr)
61 {
62   global $helpobject;
63   $str = "";
64   $test = new pluglist($_SESSION['config'],NULL);
65   foreach($_SESSION['helpobject']['helpconf'] as $id => $attrs){
66     $path = $test -> get_path($id);
67     $exists = true;
68     $helpdir = "../doc/guide/user/".$helpobject['lang']."/html/".preg_replace("/^.*\//i","",$path)."/";
69     if(!is_dir($helpdir)){
70       $exists = false;
71     }
72     $print_hl = false;
73     if($current_hl != $attrs['HEADLINE']){
74       $current_hl = $attrs['HEADLINE'];
75       $str .= "<h1>"._($current_hl)."</h1>";
76     }
77     $name = $attrs['NAME'];
78     $file = "index.html";
79     $path = $plug;
80     if($exists){
81       $str .= "<p style='padding-left:20px;'><a href='?plug=".$id."'><b>".$name."</b></a></p>";
82     }else{
83       $str .= "<p style='padding-left:20px;'><b>".$name."</b> ("._("No help available for this plugin.").")</p>";
84     }
85   }
86   return utf8_decode($str);
87 }
90 /* Some replacements */
91 $backwardlink  = "<a href=\"?pg=%s\"  class=\"maintitlebar\">
92                   <img src='images/back.png' align=\"middle\" alt=\""._("previous")."\" border=\"0\">
93                  </a>";
95 $forwardlink   = "<a href=\"?pg=%s\"  class=\"maintitlebar\">
96                   <img src='images/forward.png' align=\"middle\" alt=\""._("next")."\" border=\"0\">
97                  </a>";
99 $pre_mark                     = "<span style=\"background-color: #FFFC35;\">" ;                       // Sign words with this
100 $suf_mark                     = "</span>";                          //  and this
103 /* Define which tags musst be delete, header, navigation, banner */
104 $replacements=array();
105 $replacements['from']=array("@<!DOC.*<BODY >@si",
106     "/border=\".*\"/i",
107     "'<code.*code>'",
108 //    "/alt=\".*\"/i",
109     "/<HR>/",
110     "@<ADDRESS[^>]*?>.*?ADDRESS>@si",
111     "@<\/BODY[^>]*?>.*?HTML>@si",
112     "'<TABLE.*>'",
113     "/src.*icons/i",
114     "/src=\"/i",
115     "/<H1 ALIGN=\"CENTER\">/",
116  /* picture replacements */
117  //  "",
118     );
120 $replacements['to']=array("",
121     " border=\"0\" ",
122     "",
123   //  "",
124     "",
125     "",
126     "",
127     "<table border=1 cellspacing=0 bgcolor=\"#E0E0E0\" width=\"95%\" align=\"center\" cellpadding=\"3\" summary=\"\">",
128     "src=\"",
129     "src=\"images/",
130     "<H1>",
131  /* picture replacements */
132 //    "",
133   );
136 /* Reads all files in specified directory with contents an some inforations about the file */
137 /* Read all files with contents*/
138 /*                 |Folder="/var/ww...",
139                    |        |Fileprefix="node"
140                    |        |       |Filesuffix=".html"
141                    |        |       |       |WithoutContent=false(This means : read content)
142                    |        |       |       |          |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
143 function readfiles($basedir,$prefix,$suffix,$onlyIndex,$singlepage=false)
145   global $replacements;
147   $str    = array();  // Temporary variable
148   $cnt    = 0;        // Array index creation
149   $file   = "";       // Contains Filename
151   $dir = opendir($basedir);
153   $str['global']['start']       = $cnt;     // collect basic informations - Startpage
154   $str['global']['basedir']     = $basedir; // collect basic informations - Basedirectory
156   /* Startime for Benchmark */ 
157   $start =   (time()+microtime());
159   /* if singlepage == false -> Get all pages, */
160   if(!$singlepage) {
162     /* While theres is an unreaded file in our resource */
163     while (($file = readdir($dir)) !== false) {
164       
165       if((is_dir($basedir."/".$file))&&($file != "..")&&($file[0]!=".")){
166         $str[$file]=(readfiles($basedir."/".$file."/",$prefix,$suffix,$onlyIndex,false));
167       }
169       /* Filter all files which arn't intressting */
170       if((strstr($file,$suffix))&&($file!=".")&&($file!="..")&&(strstr($file,$prefix))){
172         /* Collect informations */
173         $str[$file]=array();
174         $str[$file]['name']   = $file;
175         $str[$file]['size']   = filesize($basedir.$file);
177         /* Readfile conent too ? */
178         if(!$onlyIndex){
179           $str[$file]['content']  = remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
180           $str[$file]['headline'] = getheader_from_content($str[$file]['content']);
181         }
183         /* Include file status, for debugging, not used in script yet */
184         $str[$file]['stat']   = stat($basedir.$file);
185         $cnt++;
186       }
187     }
189     /* Only get on file*/
190   }else{
191     /* Pages read = 1 */       
192     $cnt = 1;
194     /* Prepare result*/
195     $file                 = $singlepage;
196     $str[$file]           = array();
197     $str[$file]['name']   = $file;
198     $str[$file]['size']   = filesize($basedir.$file);
200     /* If onlyIndex == true skip reading content */
201     if(!$onlyIndex){
202       $str[$file]['content']  = remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
203       $str[$file]['headline'] = getheader_from_content($str[$file]['content']);
204     }
206     /* Include file status, for debugging, not used in script yet */
207     $str[$file]['stat']   = stat($basedir.$file);
208   }
210   /* Sort to  right order */
211   asort($str);
213   /* Endtime for Benchmark*/
214   $end = (time()+microtime());
215   $str['global']['cmptime'] = $end-$start;
217   /* Number of pages readed */
218   $str['global']['numpages']= $cnt;
219   closedir($dir);
220   return($str);
224 /* Read filecontent */
225 function getcontents($file)
227   $str = "" ;   // Temporary variable for file contents 
228   $tmp = "" ;   // Temporary varibale for partitial file contents
230   /* open file and read*/
231   $fp = fopen($file,"r");
232   if($fp) {
233     while($tmp = fread($fp,512))
234     {
235       $str.=  $tmp;
236     }
237   }else{
238     return(false);
239   }
240   return($str);
244 /*Remove tags */
245 function remove_unwanted_tags($str,$replacements)
247   $str=preg_replace($replacements['from'],$replacements['to'],$str);
248   return($str);
252 /*Converts the all links to specified path, is needed to get simple navigation */
253 function linkwrapper($str,$link)
255   $str = preg_replace("/HREF=\"http/i","target=\"_blank\" href=\"http",$str);
256   $str = preg_replace("/HREF=\"/","href=\"".$link."?pg=",$str);
257 //  $str=str_replace("HREF=\"","href=\"".$link."?pg=",$str);  
258   return($str);
262 /* Search content */
263 function search($arr,$word)
265   global $minwordlength,$allowed_chars_in_searchword;
266   /* Prepare Vars */ 
267   $result                     =array(); // Search result, filename, + hits + hits per word + matches 
268   $words                      =array(); // Temporary searchword handling
269   $useablewords               =array(); // Temporary searchword handling
270   $tryword                    = "";     // Temporary searchword handling
271   $result['global']['maxhit'] = 0;
272   unset($_SESSION['lastresults']);
273   unset($_SESSION['parsed_search_keyword']);
274   $_SESSION['parsed_search_keyword']="";
276   error_reporting(E_ALL);
278   /* prepare searchwords */
279   $word   = trim($word);
281   /* Filter all unusable chars */
282   $word   = preg_replace($allowed_chars_in_searchword,"",$word);
283   $words  = split(" ",str_replace("+"," ",$word));
285   /* Check all wordlengths */
286   foreach($words as $tryword){
287     $tryword = trim($tryword);
289     /* Filter words smaler than 3 chars */
290     if(strlen($tryword)>=$minwordlength) {
291       $_SESSION['parsed_search_keyword'].=$tryword." ";
292       $useablewords[]=$tryword;
293     }
294   }
296   /* Use words to search the content */
297   foreach($arr as $keys=>$vals)
298   {
299     foreach($vals as $key=>$val){
300       /* overallhits counts hits per page */
301       $overallhits=0;
303       /* Search all words */
304       foreach($useablewords as $word)
305       {
306         /* Skip key global, it contains no file data - it is a summary info*/
307         if($key!="global")
308         {
310           /* Get all hits for the word in $matches*/
311           preg_match_all("/".$word."/i",$arr[$keys][$key]['content'], $matches,PREG_OFFSET_CAPTURE);
313           /* Filter in Tag results*/
314           if(count($matches[0])){
315             foreach($matches[0] as $num=>$hit){
316               if(is_in_tag($arr[$key]['content'],$hit[1]))  {
317                 unset($matches[0][$num]);    
318               }    
319             }
320           }
322           /* Count matches */
323           $overallhits=$overallhits + count($matches[0]);    
325           /* Save collected data */
326           $result[$keys][$key]['hits'][$word]    = count($matches[0]); 
327           $result[$keys][$key]['hits']['overall']= $overallhits;  
329           /* Save max hits for page */
330           if($overallhits > $result['global']['maxhit']){
331             $result['global']['maxhit']=$overallhits;  
332           }
334           /* Add results for word to return value*/
335           $result[$keys][$key]['match'][$word]=array();
336           $result[$keys][$key]['match'][$word]=$matches[0];
337         }
338       }
339     }
340   }
342   /* Save result in Session, so we can mark words later, or go back to search, without searching again*/
343   $_SESSION['lastresults'] = $result;
344   return($result);
348 /* Detect 10 Best result entries, sort and call createResultEntry to create HTML output for  complete list */
349 function searchlist($arr,$res,$maxresults)
351   $global = $res['global'];
352   $topten = array();        // To detect 10 best solutions
353   $ret    = "";             // return value
354   unset($res['global']);
356   /* Detect 10 best Sites */
357   foreach($res as $key=>$resa)
358   foreach($resa as $keya=>$val){
359     /* Skip results with no hits */
360     if($val['hits']['overall']>0){
361       $topten[$key."/".$keya] = $val['hits']['overall'];
362     }
363   }
365   /* Sort by hit position in content, to easier mark words */
366   asort($topten);
367   $topten = array_reverse($topten);
368   $topten = (array_slice($topten,0,$maxresults));
371   /* We have a result, an array with all content, an array with hits and position and we have the 10 best hits */
372   /* Foreach */  
373   foreach($topten as $key => $hits)  {
375     $ks = split("\/",$key);
376     $k1 = $ks[0];
377     $k2 = $ks[1];
378     
379     $ret.= createResultEntry($arr[$k1][$k2],$res[$k1][$k2],$key,$global['maxhit']);    
380   }
382   /* appending footer message for resultlist */
383   $ret.= "<br>
384               ".sprintf(_("%s results for your search with the keyword %s interpreted as %s"), 
385                             "<b>".count($topten)."</b>", 
386                             "<b>".($_SESSION['search_string'])."</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>".$entry['headline']."</b> -".htmlentities(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                   ".htmlentities(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 = strpos($string,"<",$pos);
476   $pos2 = strpos($string,">",$pos);
478   if ($pos1 > $pos2)  {
479     return(true);
480   }else{
481     return(false);
482   }
485 /*Returns frist line of readable text, it should be the headline */
486 function getheader_from_content($str)
488   $str = strip_tags($str);
489   $pos = 0;
490   $arr = split("\n",$str);
491   foreach($arr as $possibleheadline){
492     if(strlen($possibleheadline)>=3){
493       return $possibleheadline; 
494     }
495   }
498 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
499 ?>