]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/msql.php
Fix SF bug #462168: hit count broken for pages with apostrophes in their names.
[SourceForge/phpwiki.git] / lib / msql.php
1 <?php rcs_id('$Id: msql.php,v 1.6.2.3 2001-11-07 18:58:14 dairiki Exp $');
2
3    /*
4       Database functions:
5       MakePageHash($dbhash)
6       MakeDBHash($pagename, $pagehash)
7       OpenDataBase($dbname)
8       CloseDataBase($dbi)
9       RetrievePage($dbi, $pagename, $pagestore)
10       InsertPage($dbi, $pagename, $pagehash)
11       SaveCopyToArchive($dbi, $pagename, $pagehash) 
12       IsWikiPage($dbi, $pagename)
13       InitTitleSearch($dbi, $search)
14       TitleSearchNextMatch($dbi, &$pos)
15       InitFullSearch($dbi, $search)
16       FullSearchNextMatch($dbi, &$pos)
17       MakeBackLinkSearchRegexp($pagename)
18       InitBackLinkSearch($dbi, $pagename) 
19       BackLinkSearchNextMatch($dbi, &$pos) 
20       GetAllWikiPageNames($dbi)
21    */
22
23
24    // open a database and return the handle
25    // ignores MAX_DBM_ATTEMPTS
26
27    function OpenDataBase($dbinfo) {
28       global $msql_db;
29
30       if (! ($dbc = msql_connect())) {
31          $msg = gettext ("Cannot establish connection to database, giving up.");
32          $msg .= "<BR>";
33          $msg .= sprintf(gettext ("Error message: %s"), msql_error());
34          ExitWiki($msg);
35       }
36       if (!msql_select_db($msql_db, $dbc)) {
37          $msg = gettext ("Cannot open database %s, giving up.");
38          $msg .= "<BR>";
39          $msg .= sprintf(gettext ("Error message: %s"), msql_error());
40          ExitWiki($msg);
41       }
42
43       $dbi['dbc'] = $dbc;
44       $dbi['table'] = $dbinfo['table'];           // page metadata
45       $dbi['page_table'] = $dbinfo['page_table']; // page content
46       return $dbi;
47    }
48
49
50    function CloseDataBase($dbi) {
51       // I found msql_pconnect unstable so we go the slow route.
52       return msql_close($dbi['dbc']);
53    }
54
55
56    // This should receive the full text of the page in one string
57    // It will break the page text into an array of strings
58    // of length MSQL_MAX_LINE_LENGTH which should match the length
59    // of the columns wikipages.LINE, archivepages.LINE in schema.minisql
60
61    function msqlDecomposeString($string) {
62       $ret_arr = array();
63
64       // initialize the array to satisfy E_NOTICE
65       for ($i = 0; $i < MSQL_MAX_LINE_LENGTH; $i++) {
66          $ret_arr[$i] = "";
67       }
68       $el = 0;
69    
70       // zero, one, infinity
71       // account for the small case
72       if (strlen($string) < MSQL_MAX_LINE_LENGTH) { 
73          $ret_arr[$el] = $string;
74          return $ret_arr;
75       }
76    
77       $words = array();
78       $line = $string2 = "";
79    
80       // split on single spaces
81       $words = preg_split("/ /", $string);
82       $num_words = count($words);
83    
84       reset($words);
85       $ret_arr[0] = $words[0];
86       $line = " $words[1]";
87    
88       // for all words, build up lines < MSQL_MAX_LINE_LENGTH in $ret_arr
89       for ($x = 2; $x < $num_words; $x++) {
90          $length = strlen($line) + strlen($words[$x]) 
91                    + strlen($ret_arr[$el]) + 1;
92
93          if ($length < MSQL_MAX_LINE_LENGTH) {
94             $line .= " " .  $words[$x];
95          } else {
96             // put this line in the return array, reset, continue
97             $ret_arr[$el++] .= $line;
98             $line = " $words[$x]"; // reset     
99          }
100       }
101       $ret_arr[$el] = $line;
102       return $ret_arr;
103    }
104
105
106    // Take form data and prepare it for the db
107    function MakeDBHash($pagename, $pagehash)
108    {
109       $pagehash["pagename"] = addslashes($pagename);
110       if (!isset($pagehash["flags"]))
111          $pagehash["flags"] = 0;
112       if (!isset($pagehash["content"])) {
113          $pagehash["content"] = array();
114       } else {
115          $pagehash["content"] = implode("\n", $pagehash["content"]);
116          $pagehash["content"] = msqlDecomposeString($pagehash["content"]);
117       }
118       $pagehash["author"] = addslashes($pagehash["author"]);
119       if (empty($pagehash["refs"])) {
120          $pagehash["refs"] = "";
121       } else {
122          $pagehash["refs"] = serialize($pagehash["refs"]);
123       }
124
125       return $pagehash;
126    }
127
128
129    // Take db data and prepare it for display
130    function MakePageHash($dbhash)
131    {
132       // unserialize/explode content
133       $dbhash['refs'] = unserialize($dbhash['refs']);
134       return $dbhash;
135    }
136
137
138    // Return hash of page + attributes or default
139    function RetrievePage($dbi, $pagename, $pagestore) {
140       $pagename = addslashes($pagename);
141       $table = $pagestore['table'];
142       $pagetable = $pagestore['page_table'];
143
144       $query = "select * from $table where pagename='$pagename'";
145       // echo "<p>query: $query<p>";
146       $res = msql_query($query, $dbi['dbc']);
147       if (msql_num_rows($res)) {
148          $dbhash = msql_fetch_array($res);
149
150          $query = "select lineno,line from $pagetable " .
151                   "where pagename='$pagename' " .
152                   "order by lineno";
153
154          $msql_content = "";
155          if ($res = msql_query($query, $dbi['dbc'])) {
156             $dbhash["content"] = array();
157             while ($row = msql_fetch_array($res)) {
158                 $msql_content .= $row["line"];
159             }
160             $dbhash["content"] = explode("\n", $msql_content);
161          }
162
163          return MakePageHash($dbhash);
164       }
165       return -1;
166    }
167
168
169    // Either insert or replace a key/value (a page)
170    function InsertPage($dbi, $pagename, $pagehash) {
171
172       $pagehash = MakeDBHash($pagename, $pagehash);
173       // $pagehash["content"] is now an array of strings 
174       // of MSQL_MAX_LINE_LENGTH
175
176       // record the time of modification
177       $pagehash["lastmodified"] = time();
178
179       if (IsWikiPage($dbi, $pagename)) {
180
181          $PAIRS = "author='$pagehash[author]'," .
182                   "created=$pagehash[created]," .
183                   "flags=$pagehash[flags]," .
184                   "lastmodified=$pagehash[lastmodified]," .
185                   "pagename='$pagehash[pagename]'," .
186                   "refs='$pagehash[refs]'," .
187                   "version=$pagehash[version]";
188
189          $query  = "UPDATE $dbi[table] SET $PAIRS WHERE pagename='$pagename'";
190
191       } else {
192          // do an insert
193          // build up the column names and values for the query
194
195          $COLUMNS = "author, created, flags, lastmodified, " .
196                     "pagename, refs, version";
197
198          $VALUES =  "'$pagehash[author]', " .
199                     "$pagehash[created], $pagehash[flags], " .
200                     "$pagehash[lastmodified], '$pagehash[pagename]', " .
201                     "'$pagehash[refs]', $pagehash[version]";
202
203
204          $query = "INSERT INTO $dbi[table] ($COLUMNS) VALUES($VALUES)";
205       }
206
207       // echo "<p>Query: $query<p>\n";
208
209       // first, insert the metadata
210       $retval = msql_query($query, $dbi['dbc']);
211       if ($retval == false) {
212          printf(gettext ("Insert/update failed: %s"), msql_error());
213          print "<br>\n";
214       }
215
216
217       // second, insert the page data
218       // remove old data from page_table
219       $query = "delete from $dbi[page_table] where pagename='$pagename'";
220       // echo "Delete query: $query<br>\n";
221       $retval = msql_query($query, $dbi['dbc']);
222       if ($retval == false) {
223          printf(gettext ("Delete on %s failed: %s"), $dbi[page_table],
224             msql_error());
225          print "<br>\n";
226       }
227
228       // insert the new lines
229       reset($pagehash["content"]);
230
231       for ($x = 0; $x < count($pagehash["content"]); $x++) {
232          $line = addslashes($pagehash["content"][$x]);
233          $query = "INSERT INTO $dbi[page_table] " .
234                   "(pagename, lineno, line) " .
235                   "VALUES('$pagename', $x, '$line')";
236          // echo "Page line insert query: $query<br>\n";
237          $retval = msql_query($query, $dbi['dbc']);
238          if ($retval == false) { 
239             printf(gettext ("Insert into %s failed: %s"), $dbi[page_table],
240                msql_error());
241             print "<br>\n";
242          }
243       }
244    }
245
246
247    // for archiving pages to a separate table
248    function SaveCopyToArchive($dbi, $pagename, $pagehash) {
249       global $ArchivePageStore;
250
251       $pagehash = MakeDBHash($pagename, $pagehash);
252       // $pagehash["content"] is now an array of strings 
253       // of MSQL_MAX_LINE_LENGTH
254
255       if (IsInArchive($dbi, $pagename)) {
256
257          $PAIRS = "author='$pagehash[author]'," .
258                   "created=$pagehash[created]," .
259                   "flags=$pagehash[flags]," .
260                   "lastmodified=$pagehash[lastmodified]," .
261                   "pagename='$pagehash[pagename]'," .
262                   "refs='$pagehash[refs]'," .
263                   "version=$pagehash[version]";
264
265          $query  = "UPDATE $ArchivePageStore[table] SET $PAIRS WHERE pagename='$pagename'";
266
267       } else {
268          // do an insert
269          // build up the column names and values for the query
270
271          $COLUMNS = "author, created, flags, lastmodified, " .
272                     "pagename, refs, version";
273
274          $VALUES =  "'$pagehash[author]', " .
275                     "$pagehash[created], $pagehash[flags], " .
276                     "$pagehash[lastmodified], '$pagehash[pagename]', " .
277                     "'$pagehash[refs]', $pagehash[version]";
278
279
280          $query = "INSERT INTO archive ($COLUMNS) VALUES($VALUES)";
281       }
282
283       // echo "<p>Query: $query<p>\n";
284
285       // first, insert the metadata
286       $retval = msql_query($query, $dbi['dbc']);
287       if ($retval == false) {
288          printf(gettext ("Insert/update failed: %s"), msql_error());
289          print "<br>\n";
290       }
291
292       // second, insert the page data
293       // remove old data from page_table
294       $query = "delete from $ArchivePageStore[page_table] where pagename='$pagename'";
295       // echo "Delete query: $query<br>\n";
296       $retval = msql_query($query, $dbi['dbc']);
297       if ($retval == false) {
298          printf(gettext ("Delete on %s failed: %s"),
299           $ArchivePageStore[page_table], msql_error());
300          print "<br>\n";
301       }
302
303       // insert the new lines
304       reset($pagehash["content"]);
305
306       for ($x = 0; $x < count($pagehash["content"]); $x++) {
307          $line = addslashes($pagehash["content"][$x]);
308          $query = "INSERT INTO $ArchivePageStore[page_table] " .
309                   "(pagename, lineno, line) " .
310                   "VALUES('$pagename', $x, '$line')";
311          // echo "Page line insert query: $query<br>\n";
312          $retval = msql_query($query, $dbi['dbc']);
313          if ($retval == false) {
314             printf(gettext ("Insert into %s failed: %s"),
315               $ArchivePageStore[page_table], msql_error());
316             print "<br>\n";
317          }
318       }
319
320
321    }
322
323
324    function IsWikiPage($dbi, $pagename) {
325       $pagename = addslashes($pagename);
326       $query = "select pagename from wiki where pagename='$pagename'";
327       // echo "Query: $query<br>\n";
328       if ($res = msql_query($query, $dbi['dbc'])) {
329          return(msql_affected_rows($res));
330       }
331    }
332
333
334    function IsInArchive($dbi, $pagename) {
335       $pagename = addslashes($pagename);
336       $query = "select pagename from archive where pagename='$pagename'";
337       // echo "Query: $query<br>\n";
338       if ($res = msql_query($query, $dbi['dbc'])) {
339          return(msql_affected_rows($res));
340       }
341    }
342
343
344
345    // setup for title-search
346    function InitTitleSearch($dbi, $search) {
347       $search = addslashes($search);
348       $query = "select pagename from $dbi[table] " .
349                "where pagename clike '%$search%' order by pagename";
350       $res = msql_query($query, $dbi['dbc']);
351
352       return $res;
353    }
354
355
356    // iterating through database
357    function TitleSearchNextMatch($dbi, $res) {
358       if($o = msql_fetch_object($res)) {
359          return $o->pagename;
360       }
361       else {
362          return 0;
363       }
364    }
365
366
367    // setup for full-text search
368    function InitFullSearch($dbi, $search) {
369       // select unique page names from wikipages, and then 
370       // retrieve all pages that come back.
371       $search = addslashes($search);
372       $query = "select distinct pagename from $dbi[page_table] " .
373                "where line clike '%$search%' " .
374                "order by pagename";
375       $res = msql_query($query, $dbi['dbc']);
376
377       return $res;
378    }
379
380    // iterating through database
381    function FullSearchNextMatch($dbi, $res) {
382       global $WikiPageStore;
383       if ($row = msql_fetch_row($res)) {
384         return RetrievePage($dbi, $row[0], $WikiPageStore);
385       } else {
386         return 0;
387       }
388    }
389
390    ////////////////////////
391    // new database features
392
393    // Compute PCRE suitable for searching for links to the given page.
394    function MakeBackLinkSearchRegexp($pagename) {
395       global $WikiNameRegexp;
396
397       // Note that in (at least some) PHP 3.x's, preg_quote only takes
398       // (at most) one argument.  Also it doesn't quote '/'s.
399       // It does quote '='s, so we'll use that for the delimeter.
400       $quoted_pagename = preg_quote($pagename);
401       if (preg_match("/^$WikiNameRegexp\$/", $pagename)) {
402          # FIXME: This may need modification for non-standard (non-english) $WikiNameRegexp.
403          return "=(?<![A-Za-z0-9!])$quoted_pagename(?![A-Za-z0-9])=";
404       }
405       else {
406          // Note from author: Sorry. :-/
407          return ( '='
408                   . '(?<!\[)\[(?!\[)' // Single, isolated '['
409                   . '([^]|]*\|)?'     // Optional stuff followed by '|'
410                   . '\s*'             // Optional space
411                   . $quoted_pagename  // Pagename
412                   . '\s*\]=' );       // Optional space, followed by ']'
413          // FIXME: the above regexp is still not quite right.
414          // Consider the text: " [ [ test page ]".  This is a link to a page
415          // named '[ test page'.  The above regexp will recognize this
416          // as a link either to '[ test page' (good) or to 'test page' (wrong).
417       } 
418    }
419
420    // setup for back-link search
421    function InitBackLinkSearch($dbi, $pagename) {
422       global $WikiLinksStore;
423      
424       $topage = addslashes($pagename);
425
426       // FIXME: this is buggy.  If a [multiword link] is split accross
427       // multiple lines int the page_table, we wont find it.
428       // (Probably the best fix is to implement the link table, and use it.)
429       $res['regexp'] = MakeBackLinkSearchRegexp($pagename);
430       $res['res'] = msql_query( "SELECT pagename, line FROM $dbi[page_table]"
431                                 . " WHERE line LIKE '%$topage%'"
432                                 . " ORDER BY pagename",
433                                 $dbi["dbc"]);
434       $res['lastpage'] = '';
435       
436       return $res;
437    }
438
439
440    // iterating through database
441    function BackLinkSearchNextMatch($dbi, $res) {
442       while (true) {
443          if ( ! ($o = msql_fetch_object($res['res']))) {
444             return 0;
445          }
446          if ( $res['lastpage'] == $o->pagename )
447             continue;
448          if ( ! preg_match($res['regexp'], $a->line) )
449             continue;
450          $res['lastpage'] = $o->pagename;
451          return $o->pagename;
452       }
453    }
454
455    function IncreaseHitCount($dbi, $pagename) {
456
457       $qpagename = addslashes($pagename);
458       $query = "select hits from hitcount where pagename='$qpagename'";
459       $res = msql_query($query, $dbi['dbc']);
460       if (msql_num_rows($res)) {
461          $hits = msql_result($res, 0, 'hits');
462          $hits++;
463          $query = "update hitcount set hits=$hits where pagename='$qpagename'";
464          $res = msql_query($query, $dbi['dbc']);
465
466       } else {
467          $query = "insert into hitcount (pagename, hits) " .
468                   "values ('$qpagename', 1)";
469          $res = msql_query($query, $dbi['dbc']);
470       }
471
472       return $res;
473    }
474
475    function GetHitCount($dbi, $pagename) {
476
477       $qpagename = addslashes($pagename);
478       $query = "select hits from hitcount where pagename='$qpagename'";
479       $res = msql_query($query, $dbi['dbc']);
480       if (msql_num_rows($res)) {
481          $hits = msql_result($res, 0, 'hits');
482       } else {
483          $hits = "0";
484       }
485
486       return $hits;
487    }
488
489
490
491    function InitMostPopular($dbi, $limit) {
492
493       $query = "select * from hitcount " .
494                "order by hits desc, pagename limit $limit";
495
496       $res = msql_query($query, $dbi['dbc']);
497       
498       return $res;
499    }
500
501    function MostPopularNextMatch($dbi, $res) {
502
503       if ($hits = msql_fetch_array($res)) {
504          return $hits;
505       } else {
506          return 0;
507       }
508    }
509
510    function GetAllWikiPageNames($dbi_) {
511       $res = msql_query("select pagename from wiki", $dbi['dbc']);
512       $rows = msql_num_rows($res);
513       for ($i = 0; $i < $rows; $i++) {
514          $pages[$i] = msql_result($res, $i, 'pagename');
515       }
516       return $pages;
517    }
518
519    ////////////////////////////////////////
520    // functionality for the wikilinks table
521
522    // takes a page name, returns array of scored incoming and outgoing links
523
524 /* Not implemented yet. The code below was copied from mysql.php...
525
526    function GetWikiPageLinks($dbi, $pagename) {
527       $links = array();
528       $pagename = addslashes($pagename);
529       $res = msql_query("select wikilinks.topage, wikiscore.score from wikilinks, wikiscore where wikilinks.topage=wikiscore.pagename and wikilinks.frompage='$pagename' order by score desc, topage", $dbi['dbc']);
530
531       $rows = msql_num_rows($res);
532       for ($i = 0; $i < $rows; $i++) {
533          $out = msql_fetch_array($res);
534          $links['out'][] = array($out['topage'], $out['score']);
535       }
536
537       $res = msql_query("select wikilinks.frompage, wikiscore.score from wikilinks, wikiscore where wikilinks.frompage=wikiscore.pagename and wikilinks.topage='$pagename' order by score desc, frompage", $dbi['dbc']);
538       $rows = msql_num_rows($res);
539       for ($i = 0; $i < $rows; $i++) {
540          $out = msql_fetch_array($res);
541          $links['in'][] = array($out['frompage'], $out['score']);
542       }
543
544       $res = msql_query("select distinct hitcount.pagename, hitcount.hits from wikilinks, hitcount where (wikilinks.frompage=hitcounts.pagename and wikilinks.topage='$pagename') or (wikilinks.topage=pagename and wikilinks.frompage='$pagename') order by hitcount.hits desc, wikilinks.pagename", $dbi['dbc']);
545       $rows = msql_num_rows($res);
546       for ($i = 0; $i < $rows; $i++) {
547          $out = msql_fetch_array($res);
548          $links['popular'][] = array($out['pagename'], $out['hits']);
549       }
550
551       return $links;
552    }
553
554
555    // takes page name, list of links it contains
556    // the $linklist is an array where the keys are the page names
557    function SetWikiPageLinks($dbi, $pagename, $linklist) {
558       $frompage = addslashes($pagename);
559
560       // first delete the old list of links
561       msql_query("delete from wikilinks where frompage='$frompage'",
562                 $dbi["dbc"]);
563
564       // the page may not have links, return if not
565       if (! count($linklist))
566          return;
567       // now insert the new list of links
568       while (list($topage, $count) = each($linklist)) {
569          $topage = addslashes($topage);
570          if($topage != $frompage) {
571             msql_query("insert into wikilinks (frompage, topage) " .
572                      "values ('$frompage', '$topage')", $dbi["dbc"]);
573          }
574       }
575
576       msql_query("delete from wikiscore", $dbi["dbc"]);
577       msql_query("insert into wikiscore select w1.topage, count(*) from wikilinks as w1, wikilinks as w2 where w2.topage=w1.frompage group by w1.topage", $dbi["dbc"]);
578    }
579 */
580
581 ?>