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