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