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