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