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