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