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