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