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