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