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