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