]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/mysql.php
rel1.2.8: upcase statements, mysql_pconnect => mysql_connect
[SourceForge/phpwiki.git] / lib / mysql.php
1 <?php rcs_id('$Id: mysql.php,v 1.10.2.8 2005-07-23 11:15:48 rurban Exp $');
2
3    /*
4       Database functions:
5       OpenDataBase($dbname)
6       CloseDataBase($dbi)
7       MakeDBHash($pagename, $pagehash)
8       MakePageHash($dbhash)
9       RetrievePage($dbi, $pagename, $pagestore)
10       InsertPage($dbi, $pagename, $pagehash)
11       SaveCopyToArchive($dbi, $pagename, $pagehash)
12       IsWikiPage($dbi, $pagename)
13       IsInArchive($dbi, $pagename)
14       RemovePage($dbi, $pagename)
15       IncreaseHitCount($dbi, $pagename)
16       GetHitCount($dbi, $pagename)
17       MakeSQLSearchClause($search, $column)
18       InitTitleSearch($dbi, $search)
19       TitleSearchNextMatch($dbi, $res)
20       InitFullSearch($dbi, $search)
21       FullSearchNextMatch($dbi, $res)
22       InitBackLinkSearch($dbi, $pagename) 
23       BackLinkSearchNextMatch($dbi, &$pos) 
24       InitMostPopular($dbi, $limit)
25       MostPopularNextMatch($dbi, $res)
26       GetAllWikiPageNames($dbi)
27       GetWikiPageLinks($dbi, $pagename)
28       SetWikiPageLinks($dbi, $pagename, $linklist)
29    */
30
31    // open a database and return the handle
32    // ignores MAX_DBM_ATTEMPTS
33
34    function OpenDataBase($dbname) {
35       global $mysql_server, $mysql_user, $mysql_pwd, $mysql_db;
36
37       // smaller servers might benefit from mysql_pconnect, but larger ones 
38       // may run out of connections
39       if (!($dbc = mysql_connect($mysql_server, $mysql_user, $mysql_pwd))) {
40          $msg = gettext ("Cannot establish connection to database, giving up.");
41          $msg .= "<br />";
42          $msg .= sprintf(gettext ("MySQL error: %s"), mysql_error());
43          ExitWiki($msg);
44       }
45       if (!mysql_select_db($mysql_db, $dbc)) {
46          $msg =  sprintf(gettext ("Cannot open database %s, giving up."), $mysql_db);
47          $msg .= "<br />";
48          $msg .= sprintf(gettext ("MySQL error: %s"), mysql_error());
49          ExitWiki($msg);
50       }
51       $dbi['dbc'] = $dbc;
52       $dbi['table'] = $dbname;
53       return $dbi;
54    }
55
56
57    function CloseDataBase($dbi) {
58       // NOP function
59       // mysql connections are established as persistant
60       // they cannot be closed through mysql_close()
61    }
62
63
64    // prepare $pagehash for storing in mysql
65    function MakeDBHash($pagename, $pagehash)
66    {
67       $pagehash["pagename"] = addslashes($pagename);
68       if (!isset($pagehash["flags"]))
69          $pagehash["flags"] = 0;
70       $pagehash["author"] = addslashes($pagehash["author"]);
71       $pagehash["content"] = implode("\n", $pagehash["content"]);
72       $pagehash["content"] = addslashes($pagehash["content"]);
73       if (!isset($pagehash["refs"]))
74          $pagehash["refs"] = array();
75       $pagehash["refs"] = serialize($pagehash["refs"]);
76  
77       return $pagehash;
78    }
79
80
81    // convert mysql result $dbhash to $pagehash
82    function MakePageHash($dbhash)
83    {
84       // unserialize/explode content
85       $dbhash['refs'] = unserialize($dbhash['refs']);
86       $dbhash['content'] = explode("\n", $dbhash['content']);
87       return $dbhash;
88    }
89
90
91    // Return hash of page + attributes or default
92    function RetrievePage($dbi, $pagename, $pagestore) {
93       $pagename = addslashes($pagename);
94       if ($res = mysql_query("SELECT * FROM $pagestore WHERE pagename='$pagename'", $dbi['dbc'])) {
95          if ($dbhash = mysql_fetch_array($res)) {
96             return MakePageHash($dbhash);
97          }
98       }
99       return -1;
100    }
101
102
103    // Either insert or replace a key/value (a page)
104    function InsertPage($dbi, $pagename, $pagehash)
105    {
106       global $WikiPageStore; // ugly hack
107
108       if ($dbi['table'] == $WikiPageStore) { // HACK
109          $linklist = ExtractWikiPageLinks($pagehash['content']);
110          SetWikiPageLinks($dbi, $pagename, $linklist);
111       }
112
113       $pagehash = MakeDBHash($pagename, $pagehash);
114
115       $COLUMNS = "author, content, created, flags, " .
116                  "lastmodified, pagename, refs, version";
117
118       $VALUES =  "'$pagehash[author]', '$pagehash[content]', " .
119                  "$pagehash[created], $pagehash[flags], " .
120                  "$pagehash[lastmodified], '$pagehash[pagename]', " .
121                  "'$pagehash[refs]', $pagehash[version]";
122
123       if (!mysql_query("REPLACE INTO ".$dbi['table']." ($COLUMNS) VALUES ($VALUES)",
124                         $dbi['dbc'])) {
125             $msg = sprintf(gettext ("Error writing page '%s'"), $pagename);
126             $msg .= "<br />";
127             $msg .= sprintf(gettext ("MySQL error: %s"), mysql_error());
128             ExitWiki($msg);
129       }
130    }
131
132
133    // for archiving pages to a seperate dbm
134    function SaveCopyToArchive($dbi, $pagename, $pagehash) {
135       global $ArchivePageStore;
136       $adbi = OpenDataBase($ArchivePageStore);
137       InsertPage($adbi, $pagename, $pagehash);
138    }
139
140
141    function IsWikiPage($dbi, $pagename) {
142       $pagename = addslashes($pagename);
143       if ($res = mysql_query("SELECT COUNT(*) FROM ".$dbi['table']." WHERE pagename='$pagename'", 
144                              $dbi['dbc'])) {
145          return(mysql_result($res, 0));
146       }
147       return 0;
148    }
149
150    function IsInArchive($dbi, $pagename) {
151       global $ArchivePageStore;
152
153       $pagename = addslashes($pagename);
154       if ($res = mysql_query("SELECT COUNT(*) FROM $ArchivePageStore WHERE pagename='$pagename'", 
155                              $dbi['dbc'])) {
156          return(mysql_result($res, 0));
157       }
158       return 0;
159    }
160
161
162    function RemovePage($dbi, $pagename) {
163       global $WikiPageStore, $ArchivePageStore;
164       global $WikiLinksStore, $HitCountStore, $WikiScoreStore;
165
166       $pagename = addslashes($pagename);
167       $msg = gettext ("Cannot delete '%s' from table '%s'");
168       $msg .= "<br>\n";
169       $msg .= gettext ("MySQL error: %s");
170
171       if (!mysql_query("DELETE FROM $WikiPageStore WHERE pagename='$pagename'", $dbi['dbc']))
172          ExitWiki(sprintf($msg, $pagename, $WikiPageStore, mysql_error()));
173
174       if (!mysql_query("DELETE FROM $ArchivePageStore WHERE pagename='$pagename'", $dbi['dbc']))
175          ExitWiki(sprintf($msg, $pagename, $ArchivePageStore, mysql_error()));
176
177       if (!mysql_query("DELETE FROM $WikiLinksStore WHERE frompage='$pagename'", $dbi['dbc']))
178          ExitWiki(sprintf($msg, $pagename, $WikiLinksStore, mysql_error()));
179
180       if (!mysql_query("DELETE FROM $HitCountStore WHERE pagename='$pagename'", $dbi['dbc']))
181          ExitWiki(sprintf($msg, $pagename, $HitCountStore, mysql_error()));
182
183       if (!mysql_query("DELETE FROM $WikiScoreStore WHERE pagename='$pagename'", $dbi['dbc']))
184          ExitWiki(sprintf($msg, $pagename, $WikiScoreStore, mysql_error()));
185    }
186
187
188    function IncreaseHitCount($dbi, $pagename)
189    {
190       global $HitCountStore;
191
192       $qpagename = addslashes($pagename);
193       $res = mysql_query("UPDATE $HitCountStore SET hits=hits+1"
194                          . " WHERE pagename='$qpagename'",
195                          $dbi['dbc']);
196
197       if (!mysql_affected_rows($dbi['dbc'])) {
198          $res = mysql_query("INSERT INTO $HitCountStore (pagename, hits)"
199                             . " VALUES ('$qpagename', 1)",
200                             $dbi['dbc']);
201       }
202
203       return $res;
204    }
205
206    function GetHitCount($dbi, $pagename)
207    {
208       global $HitCountStore;
209
210       $qpagename = addslashes($pagename);
211       $res = mysql_query("SELECT hits FROM $HitCountStore"
212                          . " WHERE pagename='$qpagename'",
213                          $dbi['dbc']);
214       if (mysql_num_rows($res))
215          $hits = mysql_result($res, 0);
216       else
217          $hits = "0";
218
219       return $hits;
220    }
221
222    function MakeSQLSearchClause($search, $column)
223    {
224       $search = preg_replace("/\s+/", " ", trim($search));
225       $search = preg_replace('/(?=[%_\\\\])/', "\\", $search);
226       $search = addslashes($search);
227       
228       $term = strtok($search, ' ');
229       $clause = '';
230       while($term) {
231          $word = strtolower("$term");
232          if ($word[0] == '-') {
233             $word = substr($word, 1);
234             $clause .= "NOT (LCASE($column) LIKE '%$word%') ";
235          } else {
236             $clause .= "(LCASE($column) LIKE '%$word%') ";
237          }
238          if ($term = strtok(' '))
239             $clause .= 'AND ';
240       }
241       
242       return $clause;
243    }
244
245    // setup for title-search
246    function InitTitleSearch($dbi, $search) {
247       $clause = MakeSQLSearchClause($search, 'pagename');
248       $res = mysql_query("SELECT pagename FROM ".$dbi['table']." WHERE $clause ORDER BY pagename", 
249                          $dbi["dbc"]);
250       return $res;
251    }
252
253
254    // iterating through database
255    function TitleSearchNextMatch($dbi, $res) {
256       if($o = mysql_fetch_object($res)) {
257          return $o->pagename;
258       }
259       else {
260          return 0;
261       }
262    }
263
264
265    // setup for full-text search
266    function InitFullSearch($dbi, $search) {
267       $clause = MakeSQLSearchClause($search, 'content');
268       $res = mysql_query("SELECT * FROM ".$dbi['table']." WHERE $clause", $dbi["dbc"]);
269
270       return $res;
271    }
272
273    // iterating through database
274    function FullSearchNextMatch($dbi, $res) {
275       if($hash = mysql_fetch_array($res)) {
276          return MakePageHash($hash);
277       }
278       else {
279          return 0;
280       }
281    }
282
283    // setup for back-link search
284    function InitBackLinkSearch($dbi, $pagename) {
285       global $WikiLinksStore;
286      
287       $topage = addslashes($pagename);
288       $res = mysql_query( "SELECT DISTINCT frompage FROM $WikiLinksStore"
289                           . " WHERE topage='$topage'"
290                           . " ORDER BY frompage",
291                           $dbi["dbc"]);
292       return $res;
293    }
294
295
296    // iterating through database
297    function BackLinkSearchNextMatch($dbi, $res) {
298       if($a = mysql_fetch_row($res)) {
299          return $a[0];
300       }
301       else {
302          return 0;
303       }
304    }
305
306
307    function InitMostPopular($dbi, $limit) {
308       global $HitCountStore;
309       $res = mysql_query("SELECT * FROM $HitCountStore ORDER BY hits desc, pagename LIMIT $limit", 
310                          $dbi["dbc"]);
311       
312       return $res;
313    }
314
315    function MostPopularNextMatch($dbi, $res) {
316       if ($hits = mysql_fetch_array($res))
317          return $hits;
318       else
319          return 0;
320    }
321
322    function GetAllWikiPageNames($dbi) {
323       global $WikiPageStore;
324       $res = mysql_query("SELECT pagename FROM $WikiPageStore", $dbi["dbc"]);
325       $rows = mysql_num_rows($res);
326       for ($i = 0; $i < $rows; $i++) {
327          $pages[$i] = mysql_result($res, $i);
328       }
329       return $pages;
330    }
331    
332    
333    ////////////////////////////////////////
334    // functionality for the wikilinks table
335
336    // takes a page name, returns array of scored incoming and outgoing links
337    function GetWikiPageLinks($dbi, $pagename) {
338       global $WikiLinksStore, $WikiScoreStore, $HitCountStore;
339
340       $pagename = addslashes($pagename);
341       $res = mysql_query("SELECT topage, score FROM $WikiLinksStore, $WikiScoreStore"
342                          ." WHERE topage=pagename AND frompage='$pagename'"
343                          ." ORDER BY score DESC, topage");
344       $rows = mysql_num_rows($res);
345       for ($i = 0; $i < $rows; $i++) {
346          $out = mysql_fetch_array($res);
347          $links['out'][] = array($out['topage'], $out['score']);
348       }
349
350       $res = mysql_query("SELECT frompage, score FROM $WikiLinksStore, $WikiScoreStore"
351                          ." WHERE frompage=pagename AND topage='$pagename'"
352                          ." ORDER BY score DESC, frompage");
353       $rows = mysql_num_rows($res);
354       for ($i = 0; $i < $rows; $i++) {
355          $out = mysql_fetch_array($res);
356          $links['in'][] = array($out['frompage'], $out['score']);
357       }
358
359       $res = mysql_query("SELECT DISTINCT pagename, hits FROM $WikiLinksStore, $HitCountStore"
360                          ." WHERE (frompage=pagename AND topage='$pagename')"
361                          ." OR (topage=pagename and frompage='$pagename')"
362                          ." ORDER BY hits DESC, pagename");
363       $rows = mysql_num_rows($res);
364       for ($i = 0; $i < $rows; $i++) {
365          $out = mysql_fetch_array($res);
366          $links['popular'][] = array($out['pagename'], $out['hits']);
367       }
368
369       return $links;
370    }
371
372
373    // takes page name, list of links it contains
374    // the $linklist is an array where the keys are the page names
375    function SetWikiPageLinks($dbi, $pagename, $linklist) {
376       global $WikiLinksStore, $WikiScoreStore;
377
378       $frompage = addslashes($pagename);
379
380       // first delete the old list of links
381       mysql_query("DELETE FROM $WikiLinksStore WHERE frompage='$frompage'",
382                 $dbi["dbc"]);
383
384       // the page may not have links, return if not
385       if (! count($linklist))
386          return;
387       // now insert the new list of links
388       while (list($topage, $count) = each($linklist)) {
389          $topage = addslashes($topage);
390          if($topage != $frompage) {
391             mysql_query("INSERT INTO $WikiLinksStore (frompage, topage)"
392                         ." VALUES ('$frompage', '$topage')", $dbi["dbc"]);
393          }
394       }
395
396       // update pagescore
397       mysql_query("DELETE FROM $WikiScoreStore", $dbi["dbc"]);
398       mysql_query("INSERT INTO $WikiScoreStore"
399                   ." SELECT w1.topage, COUNT(*) FROM $WikiLinksStore AS w1, $WikiLinksStore AS w2"
400                   ." WHERE w2.topage=w1.frompage GROUP BY w1.topage", $dbi["dbc"]);
401    }
402
403 /* more mysql queries:
404
405 orphans:
406 select pagename from wiki left join wikilinks on pagename=topage where topage is NULL;
407 */
408 ?>