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