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