]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
add OpenID settings to settings menu
[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         
170         common_element('script', array('type' => 'text/javascript',
171                                                                    'src' => common_path('js/jquery.min.js')),
172                                    ' ');
173                                                  
174         if ($callable) {
175                 if ($data) {
176                         call_user_func($callable, $data);
177                 } else {
178                         call_user_func($callable);
179                 }
180         }
181         common_element_end('head');
182         common_element_start('body');
183         common_element_start('div', array('id' => 'wrap'));
184         common_element_start('div', array('id' => 'header'));
185         common_nav_menu();
186         if ($config['site']['logo'] || file_exists(theme_file('logo.png'))) {
187                 common_element_start('a', array('href' => common_local_url('public')));
188                 common_element('img', array('src' => ($config['site']['logo']) ?
189                                                                         ($config['site']['logo']) : theme_path('logo.png'),
190                                                                         'alt' => $config['site']['name'],
191                                                                         'id' => 'logo'));
192                 common_element_end('a');
193         }
194         common_element('h1', 'pagetitle', $pagetitle);
195         common_element('h2', 'sitename', $config['site']['name']);
196         
197         if ($headercall) {
198                 if ($data) {
199                         call_user_func($headercall, $data);
200                 } else {
201                         call_user_func($headercall);
202                 }
203         }
204         common_element_end('div');
205         common_element_start('div', array('id' => 'content'));
206 }
207
208 function common_show_footer() {
209         global $xw, $config;
210         common_element_end('div'); # content div
211         common_foot_menu();
212         common_element_start('div', array('id' => 'footer'));
213         common_element_start('p', 'laconica');
214         common_text(_t('This site is running the '));
215         common_element('a', array('class' => 'software',
216                                                           href => 'http://laconi.ca/'),
217                                    'Laconica');
218         common_text(_t('microblogging tool, version ' . LACONICA_VERSION . ', available under the '));
219         common_element('a', array(href => 'http://www.fsf.org/licensing/licenses/agpl-3.0.html'),
220                                    'GNU Affero General Public License');
221         common_text(_t('.'));
222         common_element_end('p');
223         common_element('img', array('id' => 'cc',
224                                                                 'src' => $config['license']['image'],
225                                                                 'alt' => $config['license']['title']));
226         common_element_start('p');
227         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
228         common_element('a', array('class' => 'license',
229                                                           'rel' => 'license',
230                                                           href => $config['license']['url']),
231                                    $config['license']['title']);
232         common_text(_t('. Contributors should be attributed by full name or nickname.'));
233         common_element_end('p');
234         common_element_end('div');
235         common_element_end('div');
236         common_element_end('body');
237         common_element_end('html');
238         common_end_xml();
239 }
240
241 function common_text($txt) {
242         global $xw;
243         $xw->text($txt);
244 }
245
246 function common_raw($xml) {
247         global $xw;
248         $xw->writeRaw($xml);
249 }
250
251 function common_nav_menu() {
252         $user = common_current_user();
253         common_element_start('ul', array('id' => 'nav'));
254         if ($user) {
255                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
256                                                  _t('Home'));
257         }
258         common_menu_item(common_local_url('public'), _t('Public'));
259         common_menu_item(common_local_url('doc', array('title' => 'help')),
260                                          _t('Help'));
261         if ($user) {
262                 common_menu_item(common_local_url('profilesettings'),
263                                                  _t('Settings'));
264                 common_menu_item(common_local_url('logout'),
265                                                  _t('Logout'));
266         } else {
267                 common_menu_item(common_local_url('login'), _t('Login'));
268                 common_menu_item(common_local_url('register'), _t('Register'));
269         }
270         common_element_end('ul');
271 }
272
273 function common_foot_menu() {
274         common_element_start('ul', array('id' => 'nav_sub'));
275         common_menu_item(common_local_url('doc', array('title' => 'about')),
276                                          _t('About'));
277         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
278                                          _t('Privacy'));
279         common_menu_item(common_local_url('doc', array('title' => 'source')),
280                                          _t('Source'));
281         common_element_end('ul');
282 }
283
284 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
285         $lattrs = array();
286         if ($is_selected) {
287                 $lattrs['class'] = 'current';
288         }
289         common_element_start('li', $lattrs);
290         $attrs['href'] = $url;
291         if ($title) {
292                 $attrs['title'] = $title;
293         }
294         common_element('a', $attrs, $text);
295         common_element_end('li');
296 }
297
298 function common_input($id, $label, $value=NULL,$instructions=NULL) {
299         common_element_start('p');
300         common_element('label', array('for' => $id), $label);
301         $attrs = array('name' => $id,
302                                    'type' => 'text',
303                                    'id' => $id);
304         if ($value) {
305                 $attrs['value'] = htmlspecialchars($value);
306         }
307         common_element('input', $attrs);
308         if ($instructions) {
309                 common_element('span', 'input_instructions', $instructions);
310         }
311         common_element_end('p');
312 }
313
314 function common_hidden($id, $value) {
315         common_element('input', array('name' => $id,
316                                                                   'type' => 'hidden',
317                                                                   'id' => $id,
318                                                                   'value' => $value));
319 }
320
321 function common_password($id, $label, $instructions=NULL) {
322         common_element_start('p');
323         common_element('label', array('for' => $id), $label);
324         $attrs = array('name' => $id,
325                                    'type' => 'password',
326                                    'id' => $id);
327         common_element('input', $attrs);
328         if ($instructions) {
329                 common_element('span', 'input_instructions', $instructions);
330         }
331         common_element_end('p');
332 }
333
334 function common_submit($id, $label) {
335         global $xw;
336         common_element_start('p');
337         common_element('input', array('type' => 'submit',
338                                                                   'id' => $id,
339                                                                   'name' => $id,
340                                                                   'value' => $label));
341         common_element_end('p');
342 }
343
344 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
345         common_element_start('p');
346         common_element('label', array('for' => $id), $label);
347         common_element('textarea', array('rows' => 3,
348                                                                          'cols' => 40,
349                                                                          'name' => $id,
350                                                                          'id' => $id),
351                                    ($content) ? $content : ' ');
352         if ($instructions) {
353                 common_element('span', 'input_instructions', $instructions);
354         }
355         common_element_end('p');
356 }
357
358 # salted, hashed passwords are stored in the DB
359
360 function common_munge_password($id, $password) {
361         return md5($id . $password);
362 }
363
364 # check if a username exists and has matching password
365 function common_check_user($nickname, $password) {
366         $user = User::staticGet('nickname', $nickname);
367         if (is_null($user)) {
368                 return false;
369         } else {
370                 return (0 == strcmp(common_munge_password($password, $user->id),
371                                                         $user->password));
372         }
373 }
374
375 # is the current user logged in?
376 function common_logged_in() {
377         return (!is_null(common_current_user()));
378 }
379
380 function common_have_session() {
381         return (0 != strcmp(session_id(), ''));
382 }
383
384 function common_ensure_session() {
385         if (!common_have_session()) {
386                 @session_start();
387         }
388 }
389
390 function common_set_user($nickname) {
391         if (is_null($nickname) && common_have_session()) {
392                 unset($_SESSION['userid']);
393                 return true;
394         } else {
395                 $user = User::staticGet('nickname', $nickname);
396                 if ($user) {
397                         common_ensure_session();
398                         $_SESSION['userid'] = $user->id;
399                         return true;
400                 } else {
401                         return false;
402                 }
403         }
404         return false;
405 }
406
407 # who is the current user?
408 function common_current_user() {
409         static $user = NULL; # FIXME: global memcached
410         if (is_null($user)) {
411                 common_ensure_session();
412                 $id = $_SESSION['userid'];
413                 if ($id) {
414                         $user = User::staticGet($id);
415                 }
416         }
417         return $user;
418 }
419
420 # get canonical version of nickname for comparison
421 function common_canonical_nickname($nickname) {
422         # XXX: UTF-8 canonicalization (like combining chars)
423         return strtolower($nickname);
424 }
425
426 # get canonical version of email for comparison
427 function common_canonical_email($email) {
428         # XXX: canonicalize UTF-8
429         # XXX: lcase the domain part
430         return $email;
431 }
432
433 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$_+!*();/?:~-]))');
434
435 function common_render_content($text, $notice) {
436         $r = htmlspecialchars($text);
437         $id = $notice->profile_id;
438         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
439         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
440         # XXX: # tags
441         # XXX: machine tags
442         return $r;
443 }
444
445 function common_at_link($sender_id, $nickname) {
446         # Try to find profiles this profile is subscribed to that have this nickname
447         $recipient = new Profile();
448         # XXX: chokety and bad
449         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
450         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
451         if ($recipient->find(TRUE)) {
452                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
453         }
454         # Try to find profiles that listen to this profile and that have this nickname
455         $recipient = new Profile();
456         # XXX: chokety and bad
457         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
458         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
459         if ($recipient->find(TRUE)) {
460                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
461         }
462         # If this is a local user, try to find a local user with that nickname.
463         $sender = User::staticGet($sender_id);
464         if ($sender) {
465                 $recipient_user = User::staticGet('nickname', $nickname);
466                 if ($recipient_user) {
467                         $recipient = $recipient->getProfile();
468                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
469                 }
470         }
471         # Otherwise, no links. @messages from local users to remote users,
472         # or from remote users to other remote users, are just
473         # outside our ability to make intelligent guesses about
474         return $nickname;
475 }
476
477 // where should the avatar go for this user?
478
479 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
480         global $config;
481
482         if ($size) {
483                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
484         } else {
485                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
486         }
487 }
488
489 function common_avatar_path($filename) {
490         global $config;
491         return INSTALLDIR . '/avatar/' . $filename;
492 }
493
494 function common_avatar_url($filename) {
495         return common_path('avatar/'.$filename);
496 }
497
498 function common_default_avatar($size) {
499         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
500                                                           AVATAR_STREAM_SIZE => 'stream',
501                                                           AVATAR_MINI_SIZE => 'mini');
502         return theme_path('default-avatar-'.$sizenames[$size].'.png');
503 }
504
505 function common_local_url($action, $args=NULL) {
506         global $config;
507         if ($config['site']['fancy']) {
508                 return common_fancy_url($action, $args);
509         } else {
510                 return common_simple_url($action, $args);
511         }
512 }
513
514 function common_fancy_url($action, $args=NULL) {
515         switch (strtolower($action)) {
516          case 'public':
517                 if ($args && $args['page']) {
518                         return common_path('?page=' . $args['page']);
519                 } else {
520                         return common_path('');
521                 }
522          case 'publicrss':
523                 return common_path('rss');
524          case 'doc':
525                 return common_path('doc/'.$args['title']);
526          case 'login':
527          case 'logout':
528          case 'register':
529          case 'subscribe':
530          case 'unsubscribe':
531                 return common_path('main/'.$action);
532          case 'avatar':
533          case 'password':
534                 return common_path('settings/'.$action);
535          case 'profilesettings':
536                 return common_path('settings/profile');
537          case 'newnotice':
538                 return common_path('notice/new');
539          case 'shownotice':
540                 return common_path('notice/'.$args['notice']);
541          case 'xrds':           
542          case 'foaf':
543                 return common_path($args['nickname'].'/'.$action);
544          case 'subscriptions':
545          case 'subscribed':
546          case 'all':
547                 if ($args && $args['page']) {
548                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
549                 } else {
550                         return common_path($args['nickname'].'/'.$action);
551                 }
552          case 'allrss':
553                 return common_path($args['nickname'].'/all/rss');
554          case 'userrss':
555                 return common_path($args['nickname'].'/rss');
556          case 'showstream':
557                 if ($args && $args['page']) {
558                         return common_path($args['nickname'].'?page=' . $args['page']);
559                 } else {
560                         return common_path($args['nickname']);
561                 }
562          default:
563                 return common_simple_url($action, $args);
564         }
565 }
566
567 function common_simple_url($action, $args=NULL) {
568         global $config;
569         /* XXX: pretty URLs */
570         $extra = '';
571         if ($args) {
572                 foreach ($args as $key => $value) {
573                         $extra .= "&${key}=${value}";
574                 }
575         }
576         return common_path("index.php?action=${action}${extra}");
577 }
578
579 function common_path($relative) {
580         global $config;
581         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
582         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
583 }
584
585 function common_date_string($dt) {
586         // XXX: do some sexy date formatting
587         // return date(DATE_RFC822, $dt);
588         return $dt;
589 }
590
591 function common_date_w3dtf($dt) {
592         $t = strtotime($dt);
593         return date(DATE_W3C, $t);
594 }
595
596 function common_redirect($url, $code=307) {
597         static $status = array(301 => "Moved Permanently",
598                                                    302 => "Found",
599                                                    303 => "See Other",
600                                                    307 => "Temporary Redirect");
601         header("Status: ${code} $status[$code]");
602         header("Location: $url");
603         common_element('a', array('href' => $url), $url);
604 }
605
606 function common_broadcast_notice($notice, $remote=false) {
607         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
608         if (!$remote) {
609                 # Make sure we have the OMB stuff
610                 require_once(INSTALLDIR.'/lib/omb.php');
611                 omb_broadcast_remote_subscribers($notice);
612         }
613         // XXX: broadcast notices to Jabber
614         // XXX: broadcast notices to SMS
615         // XXX: broadcast notices to other IM
616         return true;
617 }
618
619 function common_broadcast_profile($profile) {
620         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
621         require_once(INSTALLDIR.'/lib/omb.php');
622         omb_broadcast_profile($profile);
623         // XXX: Other broadcasts...?
624         return true;
625 }
626
627 function common_profile_url($nickname) {
628         return common_local_url('showstream', array('nickname' => $nickname));
629 }
630
631 # Don't call if nobody's logged in
632
633 function common_notice_form() {
634         $user = common_current_user();
635         assert(!is_null($user));
636         common_element_start('form', array('id' => 'status_form',
637                                                                            'method' => 'POST',
638                                                                            'action' => common_local_url('newnotice')));
639         common_element_start('p');
640         common_element('label', array('for' => 'status_update',
641                                                                   'id' => 'status_label'),
642                                    _t('What\'s up, ').$user->nickname.'?');
643         common_element('textarea', array('id' => 'status_textarea',
644                                                                          'name' => 'status_textarea'));
645         common_element('input', array('id' => 'status_submit',
646                                                                   'name' => 'status_submit',
647                                                                   'type' => 'submit',
648                                                                   'value' => _t('Send')));
649         common_element_end('p');
650         common_element_end('form');
651 }
652
653 function common_mint_tag($extra) {
654         global $config;
655         return
656           'tag:'.$config['tag']['authority'].','.
657           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
658 }
659
660 # Should make up a reasonable root URL
661
662 function common_root_url() {
663         return common_path('');
664 }
665
666 # returns $bytes bytes of random data as a hexadecimal string
667 # "good" here is a goal and not a guarantee
668
669 function common_good_rand($bytes) {
670         # XXX: use random.org...?
671         if (file_exists('/dev/urandom')) {
672                 return common_urandom($bytes);
673         } else { # FIXME: this is probably not good enough
674                 return common_mtrand($bytes);
675         }
676 }
677
678 function common_urandom($bytes) {
679         $h = fopen('/dev/urandom', 'rb');
680         # should not block
681         $src = fread($h, $bytes);
682         fclose($h);
683         $enc = '';
684         for ($i = 0; $i < $bytes; $i++) {
685                 $enc .= sprintf("%02x", (ord($src[$i])));
686         }
687         return $enc;
688 }
689
690 function common_mtrand($bytes) {
691         $enc = '';
692         for ($i = 0; $i < $bytes; $i++) {
693                 $enc .= sprintf("%02x", mt_rand(0, 255));
694         }
695         return $enc;
696 }
697
698 function common_set_returnto($url) {
699         common_ensure_session();
700         $_SESSION['returnto'] = $url;
701 }
702
703 function common_get_returnto() {
704         common_ensure_session();
705         return $_SESSION['returnto'];
706 }
707
708 function common_timestamp() {
709         return date('YmdHis');
710 }
711
712 // XXX: set up gettext
713
714 function _t($str) {
715         return $str;
716 }
717
718 function common_ensure_syslog() {
719         static $initialized = false;
720         if (!$initialized) {
721                 global $config;
722                 define_syslog_variables();
723                 openlog($config['syslog']['appname'], 0, LOG_USER);
724                 $initialized = true;
725         }
726 }
727
728 function common_log($priority, $msg, $filename=NULL) {
729         common_ensure_syslog();
730         syslog($priority, $msg);
731 }
732
733 function common_debug($msg, $filename=NULL) {
734         if ($filename) {
735                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
736         } else {
737                 common_log(LOG_DEBUG, $msg);
738         }
739 }
740
741 function common_valid_http_url($url) {
742         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
743 }
744
745 function common_valid_tag($tag) {
746         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
747                 return (Validate::email($matches[1]) ||
748                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
749         }
750         return false;
751 }
752
753 # Does a little before-after block for next/prev page
754
755 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {             
756         
757         if ($have_before || $have_after) {
758                 common_element_start('div', array('id' => 'pagination'));
759                 common_element_start('ul', array('id' => 'nav_pagination'));
760         }
761         
762         if ($have_before) {
763                 $pargs = array('page' => $page-1);
764                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
765                                                                                  
766                 common_element_start('li', 'before');
767                 common_element('a', array('href' => common_local_url($action, $newargs)),
768                                            _t('« After'));
769                 common_element_end('li');
770         }
771
772         if ($have_after) {
773                 $pargs = array('page' => $page+1);
774                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
775                 common_element_start('li', 'after');
776                 common_element('a', array('href' => common_local_url($action, $newargs)),
777                                                    _t('Before »'));
778                 common_element_end('li');
779         }
780         
781         if ($have_before || $have_after) {
782                 common_element_end('ul');
783                 common_element_end('div');
784         }
785 }
786
787 /* Following functions are copied from MediaWiki GlobalFunctions.php
788  * and written by Evan Prodromou. */
789
790 function common_accept_to_prefs($accept, $def = '*/*') {
791         # No arg means accept anything (per HTTP spec)
792         if(!$accept) {
793                 return array($def => 1);
794         }
795
796         $prefs = array();
797
798         $parts = explode(',', $accept);
799
800         foreach($parts as $part) {
801                 # FIXME: doesn't deal with params like 'text/html; level=1'
802                 @list($value, $qpart) = explode(';', $part);
803                 $match = array();
804                 if(!isset($qpart)) {
805                         $prefs[$value] = 1;
806                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
807                         $prefs[$value] = $match[1];
808                 }
809         }
810
811         return $prefs;
812 }
813
814 function common_mime_type_match($type, $avail) {
815         if(array_key_exists($type, $avail)) {
816                 return $type;
817         } else {
818                 $parts = explode('/', $type);
819                 if(array_key_exists($parts[0] . '/*', $avail)) {
820                         return $parts[0] . '/*';
821                 } elseif(array_key_exists('*/*', $avail)) {
822                         return '*/*';
823                 } else {
824                         return NULL;
825                 }
826         }
827 }
828
829 function common_negotiate_type($cprefs, $sprefs) {
830         $combine = array();
831
832         foreach(array_keys($sprefs) as $type) {
833                 $parts = explode('/', $type);
834                 if($parts[1] != '*') {
835                         $ckey = common_mime_type_match($type, $cprefs);
836                         if($ckey) {
837                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
838                         }
839                 }
840         }
841
842         foreach(array_keys($cprefs) as $type) {
843                 $parts = explode('/', $type);
844                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
845                         $skey = common_mime_type_match($type, $sprefs);
846                         if($skey) {
847                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
848                         }
849                 }
850         }
851
852         $bestq = 0;
853         $besttype = NULL;
854
855         foreach(array_keys($combine) as $type) {
856                 if($combine[$type] > $bestq) {
857                         $besttype = $type;
858                         $bestq = $combine[$type];
859                 }
860         }
861
862         return $besttype;
863 }
864
865 function common_config($main, $sub) {
866         global $config;
867         return $config[$main][$sub];
868 }