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 */
22 /*******************************************
23 Only function definition will follow here
24 /*******************************************
27 /* Reads all files in specified directory with contents an some inforations about the file */
28 /* Read all files with contents*/
29 /* |Folder="/var/ww...",
30 | |Fileprefix="node"
31 | | |Filesuffix=".html"
32 | | | |WithoutContent=false(This means : read content)
33 | | | | |Singlepage=false(Means read all, if w want to read single, specify its filename)"*/
34 function readfiles($basedir,$prefix,$suffix,$onlyIndex,$singlepage=false)
35 {
36 global $replacements;
38 $str = array(); // Temporary variable
39 $cnt = 0; // Array index creation
40 $file = ""; // Contains Filename
42 $dir = opendir($basedir);
44 $str['global']['start'] = $cnt; // collect basic informations - Startpage
45 $str['global']['basedir'] = $basedir; // collect basic informations - Basedirectory
47 /* Startime for Benchmark */
48 $start = (time()+microtime());
50 /* if singlepage == false -> Get all pages, */
51 if(!$singlepage) {
53 /* While theres is an unreaded file in our resource */
54 while (($file = readdir($dir)) !== false) {
56 /* Filter all files which arn't intressting */
57 if((strstr($file,$suffix))&&($file!=".")&&($file!="..")&&(strstr($file,$prefix))){
59 /* Collect informations */
60 $str[$file]=array();
61 $str[$file]['name'] = $file;
62 $str[$file]['size'] = filesize($basedir.$file);
64 /* Readfile conent too ? */
65 if(!$onlyIndex){
66 $str[$file]['content']= remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
67 }
69 /* Include file status, for debugging, not used in script yet */
70 $str[$file]['stat'] = stat($basedir.$file);
71 $cnt++;
72 }
73 }
75 /* Only get on file*/
76 }else{
77 /* Pages read = 1 */
78 $cnt = 1;
80 /* Prepare result*/
81 $file = $singlepage;
82 $str[$file] = array();
83 $str[$file]['name'] = $file;
84 $str[$file]['size'] = filesize($basedir.$file);
86 /* If onlyIndex == true skip reading content */
87 if(!$onlyIndex){
88 $str[$file]['content']= remove_unwanted_tags(linkwrapper(getcontents($basedir.$file),""),$replacements);
89 }
91 /* Include file status, for debugging, not used in script yet */
92 $str[$file]['stat'] = stat($basedir.$file);
93 }
95 /* Sort to right order */
96 asort($str);
98 /* Endtime for Benchmark*/
99 $end = (time()+microtime());
100 $str['global']['cmptime'] = $end-$start;
102 /* Number of pages readed */
103 $str['global']['numpages']= $cnt;
104 closedir($dir);
105 return($str);
106 }
109 /* Read filecontent */
110 function getcontents($file)
111 {
112 $str = "" ; // Temporary variable for file contents
113 $tmp = "" ; // Temporary varibale for partitial file contents
115 /* open file and read*/
116 $fp = fopen($file,"r");
117 if($fp) {
118 while($tmp = fread($fp,512))
119 {
120 $str.= $tmp;
121 }
122 }else{
123 return(false);
124 }
125 return($str);
126 }
129 /*Remove tags */
130 function remove_unwanted_tags($str,$replacements)
131 {
132 $str=preg_replace($replacements['from'],$replacements['to'],$str);
133 return($str);
134 }
137 /*Converts the all links to specified path, is needed to get simple navigation */
138 function linkwrapper($str,$link)
139 {
140 // $str = preg_replace("'<HREF.*>'","href=\"".$link."?pg=",$str);
141 $str=str_replace("HREF=\"","href=\"".$link."?pg=",$str);
142 return($str);
143 }
146 /* Search content */
147 function search($arr,$word)
148 {
149 global $minwordlength,$allowed_chars_in_searchword;
150 /* Prepare Vars */
151 $result =array(); // Search result, filename, + hits + hits per word + matches
152 $words =array(); // Temporary searchword handling
153 $useablewords =array(); // Temporary searchword handling
154 $tryword = ""; // Temporary searchword handling
155 $result['global']['maxhit'] = 0;
156 unset($_SESSION['lastresults']);
157 unset($_SESSION['parsed_search_keyword']);
158 $_SESSION['parsed_search_keyword']="";
160 /* prepare searchwords */
161 $word = trim($word);
163 /* Filter all unusable chars */
164 $word = preg_replace($allowed_chars_in_searchword,"",$word);
165 $words = split(" ",str_replace("+"," ",$word));
167 /* Check all wordlengths */
168 foreach($words as $tryword){
169 $tryword = trim($tryword);
171 /* Filter words smaler than 3 chars */
172 if(strlen($tryword)>=$minwordlength) {
173 $_SESSION['parsed_search_keyword'].=$tryword." ";
174 $useablewords[]=$tryword;
175 }
176 }
178 /* Use words to search the content */
179 foreach($arr as $key=>$val)
180 {
181 /* overallhits counts hits per page */
182 $overallhits=0;
184 /* Search all words */
185 foreach($useablewords as $word)
186 {
187 /* Skip key global, it contains no file data - it is a summary info*/
188 if($key!="global")
189 {
190 /* Get all hits for the word in $matches*/
191 preg_match_all("/".$word."/i",$arr[$key]['content'], $matches,PREG_OFFSET_CAPTURE);
193 /* Filter in Tag results*/
194 if(count($matches[0])){
195 foreach($matches[0] as $num=>$hit){
196 if(is_in_tag($arr[$key]['content'],$hit[1])) {
197 unset($matches[0][$num]);
198 }
199 }
200 }
202 /* Count matches */
203 $overallhits=$overallhits + count($matches[0]);
205 /* Save collected data */
206 $result[$key]['hits'][$word] = count($matches[0]);
207 $result[$key]['hits']['overall']= $overallhits;
209 /* Save max hits for page */
210 if($overallhits > $result['global']['maxhit']){
211 $result['global']['maxhit']=$overallhits;
212 }
214 /* Add results for word to return value*/
215 $result[$key]['match'][$word]=array();
216 $result[$key]['match'][$word]=$matches[0];
217 }
218 }
219 }
221 /* Save result in Session, so we can mark words later, or go back to search, without searching again*/
222 $_SESSION['lastresults'] = $result;
223 return($result);
224 }
227 /* Detect 10 Best result entries, sort and call createResultEntry to create HTML output for complete list */
228 function searchlist($arr,$res,$maxresults)
229 {
230 $global = $res['global'];
231 $topten = array(); // To detect 10 best solutions
232 $ret = ""; // return value
233 unset($res['global']);
235 /* Detect 10 best Sites */
236 foreach($res as $key=>$val){
238 /* Skip results with no hits */
239 if($val['hits']['overall']>0){
240 $topten[$key] = $val['hits']['overall'];
241 }
242 }
244 /* Sort by hit position in content, to easier mark words */
245 asort($topten);
246 $topten = array_reverse($topten);
247 $topten = (array_slice($topten,0,$maxresults));
249 /* We have a result, an array with all content, an array with hits and position and we have the 10 best hits */
250 /* Foreach */
251 foreach($topten as $name => $hits) {
252 $ret.= createResultEntry($arr[$name],$res[$name],$name,$global['maxhit']);
253 }
255 /* appending footer message for resultlist */
256 $ret.= "<br> ".count($topten)." - "._("Results for your search with the keyword")." <b>".htmlentities($_SESSION['search_string'])."</b>"._(" interpreted as ")."<b>".$_SESSION['parsed_search_keyword']."</b>";
258 return($ret);
259 }
262 /* This function marks a string with the given search result for this string*/
263 function markup_page($arr,$res)
264 {
265 global $pre_mark,$suf_mark;
267 $ret = ""; // return value
268 $repl = array();
269 $posadd = 0;
271 foreach($res['match'] as $word => $matches) {
272 foreach($matches as $matchnr=>$match) {
273 $repl[$match[1]]=$match[0];
274 }
275 }
277 ksort($repl);
279 foreach($repl as $position=>$word) {
280 $pos1 = strlen($arr);
281 $arr= markword($arr,($position+$posadd),$word,$pre_mark,$suf_mark);
282 $pos2 = strlen($arr);
283 $posadd =$posadd + ($pos2 - $pos1);
284 }
285 return($arr);
286 }
289 /* This function marks a single word with the specified prefix and suffix */
290 function markword($string,$position,$word,$prefix,$suffix)
291 {
292 $wordlength = strlen($word);
293 $wholelength = strlen($string);
295 $first = substr($string,0,$position);
296 $last = substr($string,($position+$wordlength),$wholelength);
298 return($first.$prefix.$word.$suffix.$last);
299 }
302 /* Creates HTML output for a single search result entry */
303 function createResultEntry($entry,$res,$name,$max)
304 {
305 $percentage = (int)(($res['hits']['overall'] / $max) * 100) ;
307 $str = "<b><a href=\"?pg=".$name."&mark=1\">".sprintf(_("%s%% hit rate in file %s"),$percentage,$name)."</a></b><br>" ;
308 $str.= substr(strip_tags($entry['content']),0,200);
309 $str.= "<hr>";
311 return($str);
312 }
315 /*Simple function to detect if we prepare to change a tag or visible text */
316 function is_in_tag($string,$pos)
317 {
318 $pos1 = strpos($string,"<",$pos);
319 $pos2 = strpos($string,">",$pos);
321 if ($pos1 > $pos2) {
322 return(true);
323 }else{
324 return(false);
325 }
326 }
328 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
329 ?>