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