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