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