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