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