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