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