]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
b0edb8ef041cf2f92760ab86b0563ca6bbac2643
[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         
1114         if ($flink->noticesync == 1) {
1115                 if (!common_twitter_broadcast($notice, $flink)) {
1116                         common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1117                 }
1118         }
1119         
1120         if (common_config('queue', 'enabled')) {
1121                 # Do it later!
1122                 return common_enqueue_notice($notice);
1123         } else {
1124                 return common_real_broadcast($notice, $remote);
1125         }
1126 }
1127
1128 function common_twitter_broadcast($notice, $flink) {    
1129         global $config;
1130         $success = true;
1131         $fuser = $flink->getForeignUser();
1132         $twitter_user = $fuser->nickname;
1133         $twitter_password = $flink->credentials;
1134         $uri = 'http://www.twitter.com/statuses/update.json';
1135         
1136         // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1137         $statustxt = preg_replace('/^@/', ' @', $notice->content);
1138         
1139         $options = array(
1140                 CURLOPT_USERPWD                 => "$twitter_user:$twitter_password",
1141                 CURLOPT_POST                    => true,
1142                 CURLOPT_POSTFIELDS              => array(
1143                                                                         'status'        => $statustxt,
1144                                                                         'source'        => $config['integration']['source']
1145                                                                         ),
1146                 CURLOPT_RETURNTRANSFER  => true,
1147                 CURLOPT_FAILONERROR             => true,
1148                 CURLOPT_HEADER                  => false,
1149                 CURLOPT_FOLLOWLOCATION  => true,
1150                 CURLOPT_USERAGENT               => "Laconica",
1151                 CURLOPT_CONNECTTIMEOUT  => 120,  // XXX: Scary!!!! How long should this be?
1152                 CURLOPT_TIMEOUT                 => 120
1153         );
1154         
1155         $ch = curl_init($uri);
1156     curl_setopt_array($ch, $options);
1157     $data = curl_exec($ch);
1158     $errmsg = curl_error($ch);
1159
1160         if ($errmsg) {
1161                 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", 
1162                         __FILE__);
1163                 $success = false;
1164         }
1165
1166         curl_close($ch);
1167         
1168         if (!$data) {
1169                 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1170                         __FILE__);
1171                 $success = false;
1172         }
1173
1174         // Twitter should return a status       
1175         $status = json_decode($data);
1176
1177         if (!$status->id) {
1178                 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1179                         __FILE__);
1180                 $success = false;
1181         }
1182         
1183         return $status;
1184 }
1185
1186 # Stick the notice on the queue
1187
1188 function common_enqueue_notice($notice) {
1189         foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1190                 $qi = new Queue_item();
1191                 $qi->notice_id = $notice->id;
1192                 $qi->transport = $transport;
1193                 $qi->created = $notice->created;
1194         $result = $qi->insert();
1195                 if (!$result) {
1196                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1197                         common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1198                         return false;
1199                 }
1200                 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1201         }
1202         return $result;
1203 }
1204
1205 function common_dequeue_notice($notice) {
1206         $qi = Queue_item::staticGet($notice->id);
1207         if ($qi) {
1208                 $result = $qi->delete();
1209                 if (!$result) {
1210                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1211                     common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1212                     return false;
1213                 }
1214                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1215                 return $result;
1216         } else {
1217             return false;
1218         }
1219 }
1220
1221 function common_real_broadcast($notice, $remote=false) {
1222         $success = true;
1223         if (!$remote) {
1224                 # Make sure we have the OMB stuff
1225                 require_once(INSTALLDIR.'/lib/omb.php');
1226                 $success = omb_broadcast_remote_subscribers($notice);
1227                 if (!$success) {
1228                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1229                 }
1230         }
1231         if ($success) {
1232                 require_once(INSTALLDIR.'/lib/jabber.php');
1233                 $success = jabber_broadcast_notice($notice);
1234                 if (!$success) {
1235                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1236                 }
1237         }
1238         if ($success) {
1239                 require_once(INSTALLDIR.'/lib/mail.php');
1240                 $success = mail_broadcast_notice_sms($notice);
1241                 if (!$success) {
1242                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1243                 }
1244         }
1245         if ($success) {
1246                 $success = jabber_public_notice($notice);
1247                 if (!$success) {
1248                         common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1249                 }
1250         }
1251         // XXX: broadcast notices to other IM
1252         return $success;
1253 }
1254
1255 function common_broadcast_profile($profile) {
1256         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1257         require_once(INSTALLDIR.'/lib/omb.php');
1258         omb_broadcast_profile($profile);
1259         // XXX: Other broadcasts...?
1260         return true;
1261 }
1262
1263 function common_profile_url($nickname) {
1264         return common_local_url('showstream', array('nickname' => $nickname));
1265 }
1266
1267 # Don't call if nobody's logged in
1268
1269 function common_notice_form($action=NULL, $content=NULL) {
1270         $user = common_current_user();
1271         assert(!is_null($user));
1272         common_element_start('form', array('id' => 'status_form',
1273                                                                            'method' => 'post',
1274                                                                            'action' => common_local_url('newnotice')));
1275         common_element_start('p');
1276         common_element('label', array('for' => 'status_textarea',
1277                                                                   'id' => 'status_label'),
1278                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1279         common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1280         common_element('textarea', array('id' => 'status_textarea',
1281                                                                          'cols' => 60,
1282                                                                          'rows' => 3,
1283                                                                          'name' => 'status_textarea'),
1284                                    ($content) ? $content : '');
1285         if ($action) {
1286                 common_hidden('returnto', $action);
1287         }
1288         common_element('input', array('id' => 'status_submit',
1289                                                                   'name' => 'status_submit',
1290                                                                   'type' => 'submit',
1291                                                                   'value' => _('Send')));
1292         common_element_end('p');
1293         common_element_end('form');
1294 }
1295
1296 # Should make up a reasonable root URL
1297
1298 function common_root_url() {
1299         return common_path('');
1300 }
1301
1302 # returns $bytes bytes of random data as a hexadecimal string
1303 # "good" here is a goal and not a guarantee
1304
1305 function common_good_rand($bytes) {
1306         # XXX: use random.org...?
1307         if (file_exists('/dev/urandom')) {
1308                 return common_urandom($bytes);
1309         } else { # FIXME: this is probably not good enough
1310                 return common_mtrand($bytes);
1311         }
1312 }
1313
1314 function common_urandom($bytes) {
1315         $h = fopen('/dev/urandom', 'rb');
1316         # should not block
1317         $src = fread($h, $bytes);
1318         fclose($h);
1319         $enc = '';
1320         for ($i = 0; $i < $bytes; $i++) {
1321                 $enc .= sprintf("%02x", (ord($src[$i])));
1322         }
1323         return $enc;
1324 }
1325
1326 function common_mtrand($bytes) {
1327         $enc = '';
1328         for ($i = 0; $i < $bytes; $i++) {
1329                 $enc .= sprintf("%02x", mt_rand(0, 255));
1330         }
1331         return $enc;
1332 }
1333
1334 function common_set_returnto($url) {
1335         common_ensure_session();
1336         $_SESSION['returnto'] = $url;
1337 }
1338
1339 function common_get_returnto() {
1340         common_ensure_session();
1341         return $_SESSION['returnto'];
1342 }
1343
1344 function common_timestamp() {
1345         return date('YmdHis');
1346 }
1347
1348 function common_ensure_syslog() {
1349         static $initialized = false;
1350         if (!$initialized) {
1351                 global $config;
1352                 openlog($config['syslog']['appname'], 0, LOG_USER);
1353                 $initialized = true;
1354         }
1355 }
1356
1357 function common_log($priority, $msg, $filename=NULL) {
1358         $logfile = common_config('site', 'logfile');
1359         if ($logfile) {
1360                 $log = fopen($logfile, "a");
1361                 if ($log) {
1362                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1363                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1364                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1365                         fwrite($log, $output);
1366                         fclose($log);
1367                 }
1368         } else {
1369                 common_ensure_syslog();
1370                 syslog($priority, $msg);
1371         }
1372 }
1373
1374 function common_debug($msg, $filename=NULL) {
1375         if ($filename) {
1376                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1377         } else {
1378                 common_log(LOG_DEBUG, $msg);
1379         }
1380 }
1381
1382 function common_log_db_error(&$object, $verb, $filename=NULL) {
1383         $objstr = common_log_objstring($object);
1384         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1385         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1386 }
1387
1388 function common_log_objstring(&$object) {
1389         if (is_null($object)) {
1390                 return "NULL";
1391         }
1392         $arr = $object->toArray();
1393         $fields = array();
1394         foreach ($arr as $k => $v) {
1395                 $fields[] = "$k='$v'";
1396         }
1397         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1398         return $objstring;
1399 }
1400
1401 function common_valid_http_url($url) {
1402         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1403 }
1404
1405 function common_valid_tag($tag) {
1406         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1407                 return (Validate::email($matches[1]) ||
1408                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1409         }
1410         return false;
1411 }
1412
1413 # Does a little before-after block for next/prev page
1414
1415 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1416
1417         if ($have_before || $have_after) {
1418                 common_element_start('div', array('id' => 'pagination'));
1419                 common_element_start('ul', array('id' => 'nav_pagination'));
1420         }
1421
1422         if ($have_before) {
1423                 $pargs = array('page' => $page-1);
1424                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1425
1426                 common_element_start('li', 'before');
1427                 common_element('a', array('href' => common_local_url($action, $newargs)),
1428                                            _('« After'));
1429                 common_element_end('li');
1430         }
1431
1432         if ($have_after) {
1433                 $pargs = array('page' => $page+1);
1434                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1435                 common_element_start('li', 'after');
1436                 common_element('a', array('href' => common_local_url($action, $newargs)),
1437                                                    _('Before »'));
1438                 common_element_end('li');
1439         }
1440
1441         if ($have_before || $have_after) {
1442                 common_element_end('ul');
1443                 common_element_end('div');
1444         }
1445 }
1446
1447 /* Following functions are copied from MediaWiki GlobalFunctions.php
1448  * and written by Evan Prodromou. */
1449
1450 function common_accept_to_prefs($accept, $def = '*/*') {
1451         # No arg means accept anything (per HTTP spec)
1452         if(!$accept) {
1453                 return array($def => 1);
1454         }
1455
1456         $prefs = array();
1457
1458         $parts = explode(',', $accept);
1459
1460         foreach($parts as $part) {
1461                 # FIXME: doesn't deal with params like 'text/html; level=1'
1462                 @list($value, $qpart) = explode(';', $part);
1463                 $match = array();
1464                 if(!isset($qpart)) {
1465                         $prefs[$value] = 1;
1466                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1467                         $prefs[$value] = $match[1];
1468                 }
1469         }
1470
1471         return $prefs;
1472 }
1473
1474 function common_mime_type_match($type, $avail) {
1475         if(array_key_exists($type, $avail)) {
1476                 return $type;
1477         } else {
1478                 $parts = explode('/', $type);
1479                 if(array_key_exists($parts[0] . '/*', $avail)) {
1480                         return $parts[0] . '/*';
1481                 } elseif(array_key_exists('*/*', $avail)) {
1482                         return '*/*';
1483                 } else {
1484                         return NULL;
1485                 }
1486         }
1487 }
1488
1489 function common_negotiate_type($cprefs, $sprefs) {
1490         $combine = array();
1491
1492         foreach(array_keys($sprefs) as $type) {
1493                 $parts = explode('/', $type);
1494                 if($parts[1] != '*') {
1495                         $ckey = common_mime_type_match($type, $cprefs);
1496                         if($ckey) {
1497                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1498                         }
1499                 }
1500         }
1501
1502         foreach(array_keys($cprefs) as $type) {
1503                 $parts = explode('/', $type);
1504                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1505                         $skey = common_mime_type_match($type, $sprefs);
1506                         if($skey) {
1507                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1508                         }
1509                 }
1510         }
1511
1512         $bestq = 0;
1513         $besttype = "text/html";
1514
1515         foreach(array_keys($combine) as $type) {
1516                 if($combine[$type] > $bestq) {
1517                         $besttype = $type;
1518                         $bestq = $combine[$type];
1519                 }
1520         }
1521
1522         return $besttype;
1523 }
1524
1525 function common_config($main, $sub) {
1526         global $config;
1527         return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1528 }
1529
1530 function common_copy_args($from) {
1531         $to = array();
1532         $strip = get_magic_quotes_gpc();
1533         foreach ($from as $k => $v) {
1534                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1535         }
1536         return $to;
1537 }
1538
1539 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1540 // This is used before handing a request off to OAuthRequest::from_request.
1541 function common_remove_magic_from_request() {
1542         if(get_magic_quotes_gpc()) {
1543                 $_POST=array_map('stripslashes',$_POST);
1544                 $_GET=array_map('stripslashes',$_GET);
1545         }
1546 }
1547
1548 function common_user_uri(&$user) {
1549         return common_local_url('userbyid', array('id' => $user->id));
1550 }
1551
1552 function common_notice_uri(&$notice) {
1553         return common_local_url('shownotice',
1554                 array('notice' => $notice->id));
1555 }
1556
1557 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1558
1559 function common_confirmation_code($bits) {
1560         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1561         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1562         $chars = ceil($bits/5);
1563         $code = '';
1564         for ($i = 0; $i < $chars; $i++) {
1565                 # XXX: convert to string and back
1566                 $num = hexdec(common_good_rand(1));
1567                 # XXX: randomness is too precious to throw away almost
1568                 # 40% of the bits we get!
1569                 $code .= $codechars[$num%32];
1570         }
1571         return $code;
1572 }
1573
1574 # convert markup to HTML
1575
1576 function common_markup_to_html($c) {
1577         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1578         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1579         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1580         return Markdown($c);
1581 }
1582
1583 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1584         $avatar = $profile->getAvatar($size);
1585         if ($avatar) {
1586                 return common_avatar_display_url($avatar);
1587         } else {
1588                 return common_default_avatar($size);
1589         }
1590 }
1591
1592 function common_profile_uri($profile) {
1593         if (!$profile) {
1594                 return NULL;
1595         }
1596         $user = User::staticGet($profile->id);
1597         if ($user) {
1598                 return $user->uri;
1599         }
1600
1601         $remote = Remote_profile::staticGet($profile->id);
1602         if ($remote) {
1603                 return $remote->uri;
1604         }
1605         # XXX: this is a very bad profile!
1606         return NULL;
1607 }
1608
1609 function common_canonical_sms($sms) {
1610         # strip non-digits
1611         preg_replace('/\D/', '', $sms);
1612         return $sms;
1613 }
1614
1615 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1616     switch ($errno) {
1617      case E_USER_ERROR:
1618                 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1619                 exit(1);
1620                 break;
1621
1622          case E_USER_WARNING:
1623                 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1624                 break;
1625
1626      case E_USER_NOTICE:
1627                 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1628                 break;
1629     }
1630
1631         # FIXME: show error page if we're on the Web
1632     /* Don't execute PHP internal error handler */
1633     return true;
1634 }
1635
1636 function common_session_token() {
1637         common_ensure_session();
1638         if (!array_key_exists('token', $_SESSION)) {
1639                 $_SESSION['token'] = common_good_rand(64);
1640         }
1641         return $_SESSION['token'];
1642 }
1643
1644 function common_disfavor_form($notice) {
1645         common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1646                                                                            'method' => 'post',
1647                                                                            'class' => 'disfavor',
1648                                                                            'action' => common_local_url('disfavor')));
1649         common_hidden('token', common_session_token());
1650         common_hidden('notice', $notice->id);
1651         common_element('input', array('type' => 'submit',
1652                                                                   'id' => 'disfavor-submit-' . $notice->id,
1653                                                                   'name' => 'disfavor-submit-' . $notice->id,
1654                                                                   'class' => 'disfavor',
1655                                                                   'value' => '♥'));
1656         common_element_end('form');
1657 }
1658
1659 function common_favor_form($notice) {
1660         common_element_start('form', array('id' => 'favor-' . $notice->id,
1661                                                                            'method' => 'post',
1662                                                                            'class' => 'favor',
1663                                                                            'action' => common_local_url('favor')));
1664         common_hidden('token', common_session_token());
1665         common_hidden('notice', $notice->id);
1666         common_element('input', array('type' => 'submit',
1667                                                                   'id' => 'favor-submit-' . $notice->id,
1668                                                                   'name' => 'favor-submit-' . $notice->id,
1669                                                                   'class' => 'favor',
1670                                                                   'value' => '♡'));
1671         common_element_end('form');
1672 }
1673
1674 function common_cache_key($extra) {
1675         return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1676 }
1677
1678 function common_keyize($str) {
1679         $str = strtolower($str);
1680         $str = preg_replace('/\s/', '_', $str);
1681         return $str;
1682 }