]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
add more contact information
[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_user_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_start('p', array('id' => 'branding'));
197                 common_element('a', array('href' => common_local_url('public')),
198                                            $config['site']['name']);
199                 common_element_end('p');
200         }
201
202         common_element('h1', 'pagetitle', $pagetitle);
203
204         if ($headercall) {
205                 if ($data) {
206                         call_user_func($headercall, $data);
207                 } else {
208                         call_user_func($headercall);
209                 }
210         }
211         common_element_end('div');
212         common_element_start('div', array('id' => 'content'));
213 }
214
215 function common_show_footer() {
216         global $xw, $config;
217         common_element_end('div'); # content div
218         common_foot_menu();
219         common_element_start('div', array('id' => 'footer'));
220         common_element_start('p', 'laconica');
221         if (common_config('site', 'broughtby')) {
222                 $instr = _t('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
223         } else {
224                 $instr = _t('**%%site.name%%** is a microblogging service. ');
225         }
226         $instr .= _t('It runs the [Laconica](http://laconi.ca/) ' .
227                          'microblogging software, version ' . LACONICA_VERSION . ', ' .
228                          'available under the ' .
229                          '[GNU Affero General Public License]' .
230                          '(http://www.fsf.org/licensing/licenses/agpl-3.0.html).');
231     $output = common_markup_to_html($instr);
232     common_raw($output);
233         common_element_end('p');
234         common_element('img', array('id' => 'cc',
235                                                                 'src' => $config['license']['image'],
236                                                                 'alt' => $config['license']['title']));
237         common_element_start('p');
238         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
239         common_element('a', array('class' => 'license',
240                                                           'rel' => 'license',
241                                                           href => $config['license']['url']),
242                                    $config['license']['title']);
243         common_text(_t('. Contributors should be attributed by full name or nickname.'));
244         common_element_end('p');
245         common_element_end('div');
246         common_element_end('div');
247         common_element_end('body');
248         common_element_end('html');
249         common_end_xml();
250 }
251
252 function common_text($txt) {
253         global $xw;
254         $xw->text($txt);
255 }
256
257 function common_raw($xml) {
258         global $xw;
259         $xw->writeRaw($xml);
260 }
261
262 function common_nav_menu() {
263         $user = common_current_user();
264         common_element_start('ul', array('id' => 'nav'));
265         if ($user) {
266                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
267                                                  _t('Home'));
268         }
269         common_menu_item(common_local_url('public'), _t('Public'));
270         common_menu_item(common_local_url('doc', array('title' => 'help')),
271                                          _t('Help'));
272         if ($user) {
273                 common_menu_item(common_local_url('profilesettings'),
274                                                  _t('Settings'));
275                 common_menu_item(common_local_url('logout'),
276                                                  _t('Logout'));
277         } else {
278                 common_menu_item(common_local_url('login'), _t('Login'));
279                 common_menu_item(common_local_url('register'), _t('Register'));
280                 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
281         }
282         common_element_end('ul');
283 }
284
285 function common_foot_menu() {
286         common_element_start('ul', array('id' => 'nav_sub'));
287         common_menu_item(common_local_url('doc', array('title' => 'about')),
288                                          _t('About'));
289         common_menu_item(common_local_url('doc', array('title' => 'faq')),
290                                          _t('FAQ'));
291         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
292                                          _t('Privacy'));
293         common_menu_item(common_local_url('doc', array('title' => 'source')),
294                                          _t('Source'));
295         common_menu_item(common_local_url('doc', array('title' => 'contact')),
296                                          _t('Contact'));
297         common_element_end('ul');
298 }
299
300 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
301         $lattrs = array();
302         if ($is_selected) {
303                 $lattrs['class'] = 'current';
304         }
305         common_element_start('li', $lattrs);
306         $attrs['href'] = $url;
307         if ($title) {
308                 $attrs['title'] = $title;
309         }
310         common_element('a', $attrs, $text);
311         common_element_end('li');
312 }
313
314 function common_input($id, $label, $value=NULL,$instructions=NULL) {
315         common_element_start('p');
316         common_element('label', array('for' => $id), $label);
317         $attrs = array('name' => $id,
318                                    'type' => 'text',
319                                    'class' => 'input_text',
320                                    'id' => $id);
321         if ($value) {
322                 $attrs['value'] = htmlspecialchars($value);
323         }
324         common_element('input', $attrs);
325         if ($instructions) {
326                 common_element('span', 'input_instructions', $instructions);
327         }
328         common_element_end('p');
329 }
330
331 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
332 {
333         common_element_start('p');
334         $attrs = array('name' => $id,
335                                    'type' => 'checkbox',
336                                    'class' => 'checkbox',
337                                    'id' => $id);
338         if ($value) {
339                 $attrs['value'] = htmlspecialchars($value);
340         }
341         if ($checked) {
342                 $attrs['checked'] = 'checked';
343         }
344         common_element('input', $attrs);
345         # XXX: use a <label>
346         common_text(' ');
347         common_element('span', 'checkbox_label', $label);
348         common_text(' ');
349         if ($instructions) {
350                 common_element('span', 'input_instructions', $instructions);
351         }
352         common_element_end('p');
353 }
354
355 function common_hidden($id, $value) {
356         common_element('input', array('name' => $id,
357                                                                   'type' => 'hidden',
358                                                                   'id' => $id,
359                                                                   'value' => $value));
360 }
361
362 function common_password($id, $label, $instructions=NULL) {
363         common_element_start('p');
364         common_element('label', array('for' => $id), $label);
365         $attrs = array('name' => $id,
366                                    'type' => 'password',
367                                    'class' => 'password',
368                                    'id' => $id);
369         common_element('input', $attrs);
370         if ($instructions) {
371                 common_element('span', 'input_instructions', $instructions);
372         }
373         common_element_end('p');
374 }
375
376 function common_submit($id, $label) {
377         global $xw;
378         common_element_start('p');
379         common_element('input', array('type' => 'submit',
380                                                                   'id' => $id,
381                                                                   'name' => $id,
382                                                                   'class' => 'submit',
383                                                                   'value' => $label));
384         common_element_end('p');
385 }
386
387 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
388         common_element_start('p');
389         common_element('label', array('for' => $id), $label);
390         common_element('textarea', array('rows' => 3,
391                                                                          'cols' => 40,
392                                                                          'name' => $id,
393                                                                          'id' => $id),
394                                    ($content) ? $content : ' ');
395         if ($instructions) {
396                 common_element('span', 'input_instructions', $instructions);
397         }
398         common_element_end('p');
399 }
400
401 # salted, hashed passwords are stored in the DB
402
403 function common_munge_password($password, $id) {
404         return md5($password . $id);
405 }
406
407 # check if a username exists and has matching password
408 function common_check_user($nickname, $password) {
409         $user = User::staticGet('nickname', $nickname);
410         if (is_null($user)) {
411                 return false;
412         } else {
413                 return (0 == strcmp(common_munge_password($password, $user->id),
414                                                         $user->password));
415         }
416 }
417
418 # is the current user logged in?
419 function common_logged_in() {
420         return (!is_null(common_current_user()));
421 }
422
423 function common_have_session() {
424         return (0 != strcmp(session_id(), ''));
425 }
426
427 function common_ensure_session() {
428         if (!common_have_session()) {
429                 @session_start();
430         }
431 }
432
433 function common_set_user($nickname) {
434         if (is_null($nickname) && common_have_session()) {
435                 unset($_SESSION['userid']);
436                 return true;
437         } else {
438                 $user = User::staticGet('nickname', $nickname);
439                 if ($user) {
440                         common_ensure_session();
441                         $_SESSION['userid'] = $user->id;
442                         return true;
443                 } else {
444                         return false;
445                 }
446         }
447         return false;
448 }
449
450 function common_set_cookie($key, $value, $expiration=0) {
451         $path = common_config('site', 'path');
452         $server = common_config('site', 'server');
453
454         if ($path && ($path != '/')) {
455                 $cookiepath = '/' . $path . '/';
456         } else {
457                 $cookiepath = '/';
458         }
459         return setcookie($key,
460                          $value,
461                                  $expiration,
462                                          $cookiepath,
463                                      $server);
464 }
465
466 define('REMEMBERME', 'rememberme');
467 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
468
469 function common_rememberme() {
470         $user = common_current_user();
471         if (!$user) {
472                 return false;
473         }
474         $rm = new Remember_me();
475         $rm->code = common_good_rand(16);
476         $rm->user_id = $user->id;
477         $result = $rm->insert();
478         if (!$result) {
479                 common_log_db_error($rm, 'INSERT', __FILE__);
480                 return false;
481         }
482         common_set_cookie(REMEMBERME,
483                                           implode(':', array($rm->user_id, $rm->code)),
484                                           time() + REMEMBERME_EXPIRY);
485 }
486
487 function common_remembered_user() {
488         $user = NULL;
489         # Try to remember
490         $packed = $_COOKIE[REMEMBERME];
491         if ($packed) {
492                 list($id, $code) = explode(':', $packed);
493                 if ($id && $code) {
494                         $rm = Remember_me::staticGet($code);
495                         if ($rm && ($rm->user_id == $id)) {
496                                 $user = User::staticGet($rm->user_id);
497                                 if ($user) {
498                                         # successful!
499                                         $result = $rm->delete();
500                                         if (!$result) {
501                                                 common_log_db_error($rm, 'DELETE', __FILE__);
502                                                 $user = NULL;
503                                         } else {
504                                                 common_set_user($user->nickname);
505                                                 common_real_login(false);
506                                                 # We issue a new cookie, so they can log in
507                                                 # automatically again after this session
508                                                 common_rememberme();
509                                         }
510                                 }
511                         }
512                 }
513         }
514         return $user;
515 }
516
517 # must be called with a valid user!
518
519 function common_forgetme() {
520         common_set_cookie(REMEMBERME, '', 0);
521 }
522
523 # who is the current user?
524 function common_current_user() {
525         if ($_REQUEST[session_name()]) {
526                 common_ensure_session();
527                 $id = $_SESSION['userid'];
528                 if ($id) {
529                         # note: this should cache
530                         $user = User::staticGet($id);
531                         return $user;
532                 }
533         }
534         # that didn't work; try to remember
535         $user = common_remembered_user();
536         return $user;
537 }
538
539 # Logins that are 'remembered' aren't 'real' -- they're subject to
540 # cookie-stealing. So, we don't let them do certain things. New reg,
541 # OpenID, and password logins _are_ real.
542
543 function common_real_login($real=true) {
544         common_ensure_session();
545         $_SESSION['real_login'] = $real;
546 }
547
548 function common_is_real_login() {
549         return common_logged_in() && $_SESSION['real_login'];
550 }
551
552 # get canonical version of nickname for comparison
553 function common_canonical_nickname($nickname) {
554         # XXX: UTF-8 canonicalization (like combining chars)
555         return strtolower($nickname);
556 }
557
558 # get canonical version of email for comparison
559 function common_canonical_email($email) {
560         # XXX: canonicalize UTF-8
561         # XXX: lcase the domain part
562         return $email;
563 }
564
565 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$_+!*();/?:~-]))');
566
567 function common_render_content($text, $notice) {
568         $r = htmlspecialchars($text);
569         $id = $notice->profile_id;
570         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
571         $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
572         # XXX: # tags
573         # XXX: machine tags
574         return $r;
575 }
576
577 function common_at_link($sender_id, $nickname) {
578         # Try to find profiles this profile is subscribed to that have this nickname
579         $recipient = new Profile();
580         # XXX: chokety and bad
581         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
582         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
583         if ($recipient->find(TRUE)) {
584                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
585         }
586         # Try to find profiles that listen to this profile and that have this nickname
587         $recipient = new Profile();
588         # XXX: chokety and bad
589         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
590         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
591         if ($recipient->find(TRUE)) {
592                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
593         }
594         # If this is a local user, try to find a local user with that nickname.
595         $sender = User::staticGet($sender_id);
596         if ($sender) {
597                 $recipient_user = User::staticGet('nickname', $nickname);
598                 if ($recipient_user) {
599                         return '<a href="'.htmlspecialchars(common_profile_url($nickname)).'" class="atlink usertouser">'.$nickname.'</a>';
600                 }
601         }
602         # Otherwise, no links. @messages from local users to remote users,
603         # or from remote users to other remote users, are just
604         # outside our ability to make intelligent guesses about
605         return $nickname;
606 }
607
608 // where should the avatar go for this user?
609
610 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
611         global $config;
612
613         if ($size) {
614                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
615         } else {
616                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
617         }
618 }
619
620 function common_avatar_path($filename) {
621         global $config;
622         return INSTALLDIR . '/avatar/' . $filename;
623 }
624
625 function common_avatar_url($filename) {
626         return common_path('avatar/'.$filename);
627 }
628
629 function common_default_avatar($size) {
630         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
631                                                           AVATAR_STREAM_SIZE => 'stream',
632                                                           AVATAR_MINI_SIZE => 'mini');
633         return theme_path('default-avatar-'.$sizenames[$size].'.png');
634 }
635
636 function common_local_url($action, $args=NULL) {
637         global $config;
638         if ($config['site']['fancy']) {
639                 return common_fancy_url($action, $args);
640         } else {
641                 return common_simple_url($action, $args);
642         }
643 }
644
645 function common_fancy_url($action, $args=NULL) {
646         switch (strtolower($action)) {
647          case 'public':
648                 if ($args && $args['page']) {
649                         return common_path('?page=' . $args['page']);
650                 } else {
651                         return common_path('');
652                 }
653          case 'publicrss':
654                 return common_path('rss');
655          case 'publicxrds':
656                 return common_path('xrds');
657          case 'doc':
658                 return common_path('doc/'.$args['title']);
659          case 'login':
660          case 'logout':
661          case 'register':
662          case 'subscribe':
663          case 'unsubscribe':
664                 return common_path('main/'.$action);
665          case 'remotesubscribe':
666                 if ($args && $args['nickname']) {
667                         return common_path('main/remote?nickname=' . $args['nickname']);
668                 } else {
669                         return common_path('main/remote');
670                 }
671          case 'openidlogin':
672                 return common_path('main/openid');
673          case 'avatar':
674          case 'password':
675                 return common_path('settings/'.$action);
676          case 'profilesettings':
677                 return common_path('settings/profile');
678          case 'openidsettings':
679                 return common_path('settings/openid');
680          case 'newnotice':
681                 return common_path('notice/new');
682          case 'shownotice':
683                 return common_path('notice/'.$args['notice']);
684          case 'xrds':
685          case 'foaf':
686                 return common_path($args['nickname'].'/'.$action);
687          case 'subscriptions':
688          case 'subscribers':
689          case 'all':
690                 if ($args && $args['page']) {
691                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
692                 } else {
693                         return common_path($args['nickname'].'/'.$action);
694                 }
695          case 'allrss':
696                 return common_path($args['nickname'].'/all/rss');
697          case 'userrss':
698                 return common_path($args['nickname'].'/rss');
699          case 'showstream':
700                 if ($args && $args['page']) {
701                         return common_path($args['nickname'].'?page=' . $args['page']);
702                 } else {
703                         return common_path($args['nickname']);
704                 }
705          case 'confirmaddress':
706                 return common_path('main/confirmaddress/'.$args['code']);
707          case 'userbyid':
708                 return common_path('user/'.$args['id']);
709          case 'recoverpassword':
710             $path = 'main/recoverpassword';
711             if ($args['code']) {
712                 $path .= '/' . $args['code'];
713                 }
714             return common_path($path);
715          case 'imsettings':
716                 return common_path('settings/im');
717          default:
718                 return common_simple_url($action, $args);
719         }
720 }
721
722 function common_simple_url($action, $args=NULL) {
723         global $config;
724         /* XXX: pretty URLs */
725         $extra = '';
726         if ($args) {
727                 foreach ($args as $key => $value) {
728                         $extra .= "&${key}=${value}";
729                 }
730         }
731         return common_path("index.php?action=${action}${extra}");
732 }
733
734 function common_path($relative) {
735         global $config;
736         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
737         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
738 }
739
740 function common_date_string($dt) {
741         // XXX: do some sexy date formatting
742         // return date(DATE_RFC822, $dt);
743         $t = strtotime($dt);
744         $now = time();
745         $diff = $now - $t;
746
747         if ($now < $t) { # that shouldn't happen!
748                 return common_exact_date($dt);
749         } else if ($diff < 60) {
750                 return _t('a few seconds ago');
751         } else if ($diff < 92) {
752                 return _t('about a minute ago');
753         } else if ($diff < 3300) {
754                 return _t('about ') . round($diff/60) . _t(' minutes ago');
755         } else if ($diff < 5400) {
756                 return _t('about an hour ago');
757         } else if ($diff < 22 * 3600) {
758                 return _t('about ') . round($diff/3600) . _t(' hours ago');
759         } else if ($diff < 37 * 3600) {
760                 return _t('about a day ago');
761         } else if ($diff < 24 * 24 * 3600) {
762                 return _t('about ') . round($diff/(24*3600)) . _t(' days ago');
763         } else if ($diff < 46 * 24 * 3600) {
764                 return _t('about a month ago');
765         } else if ($diff < 330 * 24 * 3600) {
766                 return _t('about ') . round($diff/(30*24*3600)) . _t(' months ago');
767         } else if ($diff < 480 * 24 * 3600) {
768                 return _t('about a year ago');
769         } else {
770                 return common_exact_date($dt);
771         }
772 }
773
774 function common_exact_date($dt) {
775         $t = strtotime($dt);
776         return date(DATE_RFC850, $t);
777 }
778
779 function common_date_w3dtf($dt) {
780         $t = strtotime($dt);
781         return date(DATE_W3C, $t);
782 }
783
784 function common_redirect($url, $code=307) {
785         static $status = array(301 => "Moved Permanently",
786                                                    302 => "Found",
787                                                    303 => "See Other",
788                                                    307 => "Temporary Redirect");
789         header("Status: ${code} $status[$code]");
790         header("Location: $url");
791
792         common_start_xml('a',
793                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
794                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
795         common_element('a', array('href' => $url), $url);
796         common_end_xml();
797 }
798
799 function common_broadcast_notice($notice, $remote=false) {
800         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
801         if (!$remote) {
802                 # Make sure we have the OMB stuff
803                 require_once(INSTALLDIR.'/lib/omb.php');
804                 omb_broadcast_remote_subscribers($notice);
805         }
806         require_once(INSTALLDIR.'/lib/jabber.php');
807         jabber_broadcast_notice($notice);
808         // XXX: broadcast notices to SMS
809         // XXX: broadcast notices to other IM
810         return true;
811 }
812
813 function common_broadcast_profile($profile) {
814         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
815         require_once(INSTALLDIR.'/lib/omb.php');
816         omb_broadcast_profile($profile);
817         // XXX: Other broadcasts...?
818         return true;
819 }
820
821 function common_profile_url($nickname) {
822         return common_local_url('showstream', array('nickname' => $nickname));
823 }
824
825 # Don't call if nobody's logged in
826
827 function common_notice_form($action=NULL, $content=NULL) {
828         $user = common_current_user();
829         assert(!is_null($user));
830         common_element_start('form', array('id' => 'status_form',
831                                                                            'method' => 'POST',
832                                                                            'action' => common_local_url('newnotice')));
833         common_element_start('p');
834         common_element('label', array('for' => 'status_update',
835                                                                   'id' => 'status_label'),
836                                    _t('What\'s up, ').$user->nickname.'?');
837         common_element('textarea', array('id' => 'status_textarea',
838                                                                          'name' => 'status_textarea'),
839                                    ($content) ? $content : ' ');
840         if ($action) {
841                 common_hidden('returnto', $action);
842         }
843         common_element('input', array('id' => 'status_submit',
844                                                                   'name' => 'status_submit',
845                                                                   'type' => 'submit',
846                                                                   'value' => _t('Send')));
847         common_element_end('p');
848         common_element_end('form');
849 }
850
851 function common_mint_tag($extra) {
852         global $config;
853         return
854           'tag:'.$config['tag']['authority'].','.
855           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
856 }
857
858 # Should make up a reasonable root URL
859
860 function common_root_url() {
861         return common_path('');
862 }
863
864 # returns $bytes bytes of random data as a hexadecimal string
865 # "good" here is a goal and not a guarantee
866
867 function common_good_rand($bytes) {
868         # XXX: use random.org...?
869         if (file_exists('/dev/urandom')) {
870                 return common_urandom($bytes);
871         } else { # FIXME: this is probably not good enough
872                 return common_mtrand($bytes);
873         }
874 }
875
876 function common_urandom($bytes) {
877         $h = fopen('/dev/urandom', 'rb');
878         # should not block
879         $src = fread($h, $bytes);
880         fclose($h);
881         $enc = '';
882         for ($i = 0; $i < $bytes; $i++) {
883                 $enc .= sprintf("%02x", (ord($src[$i])));
884         }
885         return $enc;
886 }
887
888 function common_mtrand($bytes) {
889         $enc = '';
890         for ($i = 0; $i < $bytes; $i++) {
891                 $enc .= sprintf("%02x", mt_rand(0, 255));
892         }
893         return $enc;
894 }
895
896 function common_set_returnto($url) {
897         common_ensure_session();
898         $_SESSION['returnto'] = $url;
899 }
900
901 function common_get_returnto() {
902         common_ensure_session();
903         return $_SESSION['returnto'];
904 }
905
906 function common_timestamp() {
907         return date('YmdHis');
908 }
909
910 // XXX: set up gettext
911
912 function _t($str) {
913         return $str;
914 }
915
916 function common_ensure_syslog() {
917         static $initialized = false;
918         if (!$initialized) {
919                 global $config;
920                 define_syslog_variables();
921                 openlog($config['syslog']['appname'], 0, LOG_USER);
922                 $initialized = true;
923         }
924 }
925
926 function common_log($priority, $msg, $filename=NULL) {
927         common_ensure_syslog();
928         syslog($priority, $msg);
929 }
930
931 function common_debug($msg, $filename=NULL) {
932         if ($filename) {
933                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
934         } else {
935                 common_log(LOG_DEBUG, $msg);
936         }
937 }
938
939 function common_log_db_error(&$object, $verb, $filename=NULL) {
940         $objstr = common_log_objstring($object);
941         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
942         common_log(LOG_ERROR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
943 }
944
945 function common_log_objstring(&$object) {
946         if (is_null($object)) {
947                 return "NULL";
948         }
949         $arr = $object->toArray();
950         $fields = array();
951         foreach ($arr as $k => $v) {
952                 $fields[] = "$k='$v'";
953         }
954         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
955         return $objstring;
956 }
957
958 function common_valid_http_url($url) {
959         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
960 }
961
962 function common_valid_tag($tag) {
963         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
964                 return (Validate::email($matches[1]) ||
965                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
966         }
967         return false;
968 }
969
970 # Does a little before-after block for next/prev page
971
972 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
973
974         if ($have_before || $have_after) {
975                 common_element_start('div', array('id' => 'pagination'));
976                 common_element_start('ul', array('id' => 'nav_pagination'));
977         }
978
979         if ($have_before) {
980                 $pargs = array('page' => $page-1);
981                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
982
983                 common_element_start('li', 'before');
984                 common_element('a', array('href' => common_local_url($action, $newargs)),
985                                            _t('« After'));
986                 common_element_end('li');
987         }
988
989         if ($have_after) {
990                 $pargs = array('page' => $page+1);
991                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
992                 common_element_start('li', 'after');
993                 common_element('a', array('href' => common_local_url($action, $newargs)),
994                                                    _t('Before »'));
995                 common_element_end('li');
996         }
997
998         if ($have_before || $have_after) {
999                 common_element_end('ul');
1000                 common_element_end('div');
1001         }
1002 }
1003
1004 /* Following functions are copied from MediaWiki GlobalFunctions.php
1005  * and written by Evan Prodromou. */
1006
1007 function common_accept_to_prefs($accept, $def = '*/*') {
1008         # No arg means accept anything (per HTTP spec)
1009         if(!$accept) {
1010                 return array($def => 1);
1011         }
1012
1013         $prefs = array();
1014
1015         $parts = explode(',', $accept);
1016
1017         foreach($parts as $part) {
1018                 # FIXME: doesn't deal with params like 'text/html; level=1'
1019                 @list($value, $qpart) = explode(';', $part);
1020                 $match = array();
1021                 if(!isset($qpart)) {
1022                         $prefs[$value] = 1;
1023                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1024                         $prefs[$value] = $match[1];
1025                 }
1026         }
1027
1028         return $prefs;
1029 }
1030
1031 function common_mime_type_match($type, $avail) {
1032         if(array_key_exists($type, $avail)) {
1033                 return $type;
1034         } else {
1035                 $parts = explode('/', $type);
1036                 if(array_key_exists($parts[0] . '/*', $avail)) {
1037                         return $parts[0] . '/*';
1038                 } elseif(array_key_exists('*/*', $avail)) {
1039                         return '*/*';
1040                 } else {
1041                         return NULL;
1042                 }
1043         }
1044 }
1045
1046 function common_negotiate_type($cprefs, $sprefs) {
1047         $combine = array();
1048
1049         foreach(array_keys($sprefs) as $type) {
1050                 $parts = explode('/', $type);
1051                 if($parts[1] != '*') {
1052                         $ckey = common_mime_type_match($type, $cprefs);
1053                         if($ckey) {
1054                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1055                         }
1056                 }
1057         }
1058
1059         foreach(array_keys($cprefs) as $type) {
1060                 $parts = explode('/', $type);
1061                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1062                         $skey = common_mime_type_match($type, $sprefs);
1063                         if($skey) {
1064                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1065                         }
1066                 }
1067         }
1068
1069         $bestq = 0;
1070         $besttype = "text/html";
1071
1072         foreach(array_keys($combine) as $type) {
1073                 if($combine[$type] > $bestq) {
1074                         $besttype = $type;
1075                         $bestq = $combine[$type];
1076                 }
1077         }
1078
1079         return $besttype;
1080 }
1081
1082 function common_config($main, $sub) {
1083         global $config;
1084         return $config[$main][$sub];
1085 }
1086
1087 function common_copy_args($from) {
1088         $to = array();
1089         $strip = get_magic_quotes_gpc();
1090         foreach ($from as $k => $v) {
1091                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1092         }
1093         return $to;
1094 }
1095
1096 function common_user_uri(&$user) {
1097         return common_local_url('userbyid', array('id' => $user->id));
1098 }
1099
1100 function common_notice_uri(&$notice) {
1101         return common_local_url('shownotice',
1102                 array('notice' => $notice->id));
1103 }
1104
1105 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1106
1107 function common_confirmation_code($bits) {
1108         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1109         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1110         $chars = ceil($bits/5);
1111         $code = '';
1112         for ($i = 0; $i < $chars; $i++) {
1113                 # XXX: convert to string and back
1114                 $num = hexdec(common_good_rand(1));
1115                 # XXX: randomness is too precious to throw away almost
1116                 # 40% of the bits we get!
1117                 $code .= $codechars[$num%32];
1118         }
1119         return $code;
1120 }
1121
1122 # convert markup to HTML
1123
1124 function common_markup_to_html($c) {
1125         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1126         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1127         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1128         return Markdown($c);
1129 }