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