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