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