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