No need to declare superglobals global
[infodrom.org/www.zeitungsliste.de] / lib / functions.inc
1 <?php
2
3 /*
4  * ==================== Configuration of/for the platform ===============
5  */
6 $pages = array('logout.html' => array('lib' => 'login.inc',
7                                       'func' => 'logout'),
8                'login.html' => array('lib' => 'login.inc',
9                                      'func' => 'process_login'),
10                'activate.html' => array('lib' => 'login.inc',
11                                         'func' => 'process_activate'),
12                'passwd.html' => array('lib' => 'login.inc',
13                                       'func' => 'process_passwd'),
14                'options.html' => array('lib' => 'login.inc',
15                                        'func' => 'process_options'),
16                'search.html' => array('lib' => 'search.inc',
17                                       'func' => 'process_search'),
18                'topic.html' => array('lib' => 'board.inc',
19                                      'func' => 'process_topic'),
20                'reply.html' => array('lib' => 'board.inc',
21                                      'func' => 'process_reply'),
22                'tags.html' => array('lib' => 'tags.inc',
23                                      'func' => 'process_tags'),
24                'edit.html' => array('lib' => 'zeitung.inc',
25                                    'func' => 'process_edit'),
26                'new.html' => array('lib' => 'zeitung.inc',
27                                    'func' => 'process_new'),
28                'bookmark.html' => array('lib' => 'bookmarks.inc',
29                                         'func' => 'process_bookmark'),
30                'contact.html' => array('func' => 'process_contact'),
31                'sitemap.html' => array('lib' => 'layout.inc',
32                                        'func' => 'layout_sitemap'),
33                );
34
35 $dirs = array('zeitung' => array('func' => 'layout_showpaper'),
36               'archiv' => array('func' => 'layout_archive'),
37               'tag' => array('func' => 'layout_showtag'),
38               'topic' => array('func' => 'layout_topic'),
39               'admin' => array('lib' => 'admin.inc',
40                                'func' => 'layout_admin'),
41               );
42
43
44 /*
45  * ==================== Commonly use code ===============================
46  */
47 include_once('layout.inc');
48
49 function carp($msg)
50 {
51   error_log($msg);
52   exit;
53 }
54
55 function userstatus()
56 {
57   if (isset($_SESSION['uid']))
58     $info = array($_SESSION['online'], $_SESSION['users'], $_SESSION['zeitungen'],
59                   $_SESSION['ztags'], $_SESSION['tags']);
60   else
61     $info = userstatus_info();
62   
63   return sprintf('%d Nutzer von %d online | %d Zeitungen | Bewertungen: %d | Tags: %d',
64                  $info[0], $info[1], $info[2], $info[3], $info[4]);
65 }
66
67 function dispatch()
68 {
69   global $cfg;
70   global $zlist;
71   global $pages;
72   global $dirs;
73
74   $zlist['info'] = array('info_searchform', 'info_new', 'info_tags', 'info_tagcloud',
75                          'info_actions', 'info_bookmarks','info_hitlist');
76
77   if (strlen($cfg['path']) && array_key_exists($cfg['path'], $pages)) {
78       if (array_key_exists('lib', $pages[$cfg['path']]))
79         include_once($pages[$cfg['path']]['lib']);
80       if (array_key_exists('func', $pages[$cfg['path']])) {
81         if (function_exists($pages[$cfg['path']]['func']))
82           $body = $pages[$cfg['path']]['func']();
83         else
84           $body = notfound();
85       }
86   } elseif (strlen($cfg['dir']) && array_key_exists($cfg['dir'], $dirs)) {
87       if (array_key_exists('lib', $dirs[$cfg['dir']]))
88         include_once($dirs[$cfg['dir']]['lib']);
89       if (array_key_exists('func', $dirs[$cfg['dir']])) {
90         if (function_exists($dirs[$cfg['dir']]['func']))
91           $body = $dirs[$cfg['dir']]['func']();
92         else
93           $body = notfound();
94       }
95   } elseif (empty($_SERVER['QUERY_STRING']) &&
96            empty($cfg['path']) && empty($cfg['dir'])) {
97     $body .= load_template('main.html');
98     $zlist['page'] = 'index';
99   } else {
100     $body = notfound();
101   }
102
103   return layout_page($body);
104 }
105
106 function tagcloud_min()
107 {
108   $query = 'SELECT count(uid) AS count FROM zeitung_tags GROUP BY zeitung,tag ORDER BY count ASC LIMIT 1';
109
110   $sth = db_query($query);
111
112   if ($sth === false)
113     return 1;
114
115   if (pg_num_rows($sth) === 0)
116     return 1;
117
118   $row = pg_fetch_array($sth, 0);
119   return $row['count'];
120 }
121
122 function tagcloud_max()
123 {
124   $query = 'SELECT count(uid) AS count FROM zeitung_tags GROUP BY zeitung,tag ORDER BY count DESC LIMIT 1';
125
126   $sth = db_query($query);
127
128   if ($sth === false)
129     return 10;
130
131   if (pg_num_rows($sth) === 0)
132     return 10;
133
134   $row = pg_fetch_array($sth, 0);
135   return $row['count'];
136 }
137
138 function tag_class($count)
139 {
140   if (isset($_SESSION['uid'])) {
141     if (!isset($_SESSION['tagcloud_lastupdate']) ||
142         $_SESSION["tagcloud_lastupdate"] < time() - 60*60*12) {
143       $min = $_SESSION["tagcloud_min"] = tagcloud_min();
144       $max = $_SESSION["tagcloud_max"] = tagcloud_max();
145       $_SESSION["tagcloud_lastupdate"] = time();
146     }
147   }
148
149   if (!isset($min)) {
150     $min = tagcloud_min();
151     $max = tagcloud_max();
152   }
153
154   if ($count > (int)($min + ($max - $min) * 0.8))
155     return 4;
156   elseif ($count > (int)($min + ($max - $min) * 0.6))
157     return 3;
158   elseif ($count > (int)($min + ($max - $min) * 0.4))
159     return 2;
160   elseif ($count > (int)($min + ($max - $min) * 0.2))
161     return 1;
162   else
163     return 0;
164 }
165
166 function load_template($template, $replace=false)
167 {
168   global $cfg;
169
170   $fname = $cfg['tmpldir'] . '/' . $template;
171   if (!file_exists($fname))
172     return false;
173
174   $f = fopen($fname, 'r');
175   $content = fread($f, filesize($fname));
176   fclose($f);
177
178   if (preg_match_all('/@([^@]+)@/', $content, $matches)) {
179     $fields = array();
180     $values = array();
181
182     $found = array_unique($matches[1]);
183
184     foreach ($found as $field) {
185       $fields[] = '/@'.$field.'@/';
186       if ($replace != false && array_key_exists($field, $replace))
187         $values[] = $replace[$field];
188       else
189         $values[] = '';
190     }
191
192     $content = preg_replace($fields, $values, $content);
193   }
194
195   return $content;
196 }
197
198 function load_javascript($file)
199 {
200   global $cfg;
201
202   if (!javascript_ok())
203     return;
204
205   $fname = $cfg['tmpldir'] . '/' . $file;
206   if (!file_exists($fname))
207     return;
208
209   $f = fopen($fname, 'r');
210   $content = fread($f, filesize($fname));
211   fclose($f);
212
213   $ret = "\n" . '<script type="text/javascript"><!--' . "\n";
214   $ret .= $content;
215   $ret .= "\n" . '//--></script>' . "\n";
216
217   return $ret;
218 }
219
220 function format_date($date)
221 {
222   setlocale(LC_TIME, "de_DE.UTF-8");
223
224   return strftime("%e. %B %Y, %H:%M", strtotime($date));
225 }
226
227 function format_newspaper($id)
228 {
229   global $cfg;
230   global $zlist;
231
232   $query = sprintf("SELECT * FROM zeitungen WHERE id = %d AND deleted IS false", $id);
233
234   $sth = db_query($query) or carp("format_newspaper");
235
236   if (pg_num_rows ($sth) == 0)
237     return false;
238
239   $row = pg_fetch_array ($sth, 0);
240
241   $ret = '<div class="newspaper">';
242   $ret .= sprintf('<h3>%s</h3>', $row['name']);
243   $zlist['newspaper'] = $row['name'];
244   $zlist['city'] = $row['city'];
245
246   $ret .= sprintf('<p>%s<br>Ort: %s<br>URL: <a href="%s"><code>%s</code></a></p>',
247                   $row['description'], $row['city'],
248                   $row['url'], $row['url']);
249   $ret .= '</div>';
250
251   return $ret;
252 }
253
254 function format_topten($uid)
255 {
256   global $cfg;
257
258   if ($uid > 0)
259     $query = sprintf("SELECT zeitung,name,counter FROM hits " .
260                      "INNER JOIN zeitungen ON id = zeitung " .
261                      "WHERE deleted IS false AND uid = %d " .
262                      "ORDER BY counter DESC LIMIT 10", $uid);
263   else
264     $query = "SELECT zeitung,name,sum(counter) as counter FROM hits " .
265              "INNER JOIN zeitungen ON id = zeitung " .
266              "WHERE deleted IS false " .
267              "GROUP BY zeitung,name ORDER BY counter DESC LIMIT 10";
268
269   $sth = db_query($query) or carp("format_topten");
270
271   if (pg_num_rows ($sth) == 0)
272     return;
273
274   $ret = '<h3>Top 10</h3>';
275   $ret .= '<p><ul>';
276   for ($n=0; $n < pg_num_rows ($sth); $n++) {
277     $row = pg_fetch_array ($sth, $n);
278     $ret .= sprintf('<li><a href="%szeitung/%d.html">%s</a></li>',
279                     $cfg['basepath'], $row['zeitung'], $row['name']);
280   }
281   $ret .= '</ul></p>';
282
283   return $ret;
284 }
285
286 function format_topic($topic)
287 {
288   global $cfg;
289   global $zlist;
290
291   $query = sprintf("SELECT topic,archived,zeitung FROM topics WHERE id = %d",
292                    $topic);
293
294   if (($sth = db_query($query)) === false)
295     return warning('Es ist ein Datenbankfehler aufgetreten.');
296
297   if (pg_num_rows ($sth) == 0)
298     return warning('Keine passende Diskussion gefunden.');
299
300   if (($info = pg_fetch_array ($sth, 0)) == false)
301     return warning('Es ist ein Datenbankfehler aufgetreten.');
302
303   $query = sprintf("SELECT nickname,url,created,body FROM article " .
304                    "JOIN users ON users.id = uid " .
305                    "WHERE topic = %d AND article.status = 1 " .
306                    "ORDER BY created", $topic);
307
308   if (($sth2 = db_query($query)) === false) return false;
309
310   if (pg_num_rows ($sth2) > 0) {
311     $ret .= '<div class="topic">';
312     $ret .= sprintf ('<h3>%s</h3>', htmlspecialchars($info['topic']));
313     $col = 0;
314     $zlist['zid'] = $info['zeitung'];
315     $zlist['topic'] = $info['topic'];
316     $zlist['archived'] = $info['archived'] == 't';
317
318     for ($j=0; $j < pg_num_rows ($sth2); $j++) {
319       $row = pg_fetch_array ($sth2, $j);
320
321       $ret .= sprintf('<div class="art%d">', $col);
322
323       if (strlen($row['url']))
324         $author = sprintf('<a href="%s">%s</a>', $row['url'], $row['nickname']);
325       else
326         $author = $row['nickname'];
327
328       $ret .= sprintf('<p><b>%s</b>, %s</p>', $author, format_date($row['created']));
329       $ret .= sprintf('<p>%s</p>', $row['body']);
330       $ret .= '</div>';
331       $col = 1-$col;
332     }
333
334     if ($info['archived'] == 'f' &&
335         strpos($_SERVER['REQUEST_URI'], "/reply.html", 0) === false) {
336       $ret .= '<div class="buttons"><p>';
337       if (logged_in()) {
338         $link_rep = sprintf('%sreply.html?topic=%d', $cfg['basepath'], $topic);
339       } else {
340         $link_rep = sprintf('%slogin.html?from=article', $cfg['basepath']);
341       }
342
343       $ret .= sprintf('<img src="%santworten.gif" width="21" height="17">&nbsp;', $cfg['basepath']);
344       $ret .= sprintf('<a href="%s"><strong>antworten</strong></a>', $link_rep);
345       $ret .= '</p></div>';
346     }
347       
348     $ret .= '</div>';
349   }
350   return $ret;
351 }
352
353 function format_board($zid, $archived=false)
354 {
355   global $cfg;
356   global $zlist;
357
358   $query = sprintf("SELECT id FROM topics " .
359                    "WHERE zeitung = %d AND archived IS %s " .
360                    "ORDER BY created DESC", $zid,
361                    $archived?'true':'false');
362
363   if (($sth = db_query($query)) === false) return false;
364
365   if (pg_num_rows ($sth) == 0 && !$archived) {
366     $zlist['notopic'] = true;
367
368     return $ret;
369   }
370
371   if (pg_num_rows ($sth) > 0) {
372     if ($archived)
373       $ret = '<h3>Abgeschlossene Diskussionen</h3>';
374     else
375       $ret = '<h3>Diskussion</h3>';
376   }
377
378   for ($i=0; $i < pg_num_rows ($sth); $i++) {
379     $row = pg_fetch_array ($sth, $i);
380
381     $ret .= format_topic($row['id']);
382   }
383
384   return $ret;
385 }
386
387 function fix_url($url) {
388   if (!strlen($url))
389     return false;
390
391   if (strpos($url, "http://") === false)
392     $url = "http://" . $url;
393
394   $parts = parse_url($url);
395
396   if ($parts === false)
397     return false;
398
399   if (empty($parts['path']))
400     $url .= '/';
401
402   return $url;
403 }
404
405 function is_valid_url($url) {
406   if (strpos($url, '.') === false)
407     return false;
408
409   $parts = parse_url($url);
410
411   if (empty($parts['host']) || empty($parts['scheme']) || empty($parts['path']))
412     return false;
413
414   if ($parts['scheme'] != 'http' && $parts['scheme'] != 'https')
415     return false;
416
417   if (!preg_match ('/^[a-zA-Z][a-zA-Z0-9\.-]+$/', $parts['host'], $matches))
418     return false;
419
420   if (preg_match ('/[\\\\<>"\'\(\)\[\]]/', $parts['path'], $matches))
421     return false;
422
423   if (!empty($parts['query']) && preg_match ('/[\\\\<>"\'\(\)\[\]]/', $parts['query'], $matches))
424     return false;
425
426   return true;
427 }
428
429 function ajax_check_url()
430 {
431   if (!empty($_POST['url']) && is_valid_url($_POST['url']))
432     return true;
433
434   return false;
435 }
436
437 function sendmail($to, $name, $subject, $body, $header=array())
438 {
439   global $cfg;
440
441   if (empty($to))
442     return false;
443
444   $header[] = 'From: ' . $cfg['from'];
445   if (empty($name))
446     $header[] = 'To: ' . $to;
447   else
448     $header[] = sprintf('To: %s <%s>', $name, $to);
449   $header[] = 'MIME-Version: 1.0';
450   $header[] = 'Content-type: text/plain; charset=utf-8';
451   $header[] = 'Content-Disposition: inline';
452   $header[] = 'Content-Transfer-Encoding: 8bit';
453
454   $sig = load_template('signature');
455   if (!empty($sig))
456     $body .= $sig;
457
458   $subject = mb_encode_mimeheader($subject,"UTF-8", "Q", "\n");
459
460   if (mail ($to, $subject, $body, implode("\n", $header)) === false)
461     return false;
462
463   return true;
464 }
465
466 function logbook($table,$refid,$column,$old,$new)
467 {
468   $query = sprintf("INSERT INTO logbook (uid,tab,refid,col,oldval,newval,modified) " .
469                    "VALUES (%d,'%s',%d,'%s','%s','%s',now())",
470                    $_SESSION['uid'], $table,$refid,$column,
471                    pg_escape_string($old),
472                    pg_escape_string($new));
473
474   db_query($query);
475 }
476
477 function hits_inc($zeitung)
478 {
479   global $cfg;
480
481   if (is_spider())
482     return;
483
484   $uid = isset($_SESSION['uid'])?$_SESSION['uid']:0;
485
486   $query = sprintf("SELECT counter FROM hits WHERE uid = %d AND zeitung = %d", $uid, $zeitung);
487
488   $sth = db_query($query);
489
490   if (pg_num_rows ($sth) == 0)
491     $query = sprintf("INSERT INTO hits (zeitung,uid,counter) " .
492                      "VALUES (%d,%d,1)", $zeitung, $uid);
493   else
494     $query = sprintf("UPDATE hits SET counter = counter + 1 " .
495                      "WHERE zeitung = %d AND uid = %d", $zeitung, $uid);
496
497   db_query($query);
498 }