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