Code

Fixed PHP Warnings when creating a new FAIrelease
[gosa.git] / gosa-core / include / functions_helpviewer.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /* Simple class to parse the xml help file */
24 class parseXml
25 {
26   var $parser;
27   var $filename;
28   var $entries;
30   function parseXml($file)
31   {
32     $this->parser   = xml_parser_create();
33     $this->filename = $file;
34     xml_set_object($this->parser, $this);
35     xml_set_element_handler($this->parser, "tag_open", "tag_close");
36     return($this->entries);
37   }
38   function parse()
39   {
40     $this->entries = array();
41     $fh= fopen($this->filename, "r");
42     $xmldata= fread($fh, 100000);
43     fclose($fh);
44     if(!xml_parse($this->parser, chop($xmldata))){
45         print(sprintf(_("XML error in guide.xml: %s at line %d"),
46             xml_error_string(xml_get_error_code($this->parser)),
47             xml_get_current_line_number($this->parser)));
48         exit;
49     }
50     return($this->entries);
51   }
52   function tag_open($parser,$tag,$attrs)
53   {
54     @$this->entries[$attrs['NAME']]=$attrs;
55   }
56   function tag_close(){; }
58 }
61 /* This function genereates the Index */
62 function genIndex()
63 {
64   global $helpobject;
65   $str = "";
66   $helpobject = session::global_get('helpobject');
67   $ui= get_userinfo();
68   $test = new pluglist(session::global_get('config'), $ui);
69   $current_hl = "";
70   foreach($helpobject['helpconf'] as $id => $attrs){
71     $path = $test -> get_path($id);
72     $exists = true;
73     $helpdir = "../doc/core/".$helpobject['lang']."/html/".preg_replace("/^.*\//i","",$path)."/";
74     if(!is_dir($helpdir)){
75       $exists = false;
76     }
77     $print_hl = false;
78     if($current_hl != $attrs['HEADLINE']){
79       $current_hl = $attrs['HEADLINE'];
80       $str .= "<h1>"._($current_hl)."</h1>";
81     }
82     $name = $attrs['NAME'];
83     $file = "index.html";
84     //$path = $plug;
85     if($exists){
86       $str .= "<p style='padding-left:20px;'><a href='?plug=".$id."'><b>"._($name)."</b></a></p>";
87     }else{
88       $str .= "<p style='padding-left:20px;'><b>"._($name)."</b> ("._("No help available for this plugin.").")</p>";
89     }
90   }
91   return (utf8_decode($str));
92 }
95 /* Some replacements */
96 $backwardlink  = "<a href=\"?pg=%s\"  class=\"maintitlebar\">
97                   <img src='images/back.png' align=\"middle\" alt=\""._("previous")."\" border=\"0\">
98                  </a>";
100 $forwardlink   = "<a href=\"?pg=%s\"  class=\"maintitlebar\">
101                   <img src='images/forward.png' align=\"middle\" alt=\""._("next")."\" border=\"0\">
102                  </a>";
104 $pre_mark                     = "<span style=\"background-color: #FFFC35;\">" ;                       // Sign words with this
105 $suf_mark                     = "</span>";                          //  and this
108 /* Define which tags musst be delete, header, navigation, banner */
109 $replacements=array();
110 $replacements['from']=array("@<!DOC.*<BODY >@si",
111     "/border=\".*\"/i",
112     "'<code.*code>'",
113 //    "/alt=\".*\"/i",
114     "/<HR>/",
115     "@<ADDRESS[^>]*?>.*?ADDRESS>@si",
116     "@<\/BODY[^>]*?>.*?HTML>@si",
117     "'<TABLE.*>'",
118     "/src.*icons/i",
119     "/src=\"/i",
120     "/<H1 ALIGN=\"CENTER\">/",
121  /* picture replacements */
122  //  "",
123     );
125 $replacements['to']=array("",
126     " border=\"0\" ",
127     "",
128   //  "",
129     "",
130     "",
131     "",
132     "<table border=1 cellspacing=0 bgcolor=\"#E0E0E0\" width=\"95%\" align=\"center\" cellpadding=\"3\" summary=\"\">",
133     "src=\"",
134     "src=\"images/",
135     "<H1>",
136  /* picture replacements */
137 //    "",
138   );
141 /* Reads all files in specified directory with contents an some inforations about the file */
142 /* Read all files with contents*/
143 /*                 |Folder="/var/ww...",
144                    |        |Fileprefix="node"
145                    |        |       |Filesuffix=".html"
146                    |        |       |       |WithoutContent=false(This means : read content)
147                    |        |       |       |          |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
148 function readfiles($basedir,$prefix,$suffix,$onlyIndex,$singlepage=false)
150   global $replacements;
152   $str    = array();  // Temporary variable
153   $cnt    = 0;        // Array index creation
154   $file   = "";       // Contains Filename
156   $dir = opendir($basedir);
158   $str['global']['start']       = $cnt;     // collect basic informations - Startpage
159   $str['global']['basedir']     = $basedir; // collect basic informations - Basedirectory
161   /* Startime for Benchmark */ 
162   $start =   (time()+microtime());
164   /* if singlepage == false -> Get all pages, */
165   if(!$singlepage) {
167     /* While theres is an unreaded file in our resource */
168     while (($file = readdir($dir)) !== false) {
169       
170       if((is_dir($basedir."/".$file))&&($file != "..")&&($file[0]!=".")){
171         $str[$file]=(readfiles($basedir."/".$file."/",$prefix,$suffix,$onlyIndex,false));
172       }
174       /* Filter all files which arn't intressting */
175       if((strstr($file,$suffix))&&($file!=".")&&($file!="..")&&(strstr($file,$prefix))){
177         /* Collect informations */
178         $str[$file]=array();
179         $str[$file]['name']   = $file;
180         $str[$file]['size']   = filesize($basedir.$file);
182         /* Readfile conent too ? */
183         if(!$onlyIndex){
184           $str[$file]['content']  = remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
185           $str[$file]['headline'] = getheader_from_content($str[$file]['content']);
186         }
188         /* Include file status, for debugging, not used in script yet */
189         $str[$file]['stat']   = stat($basedir.$file);
190         $cnt++;
191       }
192     }
194     /* Only get on file*/
195   }else{
196     /* Pages read = 1 */       
197     $cnt = 1;
199     /* Prepare result*/
200     $file                 = $singlepage;
201     $str[$file]           = array();
202     $str[$file]['name']   = $file;
203     $str[$file]['size']   = filesize($basedir.$file);
205     /* If onlyIndex == true skip reading content */
206     if(!$onlyIndex){
207       $str[$file]['content']  = remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
208       $str[$file]['headline'] = getheader_from_content($str[$file]['content']);
209     }
211     /* Include file status, for debugging, not used in script yet */
212     $str[$file]['stat']   = stat($basedir.$file);
213   }
215   /* Sort to  right order */
216   asort($str);
218   /* Endtime for Benchmark*/
219   $end = (time()+microtime());
220   $str['global']['cmptime'] = $end-$start;
222   /* Number of pages readed */
223   $str['global']['numpages']= $cnt;
224   closedir($dir);
225   return($str);
229 /* Read filecontent */
230 function getcontents($file)
232   $str = "" ;   // Temporary variable for file contents 
233   $tmp = "" ;   // Temporary varibale for partitial file contents
235   /* open file and read*/
236   $fp = fopen($file,"r");
237   if($fp) {
238     while($tmp = fread($fp,512))
239     {
240       $str.=  $tmp;
241     }
242   }else{
243     return(false);
244   }
245   return($str);
249 /*Remove tags */
250 function remove_unwanted_tags($str,$replacements)
252   $str=preg_replace($replacements['from'],$replacements['to'],$str);
253   return($str);
257 /*Converts the all links to specified path, is needed to get simple navigation */
258 function linkwrapper($str,$link)
260   $str = preg_replace("/HREF=\"http/i","target=\"_blank\" href=\"http",$str);
261   $str = str_replace("HREF=\"","href=\"".$link."?pg=",$str);  
262   return($str);
266 /* Search content */
267 function search($arr,$word)
269   global $minwordlength,$allowed_chars_in_searchword;
270   /* Prepare Vars */ 
271   $result                     =array(); // Search result, filename, + hits + hits per word + matches 
272   $words                      =array(); // Temporary searchword handling
273   $useablewords               =array(); // Temporary searchword handling
274   $tryword                    = "";     // Temporary searchword handling
275   $result['global']['maxhit'] = 0;
276   session::un_set('lastresults');
277   session::un_set('parsed_search_keyword');
278   session::set('parsed_search_keyword',"");
280   error_reporting(E_ALL | E_STRICT);
282   /* prepare searchwords */
283   $word   = trim($word);
285   /* Filter all unusable chars */
286   $word   = preg_replace($allowed_chars_in_searchword,"",$word);
287   $words  = split(" ",str_replace("+"," ",$word));
289   /* Check all wordlengths */
290   foreach($words as $tryword){
291     $tryword = trim($tryword);
293     /* Filter words smaler than 3 chars */
294     if(strlen($tryword)>=$minwordlength) {
295       session::set('parsed_search_keyword', session::get('parsed_search_keyword').$tryword." ");
296       $useablewords[]=$tryword;
297     }
298   }
300   /* Use words to search the content */
301   foreach($arr as $keys=>$vals)
302   {
303     foreach($vals as $key=>$val){
304       /* overallhits counts hits per page */
305       $overallhits=0;
307       /* Search all words */
308       foreach($useablewords as $word)
309       {
310         /* Skip key global, it contains no file data - it is a summary info*/
311         if($key!="global")
312         {
314           /* Get all hits for the word in $matches*/
315           preg_match_all("/".$word."/i",$arr[$keys][$key]['content'], $matches,PREG_OFFSET_CAPTURE);
317           /* Filter in Tag results*/
318           if(count($matches[0])){
319             foreach($matches[0] as $num=>$hit){
320               if(isset($arr[$keys][$key]['content']) && (is_in_tag($arr[$keys][$key]['content'],$hit[1]))){
321                 unset($matches[0][$num]);    
322               }    
323             }
324           }
326           /* Count matches */
327           $overallhits=$overallhits + count($matches[0]);    
329           /* Save collected data */
330           $result[$keys][$key]['hits'][$word]    = count($matches[0]); 
331           $result[$keys][$key]['hits']['overall']= $overallhits;  
333           /* Save max hits for page */
334           if($overallhits > $result['global']['maxhit']){
335             $result['global']['maxhit']=$overallhits;  
336           }
338           /* Add results for word to return value*/
339           $result[$keys][$key]['match'][$word]=array();
340           $result[$keys][$key]['match'][$word]=$matches[0];
341         }
342       }
343     }
344   }
346   /* Save result in Session, so we can mark words later, or go back to search, without searching again*/
347   session::set('lastresults',$result);
348   return($result);
352 /* Detect 10 Best result entries, sort and call createResultEntry to create HTML output for  complete list */
353 function searchlist($arr,$res,$maxresults)
355   $global = $res['global'];
356   $topten = array();        // To detect 10 best solutions
357   $ret    = "";             // return value
358   unset($res['global']);
360   /* Detect 10 best Sites */
361   foreach($res as $key=>$resa)
362   foreach($resa as $keya=>$val){
363     /* Skip results with no hits */
364     if($val['hits']['overall']>0){
365       $topten[$key."/".$keya] = $val['hits']['overall'];
366     }
367   }
369   /* Sort by hit position in content, to easier mark words */
370   asort($topten);
371   $topten = array_reverse($topten);
372   $topten = (array_slice($topten,0,$maxresults));
375   /* We have a result, an array with all content, an array with hits and position and we have the 10 best hits */
376   /* Foreach */  
377   foreach($topten as $key => $hits)  {
379     $ks = split("\/",$key);
380     $k1 = $ks[0];
381     $k2 = $ks[1];
382     
383     $ret.= createResultEntry($arr[$k1][$k2],$res[$k1][$k2],$key,$global['maxhit']);    
384   }
386   /* appending footer message for resultlist */
387   $ret.= "<br>
388               ".sprintf(_("%s results for your search with the keyword %s"), 
389                             "<b>".count($topten)."</b>", 
390                             "<b>".session::get('parsed_search_keyword')."</b>");
391   $ret.="<br>
392         <br>";
393   return($ret);
397 /* This function marks a string with the given search result for this string*/
398 function markup_page($arr,$res)
400   global $pre_mark,$suf_mark;
401   
402   $ret    = "";             // return value
403   $repl   = array();
404   $posadd = 0;
406   foreach($res['match'] as $word => $matches)   {
407     foreach($matches as $matchnr=>$match)   {
408       $repl[$match[1]]=$match[0];
409     }
410   }
412   ksort($repl);
413   
414   foreach($repl as $position=>$word)  {
415     $pos1 = strlen($arr);
416     $arr= markword($arr,($position+$posadd),$word,$pre_mark,$suf_mark);
417     $pos2 = strlen($arr);
418     $posadd =$posadd + ($pos2 - $pos1);
419   }
420   return($arr); 
424 /* This function marks a single word with the specified prefix and suffix */
425 function markword($string,$position,$word,$prefix,$suffix)
427   $wordlength   = strlen($word);
428   $wholelength  = strlen($string); 
430   $first = substr($string,0,$position);
431   $last  = substr($string,($position+$wordlength),$wholelength);  
433   return($first.$prefix.$word.$suffix.$last);
434
436 /* Creates HTML output for a single search result entry */
437 function createResultEntry($entry,$res,$name,$max)
439   $percentage = (int)(($res['hits']['overall'] / $max) * 100) ;
440   $color  = dechex($percentage+150);
441   $color2 = dechex(150 - $percentage);
443   $entry['content'] = preg_replace("\"".$entry['headline']."\"","",$entry['content'],1);
445   if(strlen($color)==1) $color = "0".$color;
449   /* the object tag is needed for W3c */
450   $str =  "<a href=\"?pg=".$name."&amp;mark=1\" title=\"".$percentage."% ".$entry['headline']."\">
451           <object>
452           <table summary=\"\"  width=\"98%\" align=\"center\">
453             <tr>
454               <td height=15>
455                 <b>".utf8_encode($entry['headline'])."</b> -".utf8_encode(substr(strip_tags($entry['content']),0,120))."...
456               </td>
457               <td width=50 valign=\"top\">".progressbar($percentage,50,8)."</td>
458              </tr>
459              <tr>
460               <td colspan=2>
461                 <b>
462                   ".(sprintf(_("%s%% hit rate in file %s"),$percentage,$name))."
463                 </b>
464               </td>
465             </tr>
466           </table>
467           </object></a>
468           ";
469   $str.=  "<hr size=\"1\">";
471   return($str);
475 /*Simple function to detect if we prepare to change a tag or visible text */
476 function is_in_tag($string,$pos)
478   $pos1 = $pos2 = 0;
479   if(preg_match("/</",$string)){
480     $pos1 = strpos($string,"<",$pos);
481   }
482   if(preg_match("/>/",$string)){
483     $pos2 = strpos($string,">",$pos);
484   }
485   if ($pos1 > $pos2)  {
486     return(true);
487   }else{
488     return(false);
489   }
492 /*Returns frist line of readable text, it should be the headline */
493 function getheader_from_content($str)
495   $str = strip_tags($str);
496   $pos = 0;
497   $arr = split("\n",$str);
498   foreach($arr as $possibleheadline){
499     if(strlen($possibleheadline)>=3){
500       return $possibleheadline; 
501     }
502   }
505 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
506 ?>