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