]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
before and after are switched, pass QSA in some rewrite rules
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
21
22 # Show a server error
23
24 function common_server_error($msg, $code=500) {
25         static $status = array(500 => 'Internal Server Error',
26                                                    501 => 'Not Implemented',
27                                                    502 => 'Bad Gateway',
28                                                    503 => 'Service Unavailable',
29                                                    504 => 'Gateway Timeout',
30                                                    505 => 'HTTP Version Not Supported');
31
32         if (!array_key_exists($code, $status)) {
33                 $code = 500;
34         }
35
36         $status_string = $status[$code];
37
38         header('HTTP/1.1 '.$code.' '.$status_string);
39         header('Content-type: text/plain');
40
41         print $msg;
42         print "\n";
43         exit();
44 }
45
46 # Show a user error
47 function common_user_error($msg, $code=400) {
48         static $status = array(400 => 'Bad Request',
49                                                    401 => 'Unauthorized',
50                                                    402 => 'Payment Required',
51                                                    403 => 'Forbidden',
52                                                    404 => 'Not Found',
53                                                    405 => 'Method Not Allowed',
54                                                    406 => 'Not Acceptable',
55                                                    407 => 'Proxy Authentication Required',
56                                                    408 => 'Request Timeout',
57                                                    409 => 'Conflict',
58                                                    410 => 'Gone',
59                                                    411 => 'Length Required',
60                                                    412 => 'Precondition Failed',
61                                                    413 => 'Request Entity Too Large',
62                                                    414 => 'Request-URI Too Long',
63                                                    415 => 'Unsupported Media Type',
64                                                    416 => 'Requested Range Not Satisfiable',
65                                                    417 => 'Expectation Failed');
66
67         if (!array_key_exists($code, $status)) {
68                 $code = 400;
69         }
70
71         $status_string = $status[$code];
72
73         header('HTTP/1.1 '.$code.' '.$status_string);
74
75         common_show_header('Error');
76         common_element('div', array('class' => 'error'), $msg);
77         common_show_footer();
78 }
79
80 $xw = null;
81
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
84         global $xw;
85         $xw->startElement($tag);
86         if (is_array($attrs)) {
87                 foreach ($attrs as $name => $value) {
88                         $xw->writeAttribute($name, $value);
89                 }
90         } else if (is_string($attrs)) {
91                 $xw->writeAttribute('class', $attrs);
92         }
93 }
94
95 function common_element_end($tag) {
96         global $xw;
97         $xw->endElement();
98 }
99
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101     common_element_start($tag, $attrs);
102         if ($content) {
103                 global $xw;
104                 $xw->text($content);
105         }
106         common_element_end($tag);
107 }
108
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
110         global $xw;
111         $xw = new XMLWriter();
112         $xw->openURI('php://output');
113         $xw->setIndent(true);
114         $xw->startDocument('1.0', 'UTF-8');
115         if ($doc) {
116                 $xw->writeDTD($doc, $public, $system);
117         }
118 }
119
120 function common_end_xml() {
121         global $xw;
122         $xw->endDocument();
123         $xw->flush();
124 }
125
126 define('PAGE_TYPE_PREFS', 'application/xhtml+xml,text/html;q=0.7,application/xml;q=0.3,text/xml;q=0.2');
127            
128 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
129         global $config, $xw;
130
131         $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
132
133         # XXX: allow content negotiation for RDF, RSS, or XRDS
134         
135         $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
136                                                                   common_accept_to_prefs(PAGE_TYPE_PREFS));
137
138         if (!$type) {
139                 common_client_error(_t('This page is not available in a media type you accept'), 406);
140                 exit(0);
141         }
142         
143         header('Content-Type: '.$type);
144
145         common_start_xml('html',
146                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
147                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
148
149         # FIXME: correct language for interface
150
151         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
152                                                                            'xml:lang' => 'en',
153                                                                            'lang' => 'en'));
154
155         common_element_start('head');
156         common_element('title', NULL,
157                                    $pagetitle . " - " . $config['site']['name']);
158         common_element('link', array('rel' => 'stylesheet',
159                                                                  'type' => 'text/css',
160                                                                  'href' => theme_path('display.css'),
161                                                                  'media' => 'screen, projection, tv'));
162         foreach (array(6,7) as $ver) {
163                 if (file_exists(theme_file('ie'.$ver.'.css'))) {
164                         # Yes, IE people should be put in jail.
165                         $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
166                                                           'href="'.theme_path('ie'.$ver.'.css').' /><![endif]');
167                 }
168         }
169         if ($callable) {
170                 if ($data) {
171                         call_user_func($callable, $data);
172                 } else {
173                         call_user_func($callable);
174                 }
175         }
176         common_element_end('head');
177         common_element_start('body');
178         common_element_start('div', array('id' => 'wrap'));
179         common_element_start('div', array('id' => 'header'));
180         common_nav_menu();
181         if ($config['site']['logo'] || file_exists(theme_file('logo.png'))) {
182                 common_element_start('a', array('href' => common_local_url('public')));
183                 common_element('img', array('src' => ($config['site']['logo']) ?
184                                                                         ($config['site']['logo']) : theme_path('logo.png'),
185                                                                         'alt' => $config['site']['name'],
186                                                                         'id' => 'logo'));
187                 common_element_end('a');
188         }
189         common_element('h1', 'pagetitle', $pagetitle);
190         common_element('h2', 'sitename', $config['site']['name']);
191         
192         if ($headercall) {
193                 if ($data) {
194                         call_user_func($headercall, $data);
195                 } else {
196                         call_user_func($headercall);
197                 }
198         }
199         common_element_end('div');
200         common_element_start('div', array('id' => 'content'));
201 }
202
203 function common_show_footer() {
204         global $xw, $config;
205         common_element_end('div'); # content div
206         common_foot_menu();
207         common_element_start('div', array('id' => 'footer'));
208         common_element_start('p', 'laconica');
209         common_text(_t('This site is running the '));
210         common_element('a', array('class' => 'software',
211                                                           href => 'http://laconi.ca/'),
212                                    'Laconica');
213         common_text(_t('microblogging tool, version ' . LACONICA_VERSION . ', available under the '));
214         common_element('a', array(href => 'http://www.fsf.org/licensing/licenses/agpl-3.0.html'),
215                                    'GNU Affero General Public License');
216         common_text(_t('.'));
217         common_element_end('p');
218         common_element('img', array('id' => 'cc',
219                                                                 'src' => $config['license']['image'],
220                                                                 'alt' => $config['license']['title']));
221         common_element_start('p');
222         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
223         common_element('a', array('class' => 'license',
224                                                           'rel' => 'license',
225                                                           href => $config['license']['url']),
226                                    $config['license']['title']);
227         common_text(_t('. Contributors should be attributed by full name or nickname.'));
228         common_element_end('p');
229         common_element_end('div');
230         common_element_end('div');
231         common_element_end('body');
232         common_element_end('html');
233         common_end_xml();
234 }
235
236 function common_text($txt) {
237         global $xw;
238         $xw->text($txt);
239 }
240
241 function common_raw($xml) {
242         global $xw;
243         $xw->writeRaw($xml);
244 }
245
246 function common_nav_menu() {
247         $user = common_current_user();
248         common_element_start('ul', array('id' => 'nav'));
249         if ($user) {
250                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
251                                                  _t('Home'));
252         }
253         common_menu_item(common_local_url('public'), _t('Public'));
254         common_menu_item(common_local_url('doc', array('title' => 'help')),
255                                          _t('Help'));
256         if ($user) {
257                 common_menu_item(common_local_url('profilesettings'),
258                                                  _t('Settings'));
259                 common_menu_item(common_local_url('logout'),
260                                                  _t('Logout'));
261         } else {
262                 common_menu_item(common_local_url('login'), _t('Login'));
263                 common_menu_item(common_local_url('register'), _t('Register'));
264         }
265         common_element_end('ul');
266 }
267
268 function common_foot_menu() {
269         common_element_start('ul', array('id' => 'nav_sub'));
270         common_menu_item(common_local_url('doc', array('title' => 'about')),
271                                          _t('About'));
272         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
273                                          _t('Privacy'));
274         common_menu_item(common_local_url('doc', array('title' => 'source')),
275                                          _t('Source'));
276         common_element_end('ul');
277 }
278
279 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
280         $lattrs = array();
281         if ($is_selected) {
282                 $lattrs['class'] = 'current';
283         }
284         common_element_start('li', $lattrs);
285         $attrs['href'] = $url;
286         if ($title) {
287                 $attrs['title'] = $title;
288         }
289         common_element('a', $attrs, $text);
290         common_element_end('li');
291 }
292
293 function common_input($id, $label, $value=NULL,$instructions=NULL) {
294         common_element_start('p');
295         common_element('label', array('for' => $id), $label);
296         $attrs = array('name' => $id,
297                                    'type' => 'text',
298                                    'id' => $id);
299         if ($value) {
300                 $attrs['value'] = htmlspecialchars($value);
301         }
302         common_element('input', $attrs);
303         if ($instructions) {
304                 common_element('span', 'input_instructions', $instructions);
305         }
306         common_element_end('p');
307 }
308
309 function common_hidden($id, $value) {
310         common_element('input', array('name' => $id,
311                                                                   'type' => 'hidden',
312                                                                   'id' => $id,
313                                                                   'value' => $value));
314 }
315
316 function common_password($id, $label, $instructions=NULL) {
317         common_element_start('p');
318         common_element('label', array('for' => $id), $label);
319         $attrs = array('name' => $id,
320                                    'type' => 'password',
321                                    'id' => $id);
322         common_element('input', $attrs);
323         if ($instructions) {
324                 common_element('span', 'input_instructions', $instructions);
325         }
326         common_element_end('p');
327 }
328
329 function common_submit($id, $label) {
330         global $xw;
331         common_element_start('p');
332         common_element('input', array('type' => 'submit',
333                                                                   'id' => $id,
334                                                                   'name' => $id,
335                                                                   'value' => $label));
336         common_element_end('p');
337 }
338
339 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
340         common_element_start('p');
341         common_element('label', array('for' => $id), $label);
342         common_element('textarea', array('rows' => 3,
343                                                                          'cols' => 40,
344                                                                          'name' => $id,
345                                                                          'id' => $id),
346                                    ($content) ? $content : ' ');
347         if ($instructions) {
348                 common_element('span', 'input_instructions', $instructions);
349         }
350         common_element_end('p');
351 }
352
353 # salted, hashed passwords are stored in the DB
354
355 function common_munge_password($id, $password) {
356         return md5($id . $password);
357 }
358
359 # check if a username exists and has matching password
360 function common_check_user($nickname, $password) {
361         $user = User::staticGet('nickname', $nickname);
362         if (is_null($user)) {
363                 return false;
364         } else {
365                 return (0 == strcmp(common_munge_password($password, $user->id),
366                                                         $user->password));
367         }
368 }
369
370 # is the current user logged in?
371 function common_logged_in() {
372         return (!is_null(common_current_user()));
373 }
374
375 function common_have_session() {
376         return (0 != strcmp(session_id(), ''));
377 }
378
379 function common_ensure_session() {
380         if (!common_have_session()) {
381                 @session_start();
382         }
383 }
384
385 function common_set_user($nickname) {
386         if (is_null($nickname) && common_have_session()) {
387                 unset($_SESSION['userid']);
388                 return true;
389         } else {
390                 $user = User::staticGet('nickname', $nickname);
391                 if ($user) {
392                         common_ensure_session();
393                         $_SESSION['userid'] = $user->id;
394                         return true;
395                 } else {
396                         return false;
397                 }
398         }
399         return false;
400 }
401
402 # who is the current user?
403 function common_current_user() {
404         static $user = NULL; # FIXME: global memcached
405         if (is_null($user)) {
406                 common_ensure_session();
407                 $id = $_SESSION['userid'];
408                 if ($id) {
409                         $user = User::staticGet($id);
410                 }
411         }
412         return $user;
413 }
414
415 # get canonical version of nickname for comparison
416 function common_canonical_nickname($nickname) {
417         # XXX: UTF-8 canonicalization (like combining chars)
418         return strtolower($nickname);
419 }
420
421 # get canonical version of email for comparison
422 function common_canonical_email($email) {
423         # XXX: canonicalize UTF-8
424         # XXX: lcase the domain part
425         return $email;
426 }
427
428 define('URL_REGEX', '^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))');
429
430 function common_render_content($text, $notice) {
431         $r = htmlspecialchars($text);
432         $id = $notice->profile_id;
433         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
434         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
435         # XXX: # tags
436         # XXX: machine tags
437         return $r;
438 }
439
440 function common_at_link($sender_id, $nickname) {
441         # Try to find profiles this profile is subscribed to that have this nickname
442         $recipient = new Profile();
443         # XXX: chokety and bad
444         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
445         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
446         if ($recipient->find(TRUE)) {
447                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
448         }
449         # Try to find profiles that listen to this profile and that have this nickname
450         $recipient = new Profile();
451         # XXX: chokety and bad
452         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
453         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
454         if ($recipient->find(TRUE)) {
455                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
456         }
457         # If this is a local user, try to find a local user with that nickname.
458         $sender = User::staticGet($sender_id);
459         if ($sender) {
460                 $recipient_user = User::staticGet('nickname', $nickname);
461                 if ($recipient_user) {
462                         $recipient = $recipient->getProfile();
463                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
464                 }
465         }
466         # Otherwise, no links. @messages from local users to remote users,
467         # or from remote users to other remote users, are just
468         # outside our ability to make intelligent guesses about
469         return $nickname;
470 }
471
472 // where should the avatar go for this user?
473
474 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
475         global $config;
476
477         if ($size) {
478                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
479         } else {
480                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
481         }
482 }
483
484 function common_avatar_path($filename) {
485         global $config;
486         return INSTALLDIR . '/avatar/' . $filename;
487 }
488
489 function common_avatar_url($filename) {
490         return common_path('avatar/'.$filename);
491 }
492
493 function common_default_avatar($size) {
494         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
495                                                           AVATAR_STREAM_SIZE => 'stream',
496                                                           AVATAR_MINI_SIZE => 'mini');
497         return theme_path('default-avatar-'.$sizenames[$size].'.png');
498 }
499
500 function common_local_url($action, $args=NULL) {
501         global $config;
502         if ($config['site']['fancy']) {
503                 return common_fancy_url($action, $args);
504         } else {
505                 return common_simple_url($action, $args);
506         }
507 }
508
509 function common_fancy_url($action, $args=NULL) {
510         switch (strtolower($action)) {
511          case 'public':
512                 if ($args && $args['page']) {
513                         return common_path('?page=' . $args['page']);
514                 } else {
515                         return common_path('');
516                 }
517          case 'publicrss':
518                 return common_path('rss');
519          case 'doc':
520                 return common_path('doc/'.$args['title']);
521          case 'login':
522          case 'logout':
523          case 'register':
524          case 'subscribe':
525          case 'unsubscribe':
526                 return common_path('main/'.$action);
527          case 'avatar':
528          case 'password':
529                 return common_path('settings/'.$action);
530          case 'profilesettings':
531                 return common_path('settings/profile');
532          case 'newnotice':
533                 return common_path('notice/new');
534          case 'shownotice':
535                 return common_path('notice/'.$args['notice']);
536          case 'xrds':           
537          case 'foaf':
538                 return common_path($args['nickname'].'/'.$action);
539          case 'subscriptions':
540          case 'subscribed':
541          case 'all':
542                 if ($args && $args['page']) {
543                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
544                 } else {
545                         return common_path($args['nickname'].'/'.$action);
546                 }
547          case 'allrss':
548                 return common_path($args['nickname'].'/all/rss');
549          case 'userrss':
550                 return common_path($args['nickname'].'/rss');
551          case 'showstream':
552                 if ($args && $args['page']) {
553                         return common_path($args['nickname'].'?page=' . $args['page']);
554                 } else {
555                         return common_path($args['nickname']);
556                 }
557          default:
558                 return common_simple_url($action, $args);
559         }
560 }
561
562 function common_simple_url($action, $args=NULL) {
563         global $config;
564         /* XXX: pretty URLs */
565         $extra = '';
566         if ($args) {
567                 foreach ($args as $key => $value) {
568                         $extra .= "&${key}=${value}";
569                 }
570         }
571         return common_path("index.php?action=${action}${extra}");
572 }
573
574 function common_path($relative) {
575         global $config;
576         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
577         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
578 }
579
580 function common_date_string($dt) {
581         // XXX: do some sexy date formatting
582         // return date(DATE_RFC822, $dt);
583         return $dt;
584 }
585
586 function common_date_w3dtf($dt) {
587         $t = strtotime($dt);
588         return date(DATE_W3C, $t);
589 }
590
591 function common_redirect($url, $code=307) {
592         static $status = array(301 => "Moved Permanently",
593                                                    302 => "Found",
594                                                    303 => "See Other",
595                                                    307 => "Temporary Redirect");
596         header("Status: ${code} $status[$code]");
597         header("Location: $url");
598         common_element('a', array('href' => $url), $url);
599 }
600
601 function common_broadcast_notice($notice, $remote=false) {
602         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
603         if (!$remote) {
604                 # Make sure we have the OMB stuff
605                 require_once(INSTALLDIR.'/lib/omb.php');
606                 omb_broadcast_remote_subscribers($notice);
607         }
608         // XXX: broadcast notices to Jabber
609         // XXX: broadcast notices to SMS
610         // XXX: broadcast notices to other IM
611         return true;
612 }
613
614 function common_broadcast_profile($profile) {
615         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
616         require_once(INSTALLDIR.'/lib/omb.php');
617         omb_broadcast_profile($profile);
618         // XXX: Other broadcasts...?
619         return true;
620 }
621
622 function common_profile_url($nickname) {
623         return common_local_url('showstream', array('nickname' => $nickname));
624 }
625
626 # Don't call if nobody's logged in
627
628 function common_notice_form() {
629         $user = common_current_user();
630         assert(!is_null($user));
631         common_element_start('form', array('id' => 'status_form',
632                                                                            'method' => 'POST',
633                                                                            'action' => common_local_url('newnotice')));
634         common_element_start('p');
635         common_element('label', array('for' => 'status_update',
636                                                                   'id' => 'status_label'),
637                                    _t('What\'s up, ').$user->nickname.'?');
638         common_element('textarea', array('id' => 'status_textarea',
639                                                                          'name' => 'status_textarea'));
640         common_element('input', array('id' => 'status_submit',
641                                                                   'name' => 'status_submit',
642                                                                   'type' => 'submit',
643                                                                   'value' => _t('Send')));
644         common_element_end('p');
645         common_element_end('form');
646 }
647
648 function common_mint_tag($extra) {
649         global $config;
650         return
651           'tag:'.$config['tag']['authority'].','.
652           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
653 }
654
655 # Should make up a reasonable root URL
656
657 function common_root_url() {
658         return common_path('');
659 }
660
661 # returns $bytes bytes of random data as a hexadecimal string
662 # "good" here is a goal and not a guarantee
663
664 function common_good_rand($bytes) {
665         # XXX: use random.org...?
666         if (file_exists('/dev/urandom')) {
667                 return common_urandom($bytes);
668         } else { # FIXME: this is probably not good enough
669                 return common_mtrand($bytes);
670         }
671 }
672
673 function common_urandom($bytes) {
674         $h = fopen('/dev/urandom', 'rb');
675         # should not block
676         $src = fread($h, $bytes);
677         fclose($h);
678         $enc = '';
679         for ($i = 0; $i < $bytes; $i++) {
680                 $enc .= sprintf("%02x", (ord($src[$i])));
681         }
682         return $enc;
683 }
684
685 function common_mtrand($bytes) {
686         $enc = '';
687         for ($i = 0; $i < $bytes; $i++) {
688                 $enc .= sprintf("%02x", mt_rand(0, 255));
689         }
690         return $enc;
691 }
692
693 function common_set_returnto($url) {
694         common_ensure_session();
695         $_SESSION['returnto'] = $url;
696 }
697
698 function common_get_returnto() {
699         common_ensure_session();
700         return $_SESSION['returnto'];
701 }
702
703 function common_timestamp() {
704         return date('YmdHis');
705 }
706
707 // XXX: set up gettext
708
709 function _t($str) {
710         return $str;
711 }
712
713 function common_ensure_syslog() {
714         static $initialized = false;
715         if (!$initialized) {
716                 global $config;
717                 define_syslog_variables();
718                 openlog($config['syslog']['appname'], 0, LOG_USER);
719                 $initialized = true;
720         }
721 }
722
723 function common_log($priority, $msg, $filename=NULL) {
724         common_ensure_syslog();
725         syslog($priority, $msg);
726 }
727
728 function common_debug($msg, $filename=NULL) {
729         if ($filename) {
730                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
731         } else {
732                 common_log(LOG_DEBUG, $msg);
733         }
734 }
735
736 function common_valid_http_url($url) {
737         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
738 }
739
740 function common_valid_tag($tag) {
741         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
742                 return (Validate::email($matches[1]) ||
743                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
744         }
745         return false;
746 }
747
748 # Does a little before-after block for next/prev page
749
750 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {             
751         
752         if ($have_before || $have_after) {
753                 common_element_start('div', array('id' => 'pagination'));
754                 common_element_start('ul', array('id' => 'nav_pagination'));
755         }
756         
757         if ($have_before) {
758                 $pargs = array('page' => $page-1);
759                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
760                                                                                  
761                 common_element_start('li', 'before');
762                 common_element('a', array('href' => common_local_url($action, $newargs)),
763                                            _t('« After'));
764                 common_element_end('li');
765         }
766
767         if ($have_after) {
768                 $pargs = array('page' => $page+1);
769                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
770                 common_element_start('li', 'after');
771                 common_element('a', array('href' => common_local_url($action, $newargs)),
772                                                    _t('Before »'));
773                 common_element_end('li');
774         }
775         
776         if ($have_before || $have_after) {
777                 common_element_end('ul');
778                 common_element_end('div');
779         }
780 }
781
782 /* Following functions are copied from MediaWiki GlobalFunctions.php
783  * and written by Evan Prodromou. */
784
785 function common_accept_to_prefs($accept, $def = '*/*') {
786         # No arg means accept anything (per HTTP spec)
787         if(!$accept) {
788                 return array($def => 1);
789         }
790
791         $prefs = array();
792
793         $parts = explode(',', $accept);
794
795         foreach($parts as $part) {
796                 # FIXME: doesn't deal with params like 'text/html; level=1'
797                 @list($value, $qpart) = explode(';', $part);
798                 $match = array();
799                 if(!isset($qpart)) {
800                         $prefs[$value] = 1;
801                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
802                         $prefs[$value] = $match[1];
803                 }
804         }
805
806         return $prefs;
807 }
808
809 function common_mime_type_match($type, $avail) {
810         if(array_key_exists($type, $avail)) {
811                 return $type;
812         } else {
813                 $parts = explode('/', $type);
814                 if(array_key_exists($parts[0] . '/*', $avail)) {
815                         return $parts[0] . '/*';
816                 } elseif(array_key_exists('*/*', $avail)) {
817                         return '*/*';
818                 } else {
819                         return NULL;
820                 }
821         }
822 }
823
824 function common_negotiate_type($cprefs, $sprefs) {
825         $combine = array();
826
827         foreach(array_keys($sprefs) as $type) {
828                 $parts = explode('/', $type);
829                 if($parts[1] != '*') {
830                         $ckey = common_mime_type_match($type, $cprefs);
831                         if($ckey) {
832                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
833                         }
834                 }
835         }
836
837         foreach(array_keys($cprefs) as $type) {
838                 $parts = explode('/', $type);
839                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
840                         $skey = common_mime_type_match($type, $sprefs);
841                         if($skey) {
842                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
843                         }
844                 }
845         }
846
847         $bestq = 0;
848         $besttype = NULL;
849
850         foreach(array_keys($combine) as $type) {
851                 if($combine[$type] > $bestq) {
852                         $besttype = $type;
853                         $bestq = $combine[$type];
854                 }
855         }
856
857         return $besttype;
858 }
859
860 function common_config($main, $sub) {
861         global $config;
862         return $config[$main][$sub];
863 }