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