]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
469bc986febd948edf43d1be91d834cd3bbdd492
[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         static $empty_tag = array('base', 'meta', 'link', 'hr',
97                                                           'br', 'param', 'img', 'area',
98                                                           'input', 'col');
99         global $xw;
100         # XXX: check namespace
101         if (in_array($tag, $empty_tag)) {
102                 $xw->endElement();
103         } else {
104                 $xw->fullEndElement();
105         }
106 }
107
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109         common_element_start($tag, $attrs);
110         global $xw;
111         if (!is_null($content)) {
112                 $xw->text($content);
113         }
114         common_element_end($tag);
115 }
116
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
118         global $xw;
119         $xw = new XMLWriter();
120         $xw->openURI('php://output');
121         $xw->setIndent(true);
122         $xw->startDocument('1.0', 'UTF-8');
123         if ($doc) {
124                 $xw->writeDTD($doc, $public, $system);
125         }
126 }
127
128 function common_end_xml() {
129         global $xw;
130         $xw->endDocument();
131         $xw->flush();
132 }
133
134 function common_init_language() {
135         mb_internal_encoding('UTF-8');
136         $language = common_language();
137         # So we don't have to make people install the gettext locales
138         putenv('LANGUAGE='.$language);
139         putenv('LANG='.$language);      
140         $locale_set = setlocale(LC_ALL, $language . ".utf8",
141                                                         $language . ".UTF8",
142                                                         $language . ".utf-8",
143                                                         $language . ".UTF-8",
144                                                         $language);
145         bindtextdomain("laconica", common_config('site','locale_path'));
146         bind_textdomain_codeset("laconica", "UTF-8");
147         textdomain("laconica");
148         setlocale(LC_CTYPE, 'C');
149 }
150
151 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
152
153 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
154         global $config, $xw;
155
156         $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
157
158         # XXX: allow content negotiation for RDF, RSS, or XRDS
159
160         $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
161                                                                   common_accept_to_prefs(PAGE_TYPE_PREFS));
162
163         if (!$type) {
164                 common_user_error(_('This page is not available in a media type you accept'), 406);
165                 exit(0);
166         }
167
168         header('Content-Type: '.$type);
169
170         common_start_xml('html',
171                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
172                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
173
174         # FIXME: correct language for interface
175
176         $language = common_language();
177         
178         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
179                                                                            'xml:lang' => $language,
180                                                                            'lang' => $language));
181
182         common_element_start('head');
183         common_element('title', NULL,
184                                    $pagetitle . " - " . $config['site']['name']);
185         common_element('link', array('rel' => 'stylesheet',
186                                                                  'type' => 'text/css',
187                                                                  'href' => theme_path('display.css'),
188                                                                  'media' => 'screen, projection, tv'));
189         foreach (array(6,7) as $ver) {
190                 if (file_exists(theme_file('ie'.$ver.'.css'))) {
191                         # Yes, IE people should be put in jail.
192                         $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
193                                                           'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
194                 }
195         }
196
197         common_element('script', array('type' => 'text/javascript',
198                                                                    'src' => common_path('js/jquery.min.js')),
199                                    ' ');
200         common_element('script', array('type' => 'text/javascript',
201                                                                    'src' => common_path('js/util.js')),
202                                    ' ');
203         common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
204                                         'href' =>  common_local_url('opensearch', array('type' => 'people')),
205                                         'title' => common_config('site', 'name').' People Search'));
206
207         common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
208                                         'href' =>  common_local_url('opensearch', array('type' => 'notice')),
209                                         'title' => common_config('site', 'name').' Notice Search'));
210
211         if ($callable) {
212                 if ($data) {
213                         call_user_func($callable, $data);
214                 } else {
215                         call_user_func($callable);
216                 }
217         }
218         common_element_end('head');
219         common_element_start('body');
220         common_element_start('div', array('id' => 'wrap'));
221         common_element_start('div', array('id' => 'header'));
222         common_nav_menu();
223         if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
224                 || file_exists(theme_file('logo.png')))
225         {
226                 common_element_start('a', array('href' => common_local_url('public')));
227                 common_element('img', array('src' => isset($config['site']['logo']) ?
228                                                                         ($config['site']['logo']) : theme_path('logo.png'),
229                                                                         'alt' => $config['site']['name'],
230                                                                         'id' => 'logo'));
231                 common_element_end('a');
232         } else {
233                 common_element_start('p', array('id' => 'branding'));
234                 common_element('a', array('href' => common_local_url('public')),
235                                            $config['site']['name']);
236                 common_element_end('p');
237         }
238
239         common_element('h1', 'pagetitle', $pagetitle);
240
241         if ($headercall) {
242                 if ($data) {
243                         call_user_func($headercall, $data);
244                 } else {
245                         call_user_func($headercall);
246                 }
247         }
248         common_element_end('div');
249         common_element_start('div', array('id' => 'content'));
250 }
251
252 function common_show_footer() {
253         global $xw, $config;
254         common_element_end('div'); # content div
255         common_foot_menu();
256         common_element_start('div', array('id' => 'footer'));
257         common_element_start('div', 'laconica');
258         if (common_config('site', 'broughtby')) {
259                 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
260         } else {
261                 $instr = _('**%%site.name%%** is a microblogging service. ');
262         }
263         $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION);
264     $output = common_markup_to_html($instr);
265     common_raw($output);
266         common_element_end('div');
267         common_element('img', array('id' => 'cc',
268                                                                 'src' => $config['license']['image'],
269                                                                 'alt' => $config['license']['title']));
270         common_element_start('p');
271         common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
272         common_element('a', array('class' => 'license',
273                                                           'rel' => 'license',
274                                                           'href' => $config['license']['url']),
275                                    $config['license']['title']);
276         common_text(_('. Contributors should be attributed by full name or nickname.'));
277         common_element_end('p');
278         common_element_end('div');
279         common_element_end('div');
280         common_element_end('body');
281         common_element_end('html');
282         common_end_xml();
283 }
284
285 function common_text($txt) {
286         global $xw;
287         $xw->text($txt);
288 }
289
290 function common_raw($xml) {
291         global $xw;
292         $xw->writeRaw($xml);
293 }
294
295 function common_nav_menu() {
296         $user = common_current_user();
297         common_element_start('ul', array('id' => 'nav'));
298         if ($user) {
299                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
300                                                  _('Home'));
301         }
302         common_menu_item(common_local_url('peoplesearch'), _('Search'));
303         common_menu_item(common_local_url('tags'), _('Tags'));
304         if ($user) {
305                 common_menu_item(common_local_url('profilesettings'),
306                                                  _('Settings'));
307                 common_menu_item(common_local_url('logout'),
308                                                  _('Logout'));
309         } else {
310                 common_menu_item(common_local_url('login'), _('Login'));
311                 if (!common_config('site', 'closed')) {
312                         common_menu_item(common_local_url('register'), _('Register'));
313                 }
314                 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
315         }
316         common_element_end('ul');
317 }
318
319 function common_foot_menu() {
320         common_element_start('ul', array('id' => 'nav_sub'));
321         common_menu_item(common_local_url('doc', array('title' => 'help')),
322                                          _('Help'));
323         common_menu_item(common_local_url('doc', array('title' => 'about')),
324                                          _('About'));
325         common_menu_item(common_local_url('doc', array('title' => 'faq')),
326                                          _('FAQ'));
327         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
328                                          _('Privacy'));
329         common_menu_item(common_local_url('doc', array('title' => 'source')),
330                                          _('Source'));
331         common_menu_item(common_local_url('doc', array('title' => 'contact')),
332                                          _('Contact'));
333         common_element_end('ul');
334 }
335
336 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
337         $lattrs = array();
338         if ($is_selected) {
339                 $lattrs['class'] = 'current';
340         }
341         common_element_start('li', $lattrs);
342         $attrs['href'] = $url;
343         if ($title) {
344                 $attrs['title'] = $title;
345         }
346         common_element('a', $attrs, $text);
347         common_element_end('li');
348 }
349
350 function common_input($id, $label, $value=NULL,$instructions=NULL) {
351         common_element_start('p');
352         common_element('label', array('for' => $id), $label);
353         $attrs = array('name' => $id,
354                                    'type' => 'text',
355                                    'class' => 'input_text',
356                                    'id' => $id);
357         if ($value) {
358                 $attrs['value'] = htmlspecialchars($value);
359         }
360         common_element('input', $attrs);
361         if ($instructions) {
362                 common_element('span', 'input_instructions', $instructions);
363         }
364         common_element_end('p');
365 }
366
367 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
368 {
369         common_element_start('p');
370         $attrs = array('name' => $id,
371                                    'type' => 'checkbox',
372                                    'class' => 'checkbox',
373                                    'id' => $id);
374         if ($value) {
375                 $attrs['value'] = htmlspecialchars($value);
376         }
377         if ($checked) {
378                 $attrs['checked'] = 'checked';
379         }
380         common_element('input', $attrs);
381         # XXX: use a <label>
382         common_text(' ');
383         common_element('span', 'checkbox_label', $label);
384         common_text(' ');
385         if ($instructions) {
386                 common_element('span', 'input_instructions', $instructions);
387         }
388         common_element_end('p');
389 }
390
391 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
392         common_element_start('p');
393         common_element('label', array('for' => $id), $label);
394         common_element_start('select', array('id' => $id, 'name' => $id));
395         if ($blank_select) {
396                 common_element('option', array('value' => ''));
397         }
398         foreach ($content as $value => $option) {
399                 if ($value == $selected) {
400                         common_element('option', array('value' => $value, 'selected' => $value), $option);
401                 } else {
402                         common_element('option', array('value' => $value), $option);
403                 }
404         }
405         common_element_end('select');
406         if ($instructions) {
407                 common_element('span', 'input_instructions', $instructions);
408         }
409         common_element_end('p');
410 }
411 function common_hidden($id, $value) {
412         common_element('input', array('name' => $id,
413                                                                   'type' => 'hidden',
414                                                                   'id' => $id,
415                                                                   'value' => $value));
416 }
417
418 function common_password($id, $label, $instructions=NULL) {
419         common_element_start('p');
420         common_element('label', array('for' => $id), $label);
421         $attrs = array('name' => $id,
422                                    'type' => 'password',
423                                    'class' => 'password',
424                                    'id' => $id);
425         common_element('input', $attrs);
426         if ($instructions) {
427                 common_element('span', 'input_instructions', $instructions);
428         }
429         common_element_end('p');
430 }
431
432 function common_submit($id, $label) {
433         global $xw;
434         common_element_start('p');
435         common_element('input', array('type' => 'submit',
436                                                                   'id' => $id,
437                                                                   'name' => $id,
438                                                                   'class' => 'submit',
439                                                                   'value' => $label));
440         common_element_end('p');
441 }
442
443 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
444         common_element_start('p');
445         common_element('label', array('for' => $id), $label);
446         common_element('textarea', array('rows' => 3,
447                                                                          'cols' => 40,
448                                                                          'name' => $id,
449                                                                          'id' => $id),
450                                    ($content) ? $content : '');
451         if ($instructions) {
452                 common_element('span', 'input_instructions', $instructions);
453         }
454         common_element_end('p');
455 }
456
457 function common_timezone() {
458         if (common_logged_in()) {
459                 $user = common_current_user();
460                 if ($user->timezone) {
461                         return $user->timezone;
462                 }
463         }
464
465         global $config;
466         return $config['site']['timezone'];
467 }
468
469 function common_language() {
470         $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
471         $language = array();
472         $user_language = FALSE;
473
474         if (common_logged_in()) {
475                 $user = common_current_user();
476                 $user_language = $user->language;
477         }
478
479         if ($user_language) {
480                 return $user_language;
481         } else if (!empty($httplang)) {
482                 $language = client_prefered_language($httplang);
483                 if ($language) {
484                     return $language;
485                 }
486         } else {
487                 return $config['site']['language'];
488         }
489 }
490 # salted, hashed passwords are stored in the DB
491
492 function common_munge_password($password, $id) {
493         return md5($password . $id);
494 }
495
496 # check if a username exists and has matching password
497 function common_check_user($nickname, $password) {
498         # NEVER allow blank passwords, even if they match the DB
499         if (mb_strlen($password) == 0) {
500                 return false;
501         }
502         $user = User::staticGet('nickname', $nickname);
503         if (is_null($user)) {
504                 return false;
505         } else {
506                 if (0 == strcmp(common_munge_password($password, $user->id),
507                                                 $user->password)) {
508                         return $user;
509                 } else {
510                         return false;
511                 }
512         }
513 }
514
515 # is the current user logged in?
516 function common_logged_in() {
517         return (!is_null(common_current_user()));
518 }
519
520 function common_have_session() {
521         return (0 != strcmp(session_id(), ''));
522 }
523
524 function common_ensure_session() {
525         if (!common_have_session()) {
526                 @session_start();
527         }
528 }
529
530 # Three kinds of arguments:
531 # 1) a user object
532 # 2) a nickname
533 # 3) NULL to clear
534
535 function common_set_user($user) {
536         if (is_null($user) && common_have_session()) {
537                 unset($_SESSION['userid']);
538                 return true;
539         } else if (is_string($user)) {
540                 $nickname = $user;
541                 $user = User::staticGet('nickname', $nickname);
542         } else if (!($user instanceof User)) {
543                 return false;
544         }
545
546         if ($user) {
547                 common_ensure_session();
548                 $_SESSION['userid'] = $user->id;
549                 return $user;
550         }
551         return false;
552 }
553
554 function common_set_cookie($key, $value, $expiration=0) {
555         $path = common_config('site', 'path');
556         $server = common_config('site', 'server');
557
558         if ($path && ($path != '/')) {
559                 $cookiepath = '/' . $path . '/';
560         } else {
561                 $cookiepath = '/';
562         }
563         return setcookie($key,
564                          $value,
565                                  $expiration,
566                                          $cookiepath,
567                                      $server);
568 }
569
570 define('REMEMBERME', 'rememberme');
571 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
572
573 function common_rememberme($user=NULL) {
574         if (!$user) {
575                 $user = common_current_user();
576                 if (!$user) {
577                         common_debug('No current user to remember', __FILE__);
578                         return false;
579                 }
580         }
581         $rm = new Remember_me();
582         $rm->code = common_good_rand(16);
583         $rm->user_id = $user->id;
584         $result = $rm->insert();
585         if (!$result) {
586                 common_log_db_error($rm, 'INSERT', __FILE__);
587                 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
588                 return false;
589         }
590         common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
591         common_set_cookie(REMEMBERME,
592                                           implode(':', array($rm->user_id, $rm->code)),
593                                           time() + REMEMBERME_EXPIRY);
594         return true;
595 }
596
597 function common_remembered_user() {
598         $user = NULL;
599         # Try to remember
600         $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
601         if ($packed) {
602                 list($id, $code) = explode(':', $packed);
603                 if ($id && $code) {
604                         $rm = Remember_me::staticGet($code);
605                         if ($rm && ($rm->user_id == $id)) {
606                                 $user = User::staticGet($rm->user_id);
607                                 if ($user) {
608                                         # successful!
609                                         $result = $rm->delete();
610                                         if (!$result) {
611                                                 common_log_db_error($rm, 'DELETE', __FILE__);
612                                                 $user = NULL;
613                                         } else {
614                                                 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
615                                                 common_set_user($user->nickname);
616                                                 common_real_login(false);
617                                                 # We issue a new cookie, so they can log in
618                                                 # automatically again after this session
619                                                 common_rememberme($user);
620                                         }
621                                 }
622                         }
623                 }
624         }
625         return $user;
626 }
627
628 # must be called with a valid user!
629
630 function common_forgetme() {
631         common_set_cookie(REMEMBERME, '', 0);
632 }
633
634 # who is the current user?
635 function common_current_user() {
636         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
637                 common_ensure_session();
638                 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
639                 if ($id) {
640                         # note: this should cache
641                         $user = User::staticGet($id);
642                         return $user;
643                 }
644         }
645         # that didn't work; try to remember
646         $user = common_remembered_user();
647         if ($user) {
648                 common_debug("Got User " . $user->nickname);
649             common_debug("Faking session on remembered user");
650             $_SESSION['userid'] = $user->id;
651         }
652         return $user;
653 }
654
655 # Logins that are 'remembered' aren't 'real' -- they're subject to
656 # cookie-stealing. So, we don't let them do certain things. New reg,
657 # OpenID, and password logins _are_ real.
658
659 function common_real_login($real=true) {
660         common_ensure_session();
661         $_SESSION['real_login'] = $real;
662 }
663
664 function common_is_real_login() {
665         return common_logged_in() && $_SESSION['real_login'];
666 }
667
668 # get canonical version of nickname for comparison
669 function common_canonical_nickname($nickname) {
670         # XXX: UTF-8 canonicalization (like combining chars)
671         return strtolower($nickname);
672 }
673
674 # get canonical version of email for comparison
675 function common_canonical_email($email) {
676         # XXX: canonicalize UTF-8
677         # XXX: lcase the domain part
678         return $email;
679 }
680
681 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$_+!*();/?:~-]))');
682
683 function common_render_content($text, $notice) {
684         $r = htmlspecialchars($text);
685
686         $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
687         $id = $notice->profile_id;
688         $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
689         $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
690         $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
691         $r = preg_replace('/(^|\s+)#([A-Za-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
692         # XXX: machine tags
693         return $r;
694 }
695
696 function common_tag_link($tag) {
697         if(common_config('site', 'fancy')) {
698                 return '<a href="' . htmlspecialchars(common_path('tag/' . strtolower($tag))) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
699         } else {
700                 return '<a href="' . htmlspecialchars(common_path('index.php?action=tag&tag=' . strtolower($tag))) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
701         }
702 }
703
704 function common_at_link($sender_id, $nickname) {
705         $sender = Profile::staticGet($sender_id);
706         $recipient = common_relative_profile($sender, $nickname);
707         if ($recipient) {
708                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
709         } else {
710                 return $nickname;
711         }
712 }
713
714 function common_relative_profile($sender, $nickname, $dt=NULL) {
715         # Try to find profiles this profile is subscribed to that have this nickname
716         $recipient = new Profile();
717         # XXX: use a join instead of a subquery
718         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
719         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
720         if ($recipient->find(TRUE)) {
721                 # XXX: should probably differentiate between profiles with
722                 # the same name by date of most recent update
723                 return $recipient;
724         }
725         # Try to find profiles that listen to this profile and that have this nickname
726         $recipient = new Profile();
727         # XXX: use a join instead of a subquery
728         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
729         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
730         if ($recipient->find(TRUE)) {
731                 # XXX: should probably differentiate between profiles with
732                 # the same name by date of most recent update
733                 return $recipient;
734         }
735         # If this is a local user, try to find a local user with that nickname.
736         $sender = User::staticGet($sender->id);
737         if ($sender) {
738                 $recipient_user = User::staticGet('nickname', $nickname);
739                 if ($recipient_user) {
740                         return $recipient_user->getProfile();
741                 }
742         }
743         # Otherwise, no links. @messages from local users to remote users,
744         # or from remote users to other remote users, are just
745         # outside our ability to make intelligent guesses about
746         return NULL;
747 }
748
749 // where should the avatar go for this user?
750
751 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
752         global $config;
753
754         if ($size) {
755                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
756         } else {
757                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
758         }
759 }
760
761 function common_avatar_path($filename) {
762         global $config;
763         return INSTALLDIR . '/avatar/' . $filename;
764 }
765
766 function common_avatar_url($filename) {
767         return common_path('avatar/'.$filename);
768 }
769
770 function common_avatar_display_url($avatar) {
771         $server = common_config('avatar', 'server');
772         if ($server) {
773                 return 'http://'.$server.'/'.$avatar->filename;
774         } else {
775                 return $avatar->url;
776         }
777 }
778
779 function common_default_avatar($size) {
780         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
781                                                           AVATAR_STREAM_SIZE => 'stream',
782                                                           AVATAR_MINI_SIZE => 'mini');
783         return theme_path('default-avatar-'.$sizenames[$size].'.png');
784 }
785
786 function common_local_url($action, $args=NULL) {
787         global $config;
788         if ($config['site']['fancy']) {
789                 return common_fancy_url($action, $args);
790         } else {
791                 return common_simple_url($action, $args);
792         }
793 }
794
795 function common_fancy_url($action, $args=NULL) {
796         switch (strtolower($action)) {
797          case 'public':
798                 if ($args && isset($args['page'])) {
799                         return common_path('?page=' . $args['page']);
800                 } else {
801                         return common_path('');
802                 }
803          case 'publicrss':
804                 return common_path('rss');
805          case 'publicxrds':
806                 return common_path('xrds');
807          case 'opensearch':
808                 if ($args && $args['type']) {
809                         return common_path('opensearch/'.$args['type']);
810                 } else {
811                         return common_path('opensearch/people');
812                 }
813          case 'doc':
814                 return common_path('doc/'.$args['title']);
815          case 'login':
816          case 'logout':
817          case 'register':
818          case 'subscribe':
819          case 'unsubscribe':
820                 return common_path('main/'.$action);
821          case 'remotesubscribe':
822                 if ($args && $args['nickname']) {
823                         return common_path('main/remote?nickname=' . $args['nickname']);
824                 } else {
825                         return common_path('main/remote');
826                 }
827          case 'openidlogin':
828                 return common_path('main/openid');
829          case 'avatar':
830          case 'password':
831                 return common_path('settings/'.$action);
832          case 'profilesettings':
833                 return common_path('settings/profile');
834          case 'emailsettings':
835                 return common_path('settings/email');
836          case 'openidsettings':
837                 return common_path('settings/openid');
838          case 'smssettings':
839                 return common_path('settings/sms');
840          case 'newnotice':
841                 if ($args && $args['replyto']) {
842                         return common_path('notice/new?replyto='.$args['replyto']);
843                 } else {
844                         return common_path('notice/new');
845                 }
846          case 'shownotice':
847                 return common_path('notice/'.$args['notice']);
848          case 'deletenotice':
849                 if ($args && $args['notice']) {
850                         return common_path('notice/delete/'.$args['notice']);
851                 } else {
852                         return common_path('notice/delete');
853                 }
854          case 'xrds':
855          case 'foaf':
856                 return common_path($args['nickname'].'/'.$action);
857          case 'subscriptions':
858          case 'subscribers':
859          case 'all':
860          case 'replies':
861                 if ($args && isset($args['page'])) {
862                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
863                 } else {
864                         return common_path($args['nickname'].'/'.$action);
865                 }
866          case 'allrss':
867                 return common_path($args['nickname'].'/all/rss');
868          case 'repliesrss':
869                 return common_path($args['nickname'].'/replies/rss');
870          case 'userrss':
871                 return common_path($args['nickname'].'/rss');
872          case 'showstream':
873                 if ($args && isset($args['page'])) {
874                         return common_path($args['nickname'].'?page=' . $args['page']);
875                 } else {
876                         return common_path($args['nickname']);
877                 }
878          case 'confirmaddress':
879                 return common_path('main/confirmaddress/'.$args['code']);
880          case 'userbyid':
881                 return common_path('user/'.$args['id']);
882          case 'recoverpassword':
883             $path = 'main/recoverpassword';
884             if ($args['code']) {
885                 $path .= '/' . $args['code'];
886                 }
887             return common_path($path);
888          case 'imsettings':
889                 return common_path('settings/im');
890          case 'peoplesearch':
891                 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
892          case 'noticesearch':
893                 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
894          case 'noticesearchrss':
895                 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
896          case 'avatarbynickname':
897                 return common_path($args['nickname'].'/avatar/'.$args['size']);
898          case 'tag':
899             if (isset($args['tag']) && $args['tag']) {
900                         $path = 'tag/' . $args['tag'];
901                         unset($args['tag']);
902                 } else {
903                         $path = 'tags';
904                 }
905                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
906          case 'tags':
907                 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
908          default:
909                 return common_simple_url($action, $args);
910         }
911 }
912
913 function common_simple_url($action, $args=NULL) {
914         global $config;
915         /* XXX: pretty URLs */
916         $extra = '';
917         if ($args) {
918                 foreach ($args as $key => $value) {
919                         $extra .= "&${key}=${value}";
920                 }
921         }
922         return common_path("index.php?action=${action}${extra}");
923 }
924
925 function common_path($relative) {
926         global $config;
927         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
928         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
929 }
930
931 function common_date_string($dt) {
932         // XXX: do some sexy date formatting
933         // return date(DATE_RFC822, $dt);
934         $t = strtotime($dt);
935         $now = time();
936         $diff = $now - $t;
937
938         if ($now < $t) { # that shouldn't happen!
939                 return common_exact_date($dt);
940         } else if ($diff < 60) {
941                 return _('a few seconds ago');
942         } else if ($diff < 92) {
943                 return _('about a minute ago');
944         } else if ($diff < 3300) {
945                 return sprintf(_('about %d minutes ago'), round($diff/60));
946         } else if ($diff < 5400) {
947                 return _('about an hour ago');
948         } else if ($diff < 22 * 3600) {
949                 return sprintf(_('about %d hours ago'), round($diff/3600));
950         } else if ($diff < 37 * 3600) {
951                 return _('about a day ago');
952         } else if ($diff < 24 * 24 * 3600) {
953                 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
954         } else if ($diff < 46 * 24 * 3600) {
955                 return _('about a month ago');
956         } else if ($diff < 330 * 24 * 3600) {
957                 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
958         } else if ($diff < 480 * 24 * 3600) {
959                 return _('about a year ago');
960         } else {
961                 return common_exact_date($dt);
962         }
963 }
964
965 function common_exact_date($dt) {
966     static $_utc;
967     static $_siteTz;
968
969     if (!$_utc) {
970         $_utc = new DateTimeZone('UTC');
971         $_siteTz = new DateTimeZone(common_timezone());
972     }
973
974         $dateStr = date('d F Y H:i:s', strtotime($dt));
975         $d = new DateTime($dateStr, $_utc);
976         $d->setTimezone($_siteTz);
977         return $d->format(DATE_RFC850);
978 }
979
980 function common_date_w3dtf($dt) {
981         $dateStr = date('d F Y H:i:s', strtotime($dt));
982         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
983         $d->setTimezone(new DateTimeZone(common_timezone()));
984         return $d->format(DATE_W3C);
985 }
986
987 function common_date_rfc2822($dt) {
988         $dateStr = date('d F Y H:i:s', strtotime($dt));
989         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
990         $d->setTimezone(new DateTimeZone(common_timezone()));
991         return $d->format('r');
992 }
993
994 function common_date_iso8601($dt) {
995         $dateStr = date('d F Y H:i:s', strtotime($dt));
996         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
997         $d->setTimezone(new DateTimeZone(common_timezone()));
998         return $d->format('c');
999 }
1000
1001 function common_sql_now() {
1002         return strftime('%Y-%m-%d %H:%M:%S', time());
1003 }
1004
1005 function common_redirect($url, $code=307) {
1006         static $status = array(301 => "Moved Permanently",
1007                                                    302 => "Found",
1008                                                    303 => "See Other",
1009                                                    307 => "Temporary Redirect");
1010         header("Status: ${code} $status[$code]");
1011         header("Location: $url");
1012
1013         common_start_xml('a',
1014                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
1015                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1016         common_element('a', array('href' => $url), $url);
1017         common_end_xml();
1018     exit;
1019 }
1020
1021 function common_save_replies($notice) {
1022         # Alternative reply format
1023         $tname = false;
1024         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1025                 $tname = $match[1];
1026         }
1027         # extract all @messages
1028         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1029         if (!$cnt && !$tname) {
1030                 return true;
1031         }
1032         # XXX: is there another way to make an array copy?
1033         $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1034         $sender = Profile::staticGet($notice->profile_id);
1035         # store replied only for first @ (what user/notice what the reply directed,
1036         # we assume first @ is it)
1037         for ($i=0; $i<count($names); $i++) {
1038                 $nickname = $names[$i];
1039                 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1040                 if (!$recipient) {
1041                         continue;
1042                 }
1043                 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1044                         $reply_for = $recipient;
1045                         $recipient_notice = $reply_for->getCurrentNotice();
1046                         if ($recipient_notice) {
1047                                 $orig = clone($notice);
1048                                 $notice->reply_to = $recipient_notice->id;
1049                                 $notice->update($orig);
1050                         }
1051                 }
1052                 $reply = new Reply();
1053                 $reply->notice_id = $notice->id;
1054                 $reply->profile_id = $recipient->id;
1055                 $id = $reply->insert();
1056                 if (!$id) {
1057                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1058                         common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1059                         common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1060                         return;
1061                 }
1062         }
1063 }
1064
1065 function common_broadcast_notice($notice, $remote=false) {
1066         if (common_config('queue', 'enabled')) {
1067                 # Do it later!
1068                 return common_enqueue_notice($notice);
1069         } else {
1070                 return common_real_broadcast($notice, $remote);
1071         }
1072 }
1073
1074 # Stick the notice on the queue
1075
1076 function common_enqueue_notice($notice) {
1077         foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1078                 $qi = new Queue_item();
1079                 $qi->notice_id = $notice->id;
1080                 $qi->transport = $transport;
1081                 $qi->created = $notice->created;
1082         $result = $qi->insert();
1083                 if (!$result) {
1084                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1085                         common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1086                         return false;
1087                 }
1088                 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1089         }
1090         return $result;
1091 }
1092
1093 function common_dequeue_notice($notice) {
1094         $qi = Queue_item::staticGet($notice->id);
1095         if ($qi) {
1096                 $result = $qi->delete();
1097                 if (!$result) {
1098                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1099                     common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1100                     return false;
1101                 }
1102                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1103                 return $result;
1104         } else {
1105             return false;
1106         }
1107 }
1108
1109 function common_real_broadcast($notice, $remote=false) {
1110         $success = true;
1111         if (!$remote) {
1112                 # Make sure we have the OMB stuff
1113                 require_once(INSTALLDIR.'/lib/omb.php');
1114                 $success = omb_broadcast_remote_subscribers($notice);
1115                 if (!$success) {
1116                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1117                 }
1118         }
1119         if ($success) {
1120                 require_once(INSTALLDIR.'/lib/jabber.php');
1121                 $success = jabber_broadcast_notice($notice);
1122                 if (!$success) {
1123                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1124                 }
1125         }
1126         if ($success) {
1127                 require_once(INSTALLDIR.'/lib/mail.php');
1128                 $success = mail_broadcast_notice_sms($notice);
1129                 if (!$success) {
1130                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1131                 }
1132         }
1133         if ($success) {
1134                 $success = jabber_public_notice($notice);
1135                 if (!$success) {
1136                         common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1137                 }
1138         }
1139         // XXX: broadcast notices to other IM
1140         return $success;
1141 }
1142
1143 function common_broadcast_profile($profile) {
1144         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1145         require_once(INSTALLDIR.'/lib/omb.php');
1146         omb_broadcast_profile($profile);
1147         // XXX: Other broadcasts...?
1148         return true;
1149 }
1150
1151 function common_profile_url($nickname) {
1152         return common_local_url('showstream', array('nickname' => $nickname));
1153 }
1154
1155 # Don't call if nobody's logged in
1156
1157 function common_notice_form($action=NULL, $content=NULL) {
1158         $user = common_current_user();
1159         assert(!is_null($user));
1160         common_element_start('form', array('id' => 'status_form',
1161                                                                            'method' => 'post',
1162                                                                            'action' => common_local_url('newnotice')));
1163         common_element_start('p');
1164         common_element('label', array('for' => 'status_textarea',
1165                                                                   'id' => 'status_label'),
1166                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1167         common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1168         common_element('textarea', array('id' => 'status_textarea',
1169                                                                          'cols' => 60,
1170                                                                          'rows' => 3,
1171                                                                          'name' => 'status_textarea'),
1172                                    ($content) ? $content : '');
1173         if ($action) {
1174                 common_hidden('returnto', $action);
1175         }
1176         common_element('input', array('id' => 'status_submit',
1177                                                                   'name' => 'status_submit',
1178                                                                   'type' => 'submit',
1179                                                                   'value' => _('Send')));
1180         common_element_end('p');
1181         common_element_end('form');
1182 }
1183
1184 # Should make up a reasonable root URL
1185
1186 function common_root_url() {
1187         return common_path('');
1188 }
1189
1190 # returns $bytes bytes of random data as a hexadecimal string
1191 # "good" here is a goal and not a guarantee
1192
1193 function common_good_rand($bytes) {
1194         # XXX: use random.org...?
1195         if (file_exists('/dev/urandom')) {
1196                 return common_urandom($bytes);
1197         } else { # FIXME: this is probably not good enough
1198                 return common_mtrand($bytes);
1199         }
1200 }
1201
1202 function common_urandom($bytes) {
1203         $h = fopen('/dev/urandom', 'rb');
1204         # should not block
1205         $src = fread($h, $bytes);
1206         fclose($h);
1207         $enc = '';
1208         for ($i = 0; $i < $bytes; $i++) {
1209                 $enc .= sprintf("%02x", (ord($src[$i])));
1210         }
1211         return $enc;
1212 }
1213
1214 function common_mtrand($bytes) {
1215         $enc = '';
1216         for ($i = 0; $i < $bytes; $i++) {
1217                 $enc .= sprintf("%02x", mt_rand(0, 255));
1218         }
1219         return $enc;
1220 }
1221
1222 function common_set_returnto($url) {
1223         common_ensure_session();
1224         $_SESSION['returnto'] = $url;
1225 }
1226
1227 function common_get_returnto() {
1228         common_ensure_session();
1229         return $_SESSION['returnto'];
1230 }
1231
1232 function common_timestamp() {
1233         return date('YmdHis');
1234 }
1235
1236 function common_ensure_syslog() {
1237         static $initialized = false;
1238         if (!$initialized) {
1239                 global $config;
1240                 openlog($config['syslog']['appname'], 0, LOG_USER);
1241                 $initialized = true;
1242         }
1243 }
1244
1245 function common_log($priority, $msg, $filename=NULL) {
1246         $logfile = common_config('site', 'logfile');
1247         if ($logfile) {
1248                 $log = fopen($logfile, "a");
1249                 if ($log) {
1250                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1251                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1252                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1253                         fwrite($log, $output);
1254                         fclose($log);
1255                 }
1256         } else {
1257                 common_ensure_syslog();
1258                 syslog($priority, $msg);
1259         }
1260 }
1261
1262 function common_debug($msg, $filename=NULL) {
1263         if ($filename) {
1264                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1265         } else {
1266                 common_log(LOG_DEBUG, $msg);
1267         }
1268 }
1269
1270 function common_log_db_error(&$object, $verb, $filename=NULL) {
1271         $objstr = common_log_objstring($object);
1272         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1273         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1274 }
1275
1276 function common_log_objstring(&$object) {
1277         if (is_null($object)) {
1278                 return "NULL";
1279         }
1280         $arr = $object->toArray();
1281         $fields = array();
1282         foreach ($arr as $k => $v) {
1283                 $fields[] = "$k='$v'";
1284         }
1285         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1286         return $objstring;
1287 }
1288
1289 function common_valid_http_url($url) {
1290         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1291 }
1292
1293 function common_valid_tag($tag) {
1294         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1295                 return (Validate::email($matches[1]) ||
1296                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1297         }
1298         return false;
1299 }
1300
1301 # Does a little before-after block for next/prev page
1302
1303 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1304
1305         if ($have_before || $have_after) {
1306                 common_element_start('div', array('id' => 'pagination'));
1307                 common_element_start('ul', array('id' => 'nav_pagination'));
1308         }
1309
1310         if ($have_before) {
1311                 $pargs = array('page' => $page-1);
1312                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1313
1314                 common_element_start('li', 'before');
1315                 common_element('a', array('href' => common_local_url($action, $newargs)),
1316                                            _('« After'));
1317                 common_element_end('li');
1318         }
1319
1320         if ($have_after) {
1321                 $pargs = array('page' => $page+1);
1322                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1323                 common_element_start('li', 'after');
1324                 common_element('a', array('href' => common_local_url($action, $newargs)),
1325                                                    _('Before »'));
1326                 common_element_end('li');
1327         }
1328
1329         if ($have_before || $have_after) {
1330                 common_element_end('ul');
1331                 common_element_end('div');
1332         }
1333 }
1334
1335 /* Following functions are copied from MediaWiki GlobalFunctions.php
1336  * and written by Evan Prodromou. */
1337
1338 function common_accept_to_prefs($accept, $def = '*/*') {
1339         # No arg means accept anything (per HTTP spec)
1340         if(!$accept) {
1341                 return array($def => 1);
1342         }
1343
1344         $prefs = array();
1345
1346         $parts = explode(',', $accept);
1347
1348         foreach($parts as $part) {
1349                 # FIXME: doesn't deal with params like 'text/html; level=1'
1350                 @list($value, $qpart) = explode(';', $part);
1351                 $match = array();
1352                 if(!isset($qpart)) {
1353                         $prefs[$value] = 1;
1354                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1355                         $prefs[$value] = $match[1];
1356                 }
1357         }
1358
1359         return $prefs;
1360 }
1361
1362 function common_mime_type_match($type, $avail) {
1363         if(array_key_exists($type, $avail)) {
1364                 return $type;
1365         } else {
1366                 $parts = explode('/', $type);
1367                 if(array_key_exists($parts[0] . '/*', $avail)) {
1368                         return $parts[0] . '/*';
1369                 } elseif(array_key_exists('*/*', $avail)) {
1370                         return '*/*';
1371                 } else {
1372                         return NULL;
1373                 }
1374         }
1375 }
1376
1377 function common_negotiate_type($cprefs, $sprefs) {
1378         $combine = array();
1379
1380         foreach(array_keys($sprefs) as $type) {
1381                 $parts = explode('/', $type);
1382                 if($parts[1] != '*') {
1383                         $ckey = common_mime_type_match($type, $cprefs);
1384                         if($ckey) {
1385                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1386                         }
1387                 }
1388         }
1389
1390         foreach(array_keys($cprefs) as $type) {
1391                 $parts = explode('/', $type);
1392                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1393                         $skey = common_mime_type_match($type, $sprefs);
1394                         if($skey) {
1395                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1396                         }
1397                 }
1398         }
1399
1400         $bestq = 0;
1401         $besttype = "text/html";
1402
1403         foreach(array_keys($combine) as $type) {
1404                 if($combine[$type] > $bestq) {
1405                         $besttype = $type;
1406                         $bestq = $combine[$type];
1407                 }
1408         }
1409
1410         return $besttype;
1411 }
1412
1413 function common_config($main, $sub) {
1414         global $config;
1415         return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1416 }
1417
1418 function common_copy_args($from) {
1419         $to = array();
1420         $strip = get_magic_quotes_gpc();
1421         foreach ($from as $k => $v) {
1422                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1423         }
1424         return $to;
1425 }
1426
1427 function common_user_uri(&$user) {
1428         return common_local_url('userbyid', array('id' => $user->id));
1429 }
1430
1431 function common_notice_uri(&$notice) {
1432         return common_local_url('shownotice',
1433                 array('notice' => $notice->id));
1434 }
1435
1436 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1437
1438 function common_confirmation_code($bits) {
1439         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1440         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1441         $chars = ceil($bits/5);
1442         $code = '';
1443         for ($i = 0; $i < $chars; $i++) {
1444                 # XXX: convert to string and back
1445                 $num = hexdec(common_good_rand(1));
1446                 # XXX: randomness is too precious to throw away almost
1447                 # 40% of the bits we get!
1448                 $code .= $codechars[$num%32];
1449         }
1450         return $code;
1451 }
1452
1453 # convert markup to HTML
1454
1455 function common_markup_to_html($c) {
1456         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1457         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1458         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1459         return Markdown($c);
1460 }
1461
1462 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1463         $avatar = $profile->getAvatar($size);
1464         if ($avatar) {
1465                 return common_avatar_display_url($avatar);
1466         } else {
1467                 return common_default_avatar($size);
1468         }
1469 }
1470
1471 function common_profile_uri($profile) {
1472         if (!$profile) {
1473                 return NULL;
1474         }
1475         $user = User::staticGet($profile->id);
1476         if ($user) {
1477                 return $user->uri;
1478         }
1479
1480         $remote = Remote_profile::staticGet($profile->id);
1481         if ($remote) {
1482                 return $remote->uri;
1483         }
1484         # XXX: this is a very bad profile!
1485         return NULL;
1486 }
1487
1488 function common_canonical_sms($sms) {
1489         # strip non-digits
1490         preg_replace('/\D/', '', $sms);
1491         return $sms;
1492 }
1493
1494 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1495     switch ($errno) {
1496      case E_USER_ERROR:
1497                 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1498                 exit(1);
1499                 break;
1500
1501          case E_USER_WARNING:
1502                 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1503                 break;
1504
1505      case E_USER_NOTICE:
1506                 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1507                 break;
1508     }
1509
1510         # FIXME: show error page if we're on the Web
1511     /* Don't execute PHP internal error handler */
1512     return true;
1513 }
1514
1515 function common_session_token() {
1516         common_ensure_session();
1517         if (!array_key_exists('token', $_SESSION)) {
1518                 $_SESSION['token'] = common_good_rand(64);
1519         }
1520         return $_SESSION['token'];
1521 }