]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
First pass at replies support http://laconi.ca/PITS/00080
[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', 'text/html,application/xhtml+xml,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         return true;
488 }
489
490 function common_remembered_user() {
491         $user = NULL;
492         # Try to remember
493         $packed = $_COOKIE[REMEMBERME];
494         if ($packed) {
495                 list($id, $code) = explode(':', $packed);
496                 if ($id && $code) {
497                         $rm = Remember_me::staticGet($code);
498                         if ($rm && ($rm->user_id == $id)) {
499                                 $user = User::staticGet($rm->user_id);
500                                 if ($user) {
501                                         # successful!
502                                         $result = $rm->delete();
503                                         if (!$result) {
504                                                 common_log_db_error($rm, 'DELETE', __FILE__);
505                                                 $user = NULL;
506                                         } else {
507                                                 common_set_user($user->nickname);
508                                                 common_real_login(false);
509                                                 # We issue a new cookie, so they can log in
510                                                 # automatically again after this session
511                                                 common_rememberme();
512                                         }
513                                 }
514                         }
515                 }
516         }
517         return $user;
518 }
519
520 # must be called with a valid user!
521
522 function common_forgetme() {
523         common_set_cookie(REMEMBERME, '', 0);
524 }
525
526 # who is the current user?
527 function common_current_user() {
528         if ($_REQUEST[session_name()]) {
529                 common_ensure_session();
530                 $id = $_SESSION['userid'];
531                 if ($id) {
532                         # note: this should cache
533                         $user = User::staticGet($id);
534                         return $user;
535                 }
536         }
537         # that didn't work; try to remember
538         $user = common_remembered_user();
539         return $user;
540 }
541
542 # Logins that are 'remembered' aren't 'real' -- they're subject to
543 # cookie-stealing. So, we don't let them do certain things. New reg,
544 # OpenID, and password logins _are_ real.
545
546 function common_real_login($real=true) {
547         common_ensure_session();
548         $_SESSION['real_login'] = $real;
549 }
550
551 function common_is_real_login() {
552         return common_logged_in() && $_SESSION['real_login'];
553 }
554
555 # get canonical version of nickname for comparison
556 function common_canonical_nickname($nickname) {
557         # XXX: UTF-8 canonicalization (like combining chars)
558         return strtolower($nickname);
559 }
560
561 # get canonical version of email for comparison
562 function common_canonical_email($email) {
563         # XXX: canonicalize UTF-8
564         # XXX: lcase the domain part
565         return $email;
566 }
567
568 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$_+!*();/?:~-]))');
569
570 function common_render_content($text, $notice) {
571         $r = htmlspecialchars($text);
572         $id = $notice->profile_id;
573         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
574         $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
575         # XXX: # tags
576         # XXX: machine tags
577         return $r;
578 }
579
580 function common_at_link($sender_id, $nickname) {
581         # Try to find profiles this profile is subscribed to that have this nickname
582         $recipient = new Profile();
583         # XXX: chokety and bad
584         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
585         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
586         if ($recipient->find(TRUE)) {
587                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
588         }
589         # Try to find profiles that listen to this profile and that have this nickname
590         $recipient = new Profile();
591         # XXX: chokety and bad
592         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
593         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
594         if ($recipient->find(TRUE)) {
595                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
596         }
597         # If this is a local user, try to find a local user with that nickname.
598         $sender = User::staticGet($sender_id);
599         if ($sender) {
600                 $recipient_user = User::staticGet('nickname', $nickname);
601                 if ($recipient_user) {
602                         return '<a href="'.htmlspecialchars(common_profile_url($nickname)).'" class="atlink usertouser">'.$nickname.'</a>';
603                 }
604         }
605         # Otherwise, no links. @messages from local users to remote users,
606         # or from remote users to other remote users, are just
607         # outside our ability to make intelligent guesses about
608         return $nickname;
609 }
610
611 // where should the avatar go for this user?
612
613 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
614         global $config;
615
616         if ($size) {
617                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
618         } else {
619                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
620         }
621 }
622
623 function common_avatar_path($filename) {
624         global $config;
625         return INSTALLDIR . '/avatar/' . $filename;
626 }
627
628 function common_avatar_url($filename) {
629         return common_path('avatar/'.$filename);
630 }
631
632 function common_avatar_display_url($avatar) {
633         $server = common_config('avatar', 'server');
634         if ($server) {
635                 return 'http://'.$server.'/'.$avatar->filename;
636         } else {
637                 return $avatar->url;
638         }
639 }
640
641 function common_default_avatar($size) {
642         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
643                                                           AVATAR_STREAM_SIZE => 'stream',
644                                                           AVATAR_MINI_SIZE => 'mini');
645         return theme_path('default-avatar-'.$sizenames[$size].'.png');
646 }
647
648 function common_local_url($action, $args=NULL) {
649         global $config;
650         if ($config['site']['fancy']) {
651                 return common_fancy_url($action, $args);
652         } else {
653                 return common_simple_url($action, $args);
654         }
655 }
656
657 function common_fancy_url($action, $args=NULL) {
658         switch (strtolower($action)) {
659          case 'public':
660                 if ($args && $args['page']) {
661                         return common_path('?page=' . $args['page']);
662                 } else {
663                         return common_path('');
664                 }
665          case 'publicrss':
666                 return common_path('rss');
667          case 'publicxrds':
668                 return common_path('xrds');
669          case 'doc':
670                 return common_path('doc/'.$args['title']);
671          case 'login':
672          case 'logout':
673          case 'register':
674          case 'subscribe':
675          case 'unsubscribe':
676                 return common_path('main/'.$action);
677          case 'remotesubscribe':
678                 if ($args && $args['nickname']) {
679                         return common_path('main/remote?nickname=' . $args['nickname']);
680                 } else {
681                         return common_path('main/remote');
682                 }
683          case 'openidlogin':
684                 return common_path('main/openid');
685          case 'avatar':
686          case 'password':
687                 return common_path('settings/'.$action);
688          case 'profilesettings':
689                 return common_path('settings/profile');
690          case 'openidsettings':
691                 return common_path('settings/openid');
692          case 'newnotice':
693                 return common_path('notice/new');
694          case 'shownotice':
695                 return common_path('notice/'.$args['notice']);
696          case 'xrds':
697          case 'foaf':
698                 return common_path($args['nickname'].'/'.$action);
699          case 'subscriptions':
700          case 'subscribers':
701          case 'all':
702                 if ($args && $args['page']) {
703                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
704                 } else {
705                         return common_path($args['nickname'].'/'.$action);
706                 }
707          case 'allrss':
708                 return common_path($args['nickname'].'/all/rss');
709          case 'userrss':
710                 return common_path($args['nickname'].'/rss');
711          case 'showstream':
712                 if ($args && $args['page']) {
713                         return common_path($args['nickname'].'?page=' . $args['page']);
714                 } else {
715                         return common_path($args['nickname']);
716                 }
717          case 'confirmaddress':
718                 return common_path('main/confirmaddress/'.$args['code']);
719          case 'userbyid':
720                 return common_path('user/'.$args['id']);
721          case 'recoverpassword':
722             $path = 'main/recoverpassword';
723             if ($args['code']) {
724                 $path .= '/' . $args['code'];
725                 }
726             return common_path($path);
727          case 'imsettings':
728                 return common_path('settings/im');
729          default:
730                 return common_simple_url($action, $args);
731         }
732 }
733
734 function common_simple_url($action, $args=NULL) {
735         global $config;
736         /* XXX: pretty URLs */
737         $extra = '';
738         if ($args) {
739                 foreach ($args as $key => $value) {
740                         $extra .= "&${key}=${value}";
741                 }
742         }
743         return common_path("index.php?action=${action}${extra}");
744 }
745
746 function common_path($relative) {
747         global $config;
748         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
749         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
750 }
751
752 function common_date_string($dt) {
753         // XXX: do some sexy date formatting
754         // return date(DATE_RFC822, $dt);
755         $t = strtotime($dt);
756         $now = time();
757         $diff = $now - $t;
758
759         if ($now < $t) { # that shouldn't happen!
760                 return common_exact_date($dt);
761         } else if ($diff < 60) {
762                 return _t('a few seconds ago');
763         } else if ($diff < 92) {
764                 return _t('about a minute ago');
765         } else if ($diff < 3300) {
766                 return _t('about ') . round($diff/60) . _t(' minutes ago');
767         } else if ($diff < 5400) {
768                 return _t('about an hour ago');
769         } else if ($diff < 22 * 3600) {
770                 return _t('about ') . round($diff/3600) . _t(' hours ago');
771         } else if ($diff < 37 * 3600) {
772                 return _t('about a day ago');
773         } else if ($diff < 24 * 24 * 3600) {
774                 return _t('about ') . round($diff/(24*3600)) . _t(' days ago');
775         } else if ($diff < 46 * 24 * 3600) {
776                 return _t('about a month ago');
777         } else if ($diff < 330 * 24 * 3600) {
778                 return _t('about ') . round($diff/(30*24*3600)) . _t(' months ago');
779         } else if ($diff < 480 * 24 * 3600) {
780                 return _t('about a year ago');
781         } else {
782                 return common_exact_date($dt);
783         }
784 }
785
786 function common_exact_date($dt) {
787         $t = strtotime($dt);
788         return date(DATE_RFC850, $t);
789 }
790
791 function common_date_w3dtf($dt) {
792         $t = strtotime($dt);
793         return date(DATE_W3C, $t);
794 }
795
796 function common_redirect($url, $code=307) {
797         static $status = array(301 => "Moved Permanently",
798                                                    302 => "Found",
799                                                    303 => "See Other",
800                                                    307 => "Temporary Redirect");
801         header("Status: ${code} $status[$code]");
802         header("Location: $url");
803
804         common_start_xml('a',
805                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
806                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
807         common_element('a', array('href' => $url), $url);
808         common_end_xml();
809 }
810
811 function common_save_replies($notice) {
812         # extract all @messages
813         preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
814         $current_user = common_current_user();
815         $sender = $current_user->getProfile();
816         #store replied only for first @ (what user/notice what the reply directed, we assume first @ is it)
817         $reply_for = User::staticGet('nickname', $match[1][0]);
818         for ($i=0; $i<count($match[1]); $i++) {
819                 $nickname = $match[1][$i];
820                 #don't reply to myself
821                 if ($sender->nickname == $nickname) {
822                     continue;
823                 }
824                 $reply = DB_DataObject::factory('reply');
825                 $reply->notice_id = $notice->id;
826                 $recipient_user = User::staticGet('nickname', $nickname);
827                 #if recipient doesn't exist, skip
828                 if (!$recipient_user) {
829                       continue;
830                 }
831                 $reply->user_id = $recipient_user->id;
832                 $reply->created = DB_DataObject_Cast::dateTime();
833                 $recipient_notice = $reply_for->getCurrentNotice();
834                 $reply->replied_id = $recipient_notice->id;
835                 $id = $reply->insert();
836                 if (!$id) {
837                     common_server_error(_t('Problem saving reply.'));
838                     return;
839                 }
840         }
841 }
842
843 function common_broadcast_notice($notice, $remote=false) {
844         if (common_config('queue', 'enabled')) {
845                 # Do it later!
846                 return common_enqueue_notice($notice);
847         } else {
848                 return common_real_broadcast($notice, $remote);
849         }
850 }
851
852 # Stick the notice on the queue
853
854 function common_enqueue_notice($notice) {
855         common_log(LOG_INFO, 'start queueing notice ID = ' . $notice->id);
856         $qi = new Queue_item();
857         $qi->notice_id = $notice->id;
858         $qi->created = DB_DataObject_Cast::dateTime();
859         $result = $qi->insert();
860         if ($result === FALSE) {
861             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
862             common_log(LOG_ERROR, 'DB error inserting queue item: ' . $last_error->message);
863             return false;
864         }
865         common_log(LOG_INFO, 'complete queueing notice ID = ' . $notice->id);
866         return $result;
867 }
868           
869 function common_real_broadcast($notice, $remote=false) {
870         $success = true;
871         if (!$remote) {
872                 # Make sure we have the OMB stuff
873                 require_once(INSTALLDIR.'/lib/omb.php');
874                 $success = omb_broadcast_remote_subscribers($notice);
875                 if (!$success) {
876                         common_log(LOG_ERROR, 'Error in OMB broadcast for notice ' . $notice->id);
877                 }
878         }
879         if ($success) {
880                 require_once(INSTALLDIR.'/lib/jabber.php');
881                 $success = jabber_broadcast_notice($notice);
882                 if (!$success) {
883                         common_log(LOG_ERROR, 'Error in jabber broadcast for notice ' . $notice->id);
884                 }
885         }
886         // XXX: broadcast notices to SMS
887         // XXX: broadcast notices to other IM
888         return $success;
889 }
890
891 function common_broadcast_profile($profile) {
892         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
893         require_once(INSTALLDIR.'/lib/omb.php');
894         omb_broadcast_profile($profile);
895         // XXX: Other broadcasts...?
896         return true;
897 }
898
899 function common_profile_url($nickname) {
900         return common_local_url('showstream', array('nickname' => $nickname));
901 }
902
903 # Don't call if nobody's logged in
904
905 function common_notice_form($action=NULL, $content=NULL) {
906         $user = common_current_user();
907         assert(!is_null($user));
908         common_element_start('form', array('id' => 'status_form',
909                                                                            'method' => 'post',
910                                                                            'action' => common_local_url('newnotice')));
911         common_element_start('p');
912         common_element('label', array('for' => 'status_textarea',
913                                                                   'id' => 'status_label'),
914                                    _t('What\'s up, ').$user->nickname.'?');
915         common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
916         common_element('textarea', array('id' => 'status_textarea',
917                                                                          'cols' => 60,
918                                                                          'rows' => 3,
919                                                                          'name' => 'status_textarea'),
920                                    ($content) ? $content : '');
921         if ($action) {
922                 common_hidden('returnto', $action);
923         }
924         common_element('input', array('id' => 'status_submit',
925                                                                   'name' => 'status_submit',
926                                                                   'type' => 'submit',
927                                                                   'value' => _t('Send')));
928         common_element_end('p');
929         common_element_end('form');
930 }
931
932 function common_mint_tag($extra) {
933         global $config;
934         return
935           'tag:'.$config['tag']['authority'].','.
936           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
937 }
938
939 # Should make up a reasonable root URL
940
941 function common_root_url() {
942         return common_path('');
943 }
944
945 # returns $bytes bytes of random data as a hexadecimal string
946 # "good" here is a goal and not a guarantee
947
948 function common_good_rand($bytes) {
949         # XXX: use random.org...?
950         if (file_exists('/dev/urandom')) {
951                 return common_urandom($bytes);
952         } else { # FIXME: this is probably not good enough
953                 return common_mtrand($bytes);
954         }
955 }
956
957 function common_urandom($bytes) {
958         $h = fopen('/dev/urandom', 'rb');
959         # should not block
960         $src = fread($h, $bytes);
961         fclose($h);
962         $enc = '';
963         for ($i = 0; $i < $bytes; $i++) {
964                 $enc .= sprintf("%02x", (ord($src[$i])));
965         }
966         return $enc;
967 }
968
969 function common_mtrand($bytes) {
970         $enc = '';
971         for ($i = 0; $i < $bytes; $i++) {
972                 $enc .= sprintf("%02x", mt_rand(0, 255));
973         }
974         return $enc;
975 }
976
977 function common_set_returnto($url) {
978         common_ensure_session();
979         $_SESSION['returnto'] = $url;
980 }
981
982 function common_get_returnto() {
983         common_ensure_session();
984         return $_SESSION['returnto'];
985 }
986
987 function common_timestamp() {
988         return date('YmdHis');
989 }
990
991 // XXX: set up gettext
992
993 function _t($str) {
994         return $str;
995 }
996
997 function common_ensure_syslog() {
998         static $initialized = false;
999         if (!$initialized) {
1000                 global $config;
1001                 define_syslog_variables();
1002                 openlog($config['syslog']['appname'], 0, LOG_USER);
1003                 $initialized = true;
1004         }
1005 }
1006
1007 function common_log($priority, $msg, $filename=NULL) {
1008         common_ensure_syslog();
1009         syslog($priority, $msg);
1010 }
1011
1012 function common_debug($msg, $filename=NULL) {
1013         if ($filename) {
1014                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1015         } else {
1016                 common_log(LOG_DEBUG, $msg);
1017         }
1018 }
1019
1020 function common_log_db_error(&$object, $verb, $filename=NULL) {
1021         $objstr = common_log_objstring($object);
1022         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1023         common_log(LOG_ERROR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1024 }
1025
1026 function common_log_objstring(&$object) {
1027         if (is_null($object)) {
1028                 return "NULL";
1029         }
1030         $arr = $object->toArray();
1031         $fields = array();
1032         foreach ($arr as $k => $v) {
1033                 $fields[] = "$k='$v'";
1034         }
1035         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1036         return $objstring;
1037 }
1038
1039 function common_valid_http_url($url) {
1040         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1041 }
1042
1043 function common_valid_tag($tag) {
1044         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1045                 return (Validate::email($matches[1]) ||
1046                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1047         }
1048         return false;
1049 }
1050
1051 # Does a little before-after block for next/prev page
1052
1053 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1054
1055         if ($have_before || $have_after) {
1056                 common_element_start('div', array('id' => 'pagination'));
1057                 common_element_start('ul', array('id' => 'nav_pagination'));
1058         }
1059
1060         if ($have_before) {
1061                 $pargs = array('page' => $page-1);
1062                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1063
1064                 common_element_start('li', 'before');
1065                 common_element('a', array('href' => common_local_url($action, $newargs)),
1066                                            _t('« After'));
1067                 common_element_end('li');
1068         }
1069
1070         if ($have_after) {
1071                 $pargs = array('page' => $page+1);
1072                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1073                 common_element_start('li', 'after');
1074                 common_element('a', array('href' => common_local_url($action, $newargs)),
1075                                                    _t('Before »'));
1076                 common_element_end('li');
1077         }
1078
1079         if ($have_before || $have_after) {
1080                 common_element_end('ul');
1081                 common_element_end('div');
1082         }
1083 }
1084
1085 /* Following functions are copied from MediaWiki GlobalFunctions.php
1086  * and written by Evan Prodromou. */
1087
1088 function common_accept_to_prefs($accept, $def = '*/*') {
1089         # No arg means accept anything (per HTTP spec)
1090         if(!$accept) {
1091                 return array($def => 1);
1092         }
1093
1094         $prefs = array();
1095
1096         $parts = explode(',', $accept);
1097
1098         foreach($parts as $part) {
1099                 # FIXME: doesn't deal with params like 'text/html; level=1'
1100                 @list($value, $qpart) = explode(';', $part);
1101                 $match = array();
1102                 if(!isset($qpart)) {
1103                         $prefs[$value] = 1;
1104                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1105                         $prefs[$value] = $match[1];
1106                 }
1107         }
1108
1109         return $prefs;
1110 }
1111
1112 function common_mime_type_match($type, $avail) {
1113         if(array_key_exists($type, $avail)) {
1114                 return $type;
1115         } else {
1116                 $parts = explode('/', $type);
1117                 if(array_key_exists($parts[0] . '/*', $avail)) {
1118                         return $parts[0] . '/*';
1119                 } elseif(array_key_exists('*/*', $avail)) {
1120                         return '*/*';
1121                 } else {
1122                         return NULL;
1123                 }
1124         }
1125 }
1126
1127 function common_negotiate_type($cprefs, $sprefs) {
1128         $combine = array();
1129
1130         foreach(array_keys($sprefs) as $type) {
1131                 $parts = explode('/', $type);
1132                 if($parts[1] != '*') {
1133                         $ckey = common_mime_type_match($type, $cprefs);
1134                         if($ckey) {
1135                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1136                         }
1137                 }
1138         }
1139
1140         foreach(array_keys($cprefs) as $type) {
1141                 $parts = explode('/', $type);
1142                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1143                         $skey = common_mime_type_match($type, $sprefs);
1144                         if($skey) {
1145                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1146                         }
1147                 }
1148         }
1149
1150         $bestq = 0;
1151         $besttype = "text/html";
1152
1153         foreach(array_keys($combine) as $type) {
1154                 if($combine[$type] > $bestq) {
1155                         $besttype = $type;
1156                         $bestq = $combine[$type];
1157                 }
1158         }
1159
1160         return $besttype;
1161 }
1162
1163 function common_config($main, $sub) {
1164         global $config;
1165         return $config[$main][$sub];
1166 }
1167
1168 function common_copy_args($from) {
1169         $to = array();
1170         $strip = get_magic_quotes_gpc();
1171         foreach ($from as $k => $v) {
1172                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1173         }
1174         return $to;
1175 }
1176
1177 function common_user_uri(&$user) {
1178         return common_local_url('userbyid', array('id' => $user->id));
1179 }
1180
1181 function common_notice_uri(&$notice) {
1182         return common_local_url('shownotice',
1183                 array('notice' => $notice->id));
1184 }
1185
1186 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1187
1188 function common_confirmation_code($bits) {
1189         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1190         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1191         $chars = ceil($bits/5);
1192         $code = '';
1193         for ($i = 0; $i < $chars; $i++) {
1194                 # XXX: convert to string and back
1195                 $num = hexdec(common_good_rand(1));
1196                 # XXX: randomness is too precious to throw away almost
1197                 # 40% of the bits we get!
1198                 $code .= $codechars[$num%32];
1199         }
1200         return $code;
1201 }
1202
1203 # convert markup to HTML
1204
1205 function common_markup_to_html($c) {
1206         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1207         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1208         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1209         return Markdown($c);
1210 }