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