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