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