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