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