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