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