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