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