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