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