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