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