]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
don't save replies from a blocked profile to the blocking user
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
21
22 # Show a server error
23
24 function common_server_error($msg, $code=500) {
25         static $status = array(500 => 'Internal Server Error',
26                                                    501 => 'Not Implemented',
27                                                    502 => 'Bad Gateway',
28                                                    503 => 'Service Unavailable',
29                                                    504 => 'Gateway Timeout',
30                                                    505 => 'HTTP Version Not Supported');
31
32         if (!array_key_exists($code, $status)) {
33                 $code = 500;
34         }
35
36         $status_string = $status[$code];
37
38         header('HTTP/1.1 '.$code.' '.$status_string);
39         header('Content-type: text/plain');
40
41         print $msg;
42         print "\n";
43         exit();
44 }
45
46 # Show a user error
47 function common_user_error($msg, $code=400) {
48         static $status = array(400 => 'Bad Request',
49                                                    401 => 'Unauthorized',
50                                                    402 => 'Payment Required',
51                                                    403 => 'Forbidden',
52                                                    404 => 'Not Found',
53                                                    405 => 'Method Not Allowed',
54                                                    406 => 'Not Acceptable',
55                                                    407 => 'Proxy Authentication Required',
56                                                    408 => 'Request Timeout',
57                                                    409 => 'Conflict',
58                                                    410 => 'Gone',
59                                                    411 => 'Length Required',
60                                                    412 => 'Precondition Failed',
61                                                    413 => 'Request Entity Too Large',
62                                                    414 => 'Request-URI Too Long',
63                                                    415 => 'Unsupported Media Type',
64                                                    416 => 'Requested Range Not Satisfiable',
65                                                    417 => 'Expectation Failed');
66
67         if (!array_key_exists($code, $status)) {
68                 $code = 400;
69         }
70
71         $status_string = $status[$code];
72
73         header('HTTP/1.1 '.$code.' '.$status_string);
74
75         common_show_header('Error');
76         common_element('div', array('class' => 'error'), $msg);
77         common_show_footer();
78 }
79
80 $xw = null;
81
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
84         global $xw;
85         $xw->startElement($tag);
86         if (is_array($attrs)) {
87                 foreach ($attrs as $name => $value) {
88                         $xw->writeAttribute($name, $value);
89                 }
90         } else if (is_string($attrs)) {
91                 $xw->writeAttribute('class', $attrs);
92         }
93 }
94
95 function common_element_end($tag) {
96         static $empty_tag = array('base', 'meta', 'link', 'hr',
97                                                           'br', 'param', 'img', 'area',
98                                                           'input', 'col');
99         global $xw;
100         # XXX: check namespace
101         if (in_array($tag, $empty_tag)) {
102                 $xw->endElement();
103         } else {
104                 $xw->fullEndElement();
105         }
106 }
107
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109         common_element_start($tag, $attrs);
110         global $xw;
111         if (!is_null($content)) {
112                 $xw->text($content);
113         }
114         common_element_end($tag);
115 }
116
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL, $indent=true) {
118         global $xw;
119         $xw = new XMLWriter();
120         $xw->openURI('php://output');
121         $xw->setIndent($indent);
122         $xw->startDocument('1.0', 'UTF-8');
123         if ($doc) {
124                 $xw->writeDTD($doc, $public, $system);
125         }
126 }
127
128 function common_end_xml() {
129         global $xw;
130         $xw->endDocument();
131         $xw->flush();
132 }
133
134 function common_init_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 '<span class="vcard"><a class="fn nickname url" rel="reply" href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a></span>';
940         } else {
941                 return '<span class="vcard"> <span class="fn nickname">'.$nickname.'</span> </span>';
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 'login':
1085          case 'logout':
1086          case 'subscribe':
1087          case 'unsubscribe':
1088          case 'invite':
1089                 return common_path('main/'.$action);
1090          case 'tagother':
1091                 return common_path('main/tagother?id='.$args['id']);
1092          case 'register':
1093                 if ($args && $args['code']) {
1094                         return common_path('main/register/'.$args['code']);
1095                 } else {
1096                         return common_path('main/register');
1097                 }
1098          case 'remotesubscribe':
1099                 if ($args && $args['nickname']) {
1100                         return common_path('main/remote?nickname=' . $args['nickname']);
1101                 } else {
1102                         return common_path('main/remote');
1103                 }
1104          case 'nudge':
1105                 return common_path($args['nickname'].'/nudge');
1106          case 'openidlogin':
1107                 return common_path('main/openid');
1108          case 'profilesettings':
1109                 return common_path('settings/profile');
1110          case 'emailsettings':
1111                 return common_path('settings/email');
1112          case 'openidsettings':
1113                 return common_path('settings/openid');
1114          case 'smssettings':
1115                 return common_path('settings/sms');
1116          case 'twittersettings':
1117                 return common_path('settings/twitter');
1118          case 'othersettings':
1119                 return common_path('settings/other');
1120      case 'deleteprofile':
1121         return common_path('settings/delete');
1122          case 'newnotice':
1123                 if ($args && $args['replyto']) {
1124                         return common_path('notice/new?replyto='.$args['replyto']);
1125                 } else {
1126                         return common_path('notice/new');
1127                 }
1128          case 'shownotice':
1129                 return common_path('notice/'.$args['notice']);
1130          case 'deletenotice':
1131                 if ($args && $args['notice']) {
1132                         return common_path('notice/delete/'.$args['notice']);
1133                 } else {
1134                         return common_path('notice/delete');
1135                 }
1136          case 'microsummary':
1137          case 'xrds':
1138          case 'foaf':
1139                 return common_path($args['nickname'].'/'.$action);
1140          case 'all':
1141          case 'replies':
1142          case 'inbox':
1143          case 'outbox':
1144                 if ($args && isset($args['page'])) {
1145                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1146                 } else {
1147                         return common_path($args['nickname'].'/'.$action);
1148                 }
1149          case 'subscriptions':
1150          case 'subscribers':
1151                 $nickname = $args['nickname'];
1152                 unset($args['nickname']);
1153                 if (isset($args['tag'])) {
1154                         $tag = $args['tag'];
1155                         unset($args['tag']);
1156                 }
1157                 $params = http_build_query($args);
1158                 if ($params) {
1159                         return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1160                 } else {
1161                         return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1162                 }
1163          case 'allrss':
1164                 return common_path($args['nickname'].'/all/rss');
1165          case 'repliesrss':
1166                 return common_path($args['nickname'].'/replies/rss');
1167          case 'userrss':
1168         if (isset($args['limit']))
1169                     return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1170                 return common_path($args['nickname'].'/rss');
1171          case 'showstream':
1172                 if ($args && isset($args['page'])) {
1173                         return common_path($args['nickname'].'?page=' . $args['page']);
1174                 } else {
1175                         return common_path($args['nickname']);
1176                 }
1177
1178          case 'usertimeline':
1179                 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1180          case 'confirmaddress':
1181                 return common_path('main/confirmaddress/'.$args['code']);
1182          case 'userbyid':
1183                 return common_path('user/'.$args['id']);
1184          case 'recoverpassword':
1185             $path = 'main/recoverpassword';
1186             if ($args['code']) {
1187                 $path .= '/' . $args['code'];
1188                 }
1189             return common_path($path);
1190          case 'imsettings':
1191                 return common_path('settings/im');
1192          case 'peoplesearch':
1193                 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1194          case 'noticesearch':
1195                 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1196          case 'noticesearchrss':
1197                 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1198          case 'avatarbynickname':
1199                 return common_path($args['nickname'].'/avatar/'.$args['size']);
1200          case 'tag':
1201             if (isset($args['tag']) && $args['tag']) {
1202                         $path = 'tag/' . $args['tag'];
1203                         unset($args['tag']);
1204                 } else {
1205                         $path = 'tags';
1206                 }
1207                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1208          case 'peopletag':
1209                 $path = 'peopletag/' . $args['tag'];
1210                 unset($args['tag']);
1211                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1212          case 'tags':
1213                 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1214          case 'favor':
1215                 return common_path('main/favor');
1216          case 'disfavor':
1217                 return common_path('main/disfavor');
1218          case 'showfavorites':
1219                 if ($args && isset($args['page'])) {
1220                         return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1221                 } else {
1222                         return common_path($args['nickname'].'/favorites');
1223                 }
1224          case 'favoritesrss':
1225                 return common_path($args['nickname'].'/favorites/rss');
1226          case 'showmessage':
1227                 return common_path('message/' . $args['message']);
1228          case 'newmessage':
1229                 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1230          case 'api':
1231                 # XXX: do fancy URLs for all the API methods
1232                 switch (strtolower($args['apiaction'])) {
1233                  case 'statuses':
1234                         switch (strtolower($args['method'])) {
1235                          case 'user_timeline.rss':
1236                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1237                          case 'user_timeline.atom':
1238                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1239                          case 'user_timeline.json':
1240                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1241                          case 'user_timeline.xml':
1242                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1243                          default: return common_simple_url($action, $args);
1244                         }
1245                  default: return common_simple_url($action, $args);
1246                 }
1247          case 'sup':
1248                 if ($args && isset($args['seconds'])) {
1249                         return common_path('main/sup?seconds='.$args['seconds']);
1250                 } else {
1251                         return common_path('main/sup');
1252                 }
1253          default:
1254                 return common_simple_url($action, $args);
1255         }
1256 }
1257
1258 function common_simple_url($action, $args=NULL) {
1259         global $config;
1260         /* XXX: pretty URLs */
1261         $extra = '';
1262         if ($args) {
1263                 foreach ($args as $key => $value) {
1264                         $extra .= "&${key}=${value}";
1265                 }
1266         }
1267         return common_path("index.php?action=${action}${extra}");
1268 }
1269
1270 function common_path($relative) {
1271         global $config;
1272         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1273         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1274 }
1275
1276 function common_date_string($dt) {
1277         // XXX: do some sexy date formatting
1278         // return date(DATE_RFC822, $dt);
1279         $t = strtotime($dt);
1280         $now = time();
1281         $diff = $now - $t;
1282
1283         if ($now < $t) { # that shouldn't happen!
1284                 return common_exact_date($dt);
1285         } else if ($diff < 60) {
1286                 return _('a few seconds ago');
1287         } else if ($diff < 92) {
1288                 return _('about a minute ago');
1289         } else if ($diff < 3300) {
1290                 return sprintf(_('about %d minutes ago'), round($diff/60));
1291         } else if ($diff < 5400) {
1292                 return _('about an hour ago');
1293         } else if ($diff < 22 * 3600) {
1294                 return sprintf(_('about %d hours ago'), round($diff/3600));
1295         } else if ($diff < 37 * 3600) {
1296                 return _('about a day ago');
1297         } else if ($diff < 24 * 24 * 3600) {
1298                 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1299         } else if ($diff < 46 * 24 * 3600) {
1300                 return _('about a month ago');
1301         } else if ($diff < 330 * 24 * 3600) {
1302                 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1303         } else if ($diff < 480 * 24 * 3600) {
1304                 return _('about a year ago');
1305         } else {
1306                 return common_exact_date($dt);
1307         }
1308 }
1309
1310 function common_exact_date($dt) {
1311     static $_utc;
1312     static $_siteTz;
1313
1314     if (!$_utc) {
1315         $_utc = new DateTimeZone('UTC');
1316         $_siteTz = new DateTimeZone(common_timezone());
1317     }
1318
1319         $dateStr = date('d F Y H:i:s', strtotime($dt));
1320         $d = new DateTime($dateStr, $_utc);
1321         $d->setTimezone($_siteTz);
1322         return $d->format(DATE_RFC850);
1323 }
1324
1325 function common_date_w3dtf($dt) {
1326         $dateStr = date('d F Y H:i:s', strtotime($dt));
1327         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1328         $d->setTimezone(new DateTimeZone(common_timezone()));
1329         return $d->format(DATE_W3C);
1330 }
1331
1332 function common_date_rfc2822($dt) {
1333         $dateStr = date('d F Y H:i:s', strtotime($dt));
1334         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1335         $d->setTimezone(new DateTimeZone(common_timezone()));
1336         return $d->format('r');
1337 }
1338
1339 function common_date_iso8601($dt) {
1340         $dateStr = date('d F Y H:i:s', strtotime($dt));
1341         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1342         $d->setTimezone(new DateTimeZone(common_timezone()));
1343         return $d->format('c');
1344 }
1345
1346 function common_sql_now() {
1347         return strftime('%Y-%m-%d %H:%M:%S', time());
1348 }
1349
1350 function common_redirect($url, $code=307) {
1351         static $status = array(301 => "Moved Permanently",
1352                                                    302 => "Found",
1353                                                    303 => "See Other",
1354                                                    307 => "Temporary Redirect");
1355         header("Status: ${code} $status[$code]");
1356         header("Location: $url");
1357
1358         common_start_xml('a',
1359                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
1360                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1361         common_element('a', array('href' => $url), $url);
1362         common_end_xml();
1363     exit;
1364 }
1365
1366 function common_save_replies($notice) {
1367         # Alternative reply format
1368         $tname = false;
1369         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1370                 $tname = $match[1];
1371         }
1372         # extract all @messages
1373         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1374
1375         $names = array();
1376
1377         if ($cnt || $tname) {
1378                 # XXX: is there another way to make an array copy?
1379                 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1380         }
1381
1382         $sender = Profile::staticGet($notice->profile_id);
1383
1384         $replied = array();
1385
1386         # store replied only for first @ (what user/notice what the reply directed,
1387         # we assume first @ is it)
1388
1389         for ($i=0; $i<count($names); $i++) {
1390                 $nickname = $names[$i];
1391                 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1392                 if (!$recipient) {
1393                         continue;
1394                 }
1395                 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1396                         $reply_for = $recipient;
1397                         $recipient_notice = $reply_for->getCurrentNotice();
1398                         if ($recipient_notice) {
1399                                 $orig = clone($notice);
1400                                 $notice->reply_to = $recipient_notice->id;
1401                                 $notice->update($orig);
1402                         }
1403                 }
1404         # Don't save replies from blocked profile to local user
1405         $recipient_user = User::staticGet('id', $recipient->id);
1406         if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1407             continue;
1408         }
1409                 $reply = new Reply();
1410                 $reply->notice_id = $notice->id;
1411                 $reply->profile_id = $recipient->id;
1412                 $id = $reply->insert();
1413                 if (!$id) {
1414                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1415                         common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1416                         common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1417                         return;
1418                 } else {
1419                         $replied[$recipient->id] = 1;
1420                 }
1421         }
1422
1423         # Hash format replies, too
1424         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1425         if ($cnt) {
1426                 foreach ($match[1] as $tag) {
1427                         $tagged = Profile_tag::getTagged($sender->id, $tag);
1428                         foreach ($tagged as $t) {
1429                                 if (!$replied[$t->id]) {
1430                     # Don't save replies from blocked profile to local user
1431                     $t_user = User::staticGet('id', $t->id);
1432                     if ($t_user && $t_user->hasBlocked($sender)) {
1433                         continue;
1434                     }
1435                                         $reply = new Reply();
1436                                         $reply->notice_id = $notice->id;
1437                                         $reply->profile_id = $t->id;
1438                                         $id = $reply->insert();
1439                                         if (!$id) {
1440                                                 common_log_db_error($reply, 'INSERT', __FILE__);
1441                                                 return;
1442                                         }
1443                                 }
1444                         }
1445                 }
1446         }
1447 }
1448
1449 function common_broadcast_notice($notice, $remote=false) {
1450
1451         // Check to see if notice should go to Twitter
1452         $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1453         if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1454
1455                 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1456
1457                 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1458                         (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1459
1460                         $result = common_twitter_broadcast($notice, $flink);
1461
1462                         if (!$result) {
1463                                 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1464                         }
1465                 }
1466         }
1467
1468         if (common_config('queue', 'enabled')) {
1469                 # Do it later!
1470                 return common_enqueue_notice($notice);
1471         } else {
1472                 return common_real_broadcast($notice, $remote);
1473         }
1474 }
1475
1476 function common_twitter_broadcast($notice, $flink) {
1477         global $config;
1478         $success = true;
1479         $fuser = $flink->getForeignUser();
1480         $twitter_user = $fuser->nickname;
1481         $twitter_password = $flink->credentials;
1482         $uri = 'http://www.twitter.com/statuses/update.json';
1483
1484         // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1485         $statustxt = preg_replace('/^@/', ' @', $notice->content);
1486
1487         $options = array(
1488                 CURLOPT_USERPWD                 => "$twitter_user:$twitter_password",
1489                 CURLOPT_POST                    => true,
1490                 CURLOPT_POSTFIELDS              => array(
1491                                                                         'status'        => $statustxt,
1492                                                                         'source'        => $config['integration']['source']
1493                                                                         ),
1494                 CURLOPT_RETURNTRANSFER  => true,
1495                 CURLOPT_FAILONERROR             => true,
1496                 CURLOPT_HEADER                  => false,
1497                 CURLOPT_FOLLOWLOCATION  => true,
1498                 CURLOPT_USERAGENT               => "Laconica",
1499                 CURLOPT_CONNECTTIMEOUT  => 120,  // XXX: Scary!!!! How long should this be?
1500                 CURLOPT_TIMEOUT                 => 120
1501         );
1502
1503         $ch = curl_init($uri);
1504     curl_setopt_array($ch, $options);
1505     $data = curl_exec($ch);
1506     $errmsg = curl_error($ch);
1507
1508         if ($errmsg) {
1509                 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1510                         __FILE__);
1511                 $success = false;
1512         }
1513
1514         curl_close($ch);
1515
1516         if (!$data) {
1517                 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1518                         __FILE__);
1519                 $success = false;
1520         }
1521
1522         // Twitter should return a status
1523         $status = json_decode($data);
1524
1525         if (!$status->id) {
1526                 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1527                         __FILE__);
1528                 $success = false;
1529         }
1530
1531         return $success;
1532 }
1533
1534 # Stick the notice on the queue
1535
1536 function common_enqueue_notice($notice) {
1537         foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1538                 $qi = new Queue_item();
1539                 $qi->notice_id = $notice->id;
1540                 $qi->transport = $transport;
1541                 $qi->created = $notice->created;
1542         $result = $qi->insert();
1543                 if (!$result) {
1544                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1545                         common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1546                         return false;
1547                 }
1548                 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1549         }
1550         return $result;
1551 }
1552
1553 function common_dequeue_notice($notice) {
1554         $qi = Queue_item::staticGet($notice->id);
1555         if ($qi) {
1556                 $result = $qi->delete();
1557                 if (!$result) {
1558                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1559                     common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1560                     return false;
1561                 }
1562                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1563                 return $result;
1564         } else {
1565             return false;
1566         }
1567 }
1568
1569 function common_real_broadcast($notice, $remote=false) {
1570         $success = true;
1571         if (!$remote) {
1572                 # Make sure we have the OMB stuff
1573                 require_once(INSTALLDIR.'/lib/omb.php');
1574                 $success = omb_broadcast_remote_subscribers($notice);
1575                 if (!$success) {
1576                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1577                 }
1578         }
1579         if ($success) {
1580                 require_once(INSTALLDIR.'/lib/jabber.php');
1581                 $success = jabber_broadcast_notice($notice);
1582                 if (!$success) {
1583                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1584                 }
1585         }
1586         if ($success) {
1587                 require_once(INSTALLDIR.'/lib/mail.php');
1588                 $success = mail_broadcast_notice_sms($notice);
1589                 if (!$success) {
1590                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1591                 }
1592         }
1593         if ($success) {
1594                 $success = jabber_public_notice($notice);
1595                 if (!$success) {
1596                         common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1597                 }
1598         }
1599         // XXX: broadcast notices to other IM
1600         return $success;
1601 }
1602
1603 function common_broadcast_profile($profile) {
1604         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1605         require_once(INSTALLDIR.'/lib/omb.php');
1606         omb_broadcast_profile($profile);
1607         // XXX: Other broadcasts...?
1608         return true;
1609 }
1610
1611 function common_profile_url($nickname) {
1612         return common_local_url('showstream', array('nickname' => $nickname));
1613 }
1614
1615 # Don't call if nobody's logged in
1616
1617 function common_notice_form($action=NULL, $content=NULL) {
1618         $user = common_current_user();
1619         assert(!is_null($user));
1620         common_element_start('form', array('id' => 'status_form',
1621                                                                            'method' => 'post',
1622                                                                            'action' => common_local_url('newnotice')));
1623         common_element_start('p');
1624         common_element('label', array('for' => 'status_textarea',
1625                                                                   'id' => 'status_label'),
1626                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1627     common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1628         common_element('textarea', array('id' => 'status_textarea',
1629                                                                          'cols' => 60,
1630                                                                          'rows' => 3,
1631                                                                          'name' => 'status_textarea'),
1632                                    ($content) ? $content : '');
1633         common_hidden('token', common_session_token());
1634         if ($action) {
1635                 common_hidden('returnto', $action);
1636         }
1637         # set by JavaScript
1638         common_hidden('inreplyto', 'false');
1639         common_element('input', array('id' => 'status_submit',
1640                                                                   'name' => 'status_submit',
1641                                                                   'type' => 'submit',
1642                                                                   'value' => _('Send')));
1643         common_element_end('p');
1644         common_element_end('form');
1645 }
1646
1647 # Should make up a reasonable root URL
1648
1649 function common_root_url() {
1650         return common_path('');
1651 }
1652
1653 # returns $bytes bytes of random data as a hexadecimal string
1654 # "good" here is a goal and not a guarantee
1655
1656 function common_good_rand($bytes) {
1657         # XXX: use random.org...?
1658         if (file_exists('/dev/urandom')) {
1659                 return common_urandom($bytes);
1660         } else { # FIXME: this is probably not good enough
1661                 return common_mtrand($bytes);
1662         }
1663 }
1664
1665 function common_urandom($bytes) {
1666         $h = fopen('/dev/urandom', 'rb');
1667         # should not block
1668         $src = fread($h, $bytes);
1669         fclose($h);
1670         $enc = '';
1671         for ($i = 0; $i < $bytes; $i++) {
1672                 $enc .= sprintf("%02x", (ord($src[$i])));
1673         }
1674         return $enc;
1675 }
1676
1677 function common_mtrand($bytes) {
1678         $enc = '';
1679         for ($i = 0; $i < $bytes; $i++) {
1680                 $enc .= sprintf("%02x", mt_rand(0, 255));
1681         }
1682         return $enc;
1683 }
1684
1685 function common_set_returnto($url) {
1686         common_ensure_session();
1687         $_SESSION['returnto'] = $url;
1688 }
1689
1690 function common_get_returnto() {
1691         common_ensure_session();
1692         return $_SESSION['returnto'];
1693 }
1694
1695 function common_timestamp() {
1696         return date('YmdHis');
1697 }
1698
1699 function common_ensure_syslog() {
1700         static $initialized = false;
1701         if (!$initialized) {
1702                 global $config;
1703                 openlog($config['syslog']['appname'], 0, LOG_USER);
1704                 $initialized = true;
1705         }
1706 }
1707
1708 function common_log($priority, $msg, $filename=NULL) {
1709         $logfile = common_config('site', 'logfile');
1710         if ($logfile) {
1711                 $log = fopen($logfile, "a");
1712                 if ($log) {
1713                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1714                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1715                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1716                         fwrite($log, $output);
1717                         fclose($log);
1718                 }
1719         } else {
1720                 common_ensure_syslog();
1721                 syslog($priority, $msg);
1722         }
1723 }
1724
1725 function common_debug($msg, $filename=NULL) {
1726         if ($filename) {
1727                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1728         } else {
1729                 common_log(LOG_DEBUG, $msg);
1730         }
1731 }
1732
1733 function common_log_db_error(&$object, $verb, $filename=NULL) {
1734         $objstr = common_log_objstring($object);
1735         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1736         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1737 }
1738
1739 function common_log_objstring(&$object) {
1740         if (is_null($object)) {
1741                 return "NULL";
1742         }
1743         $arr = $object->toArray();
1744         $fields = array();
1745         foreach ($arr as $k => $v) {
1746                 $fields[] = "$k='$v'";
1747         }
1748         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1749         return $objstring;
1750 }
1751
1752 function common_valid_http_url($url) {
1753         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1754 }
1755
1756 function common_valid_tag($tag) {
1757         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1758                 return (Validate::email($matches[1]) ||
1759                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1760         }
1761         return false;
1762 }
1763
1764 # Does a little before-after block for next/prev page
1765
1766 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1767
1768         if ($have_before || $have_after) {
1769                 common_element_start('div', array('id' => 'pagination'));
1770                 common_element_start('ul', array('id' => 'nav_pagination'));
1771         }
1772
1773         if ($have_before) {
1774                 $pargs = array('page' => $page-1);
1775                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1776
1777                 common_element_start('li', 'before');
1778                 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1779                                            _('« After'));
1780                 common_element_end('li');
1781         }
1782
1783         if ($have_after) {
1784                 $pargs = array('page' => $page+1);
1785                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1786                 common_element_start('li', 'after');
1787                 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1788                                                    _('Before Â»'));
1789                 common_element_end('li');
1790         }
1791
1792         if ($have_before || $have_after) {
1793                 common_element_end('ul');
1794                 common_element_end('div');
1795         }
1796 }
1797
1798 /* Following functions are copied from MediaWiki GlobalFunctions.php
1799  * and written by Evan Prodromou. */
1800
1801 function common_accept_to_prefs($accept, $def = '*/*') {
1802         # No arg means accept anything (per HTTP spec)
1803         if(!$accept) {
1804                 return array($def => 1);
1805         }
1806
1807         $prefs = array();
1808
1809         $parts = explode(',', $accept);
1810
1811         foreach($parts as $part) {
1812                 # FIXME: doesn't deal with params like 'text/html; level=1'
1813                 @list($value, $qpart) = explode(';', $part);
1814                 $match = array();
1815                 if(!isset($qpart)) {
1816                         $prefs[$value] = 1;
1817                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1818                         $prefs[$value] = $match[1];
1819                 }
1820         }
1821
1822         return $prefs;
1823 }
1824
1825 function common_mime_type_match($type, $avail) {
1826         if(array_key_exists($type, $avail)) {
1827                 return $type;
1828         } else {
1829                 $parts = explode('/', $type);
1830                 if(array_key_exists($parts[0] . '/*', $avail)) {
1831                         return $parts[0] . '/*';
1832                 } elseif(array_key_exists('*/*', $avail)) {
1833                         return '*/*';
1834                 } else {
1835                         return NULL;
1836                 }
1837         }
1838 }
1839
1840 function common_negotiate_type($cprefs, $sprefs) {
1841         $combine = array();
1842
1843         foreach(array_keys($sprefs) as $type) {
1844                 $parts = explode('/', $type);
1845                 if($parts[1] != '*') {
1846                         $ckey = common_mime_type_match($type, $cprefs);
1847                         if($ckey) {
1848                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1849                         }
1850                 }
1851         }
1852
1853         foreach(array_keys($cprefs) as $type) {
1854                 $parts = explode('/', $type);
1855                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1856                         $skey = common_mime_type_match($type, $sprefs);
1857                         if($skey) {
1858                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1859                         }
1860                 }
1861         }
1862
1863         $bestq = 0;
1864         $besttype = "text/html";
1865
1866         foreach(array_keys($combine) as $type) {
1867                 if($combine[$type] > $bestq) {
1868                         $besttype = $type;
1869                         $bestq = $combine[$type];
1870                 }
1871         }
1872
1873         return $besttype;
1874 }
1875
1876 function common_config($main, $sub) {
1877         global $config;
1878         return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1879 }
1880
1881 function common_copy_args($from) {
1882         $to = array();
1883         $strip = get_magic_quotes_gpc();
1884         foreach ($from as $k => $v) {
1885                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1886         }
1887         return $to;
1888 }
1889
1890 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1891 // This is used before handing a request off to OAuthRequest::from_request.
1892 function common_remove_magic_from_request() {
1893         if(get_magic_quotes_gpc()) {
1894                 $_POST=array_map('stripslashes',$_POST);
1895                 $_GET=array_map('stripslashes',$_GET);
1896         }
1897 }
1898
1899 function common_user_uri(&$user) {
1900         return common_local_url('userbyid', array('id' => $user->id));
1901 }
1902
1903 function common_notice_uri(&$notice) {
1904         return common_local_url('shownotice',
1905                 array('notice' => $notice->id));
1906 }
1907
1908 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1909
1910 function common_confirmation_code($bits) {
1911         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1912         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1913         $chars = ceil($bits/5);
1914         $code = '';
1915         for ($i = 0; $i < $chars; $i++) {
1916                 # XXX: convert to string and back
1917                 $num = hexdec(common_good_rand(1));
1918                 # XXX: randomness is too precious to throw away almost
1919                 # 40% of the bits we get!
1920                 $code .= $codechars[$num%32];
1921         }
1922         return $code;
1923 }
1924
1925 # convert markup to HTML
1926
1927 function common_markup_to_html($c) {
1928         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1929         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1930         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1931         return Markdown($c);
1932 }
1933
1934 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1935         $avatar = $profile->getAvatar($size);
1936         if ($avatar) {
1937                 return common_avatar_display_url($avatar);
1938         } else {
1939                 return common_default_avatar($size);
1940         }
1941 }
1942
1943 function common_profile_uri($profile) {
1944         if (!$profile) {
1945                 return NULL;
1946         }
1947         $user = User::staticGet($profile->id);
1948         if ($user) {
1949                 return $user->uri;
1950         }
1951
1952         $remote = Remote_profile::staticGet($profile->id);
1953         if ($remote) {
1954                 return $remote->uri;
1955         }
1956         # XXX: this is a very bad profile!
1957         return NULL;
1958 }
1959
1960 function common_canonical_sms($sms) {
1961         # strip non-digits
1962         preg_replace('/\D/', '', $sms);
1963         return $sms;
1964 }
1965
1966 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1967     switch ($errno) {
1968      case E_USER_ERROR:
1969                 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1970                 exit(1);
1971                 break;
1972
1973          case E_USER_WARNING:
1974                 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1975                 break;
1976
1977      case E_USER_NOTICE:
1978                 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1979                 break;
1980     }
1981
1982         # FIXME: show error page if we're on the Web
1983     /* Don't execute PHP internal error handler */
1984     return true;
1985 }
1986
1987 function common_session_token() {
1988         common_ensure_session();
1989         if (!array_key_exists('token', $_SESSION)) {
1990                 $_SESSION['token'] = common_good_rand(64);
1991         }
1992         return $_SESSION['token'];
1993 }
1994
1995 function common_disfavor_form($notice) {
1996         common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1997                                                                            'method' => 'post',
1998                                                                            'class' => 'disfavor',
1999                                                                            'action' => common_local_url('disfavor')));
2000
2001         common_element('input', array('type' => 'hidden',
2002                                                                   'name' => 'token-'. $notice->id,
2003                                                                   'id' => 'token-'. $notice->id,
2004                                                                   'class' => 'token',
2005                                                                   'value' => common_session_token()));
2006
2007         common_element('input', array('type' => 'hidden',
2008                                                                   'name' => 'notice',
2009                                                                   'id' => 'notice-n'. $notice->id,
2010                                                                   'class' => 'notice',
2011                                                                   'value' => $notice->id));
2012
2013         common_element('input', array('type' => 'submit',
2014                                                                   'id' => 'disfavor-submit-' . $notice->id,
2015                                                                   'name' => 'disfavor-submit-' . $notice->id,
2016                                                                   'class' => 'disfavor',
2017                                                                   'value' => 'Disfavor favorite',
2018                                                                   'title' => 'Remove this message from favorites'));
2019         common_element_end('form');
2020 }
2021
2022 function common_favor_form($notice) {
2023         common_element_start('form', array('id' => 'favor-' . $notice->id,
2024                                                                            'method' => 'post',
2025                                                                            'class' => 'favor',
2026                                                                            'action' => common_local_url('favor')));
2027
2028         common_element('input', array('type' => 'hidden',
2029                                                                   'name' => 'token-'. $notice->id,
2030                                                                   'id' => 'token-'. $notice->id,
2031                                                                   'class' => 'token',
2032                                                                   'value' => common_session_token()));
2033
2034         common_element('input', array('type' => 'hidden',
2035                                                                   'name' => 'notice',
2036                                                                   'id' => 'notice-n'. $notice->id,
2037                                                                   'class' => 'notice',
2038                                                                   'value' => $notice->id));
2039
2040         common_element('input', array('type' => 'submit',
2041                                                                   'id' => 'favor-submit-' . $notice->id,
2042                                                                   'name' => 'favor-submit-' . $notice->id,
2043                                                                   'class' => 'favor',
2044                                                                   'value' => 'Add to favorites',
2045                                                                   'title' => 'Add this message to favorites'));
2046         common_element_end('form');
2047 }
2048
2049 function common_nudge_form($profile) {
2050         common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2051                                                                            'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2052         common_hidden('token', common_session_token());
2053         common_element('input', array('type' => 'submit',
2054                                                                   'class' => 'submit',
2055                                                                   'value' => _('Send a nudge')));
2056         common_element_end('form');
2057 }
2058 function common_nudge_response() {
2059         common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2060 }
2061
2062 function common_subscribe_form($profile) {
2063         common_element_start('form', array('id' => 'subscribe-' . $profile->id,
2064                                                                            'method' => 'post',
2065                                                                            'class' => 'subscribe',
2066                                                                            'action' => common_local_url('subscribe')));
2067         common_hidden('token', common_session_token());
2068         common_element('input', array('id' => 'subscribeto-' . $profile->id,
2069                                                                   'name' => 'subscribeto',
2070                                                                   'type' => 'hidden',
2071                                                                   'value' => $profile->id));
2072         common_element('input', array('type' => 'submit',
2073                                                                   'class' => 'submit',
2074                                                                   'value' => _('Subscribe')));
2075         common_element_end('form');
2076 }
2077
2078 function common_unsubscribe_form($profile) {
2079         common_element_start('form', array('id' => 'unsubscribe-' . $profile->nickname,
2080                                                                            'method' => 'post',
2081                                                                            'class' => 'unsubscribe',
2082                                                                            'action' => common_local_url('unsubscribe')));
2083         common_hidden('token', common_session_token());
2084         common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
2085                                                                   'name' => 'unsubscribeto',
2086                                                                   'type' => 'hidden',
2087                                                                   'value' => $profile->id));
2088         common_element('input', array('type' => 'submit',
2089                                                                   'class' => 'submit',
2090                                                                   'value' => _('Unsubscribe')));
2091         common_element_end('form');
2092 }
2093
2094 // XXX: Refactor this code
2095 function common_profile_new_message_nudge ($cur, $profile) {
2096         $user = User::staticGet('id', $profile->id);
2097
2098         if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2099         common_element_start('li', array('id' => 'profile_send_a_new_message'));
2100                 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2101                                            _('Send a message'));
2102         common_element_end('li');
2103
2104             if ($user->email && $user->emailnotifynudge) {
2105             common_element_start('li', array('id' => 'profile_nudge'));
2106             common_nudge_form($user);
2107             common_element_end('li');
2108         }
2109         }
2110 }
2111
2112 function common_cache_key($extra) {
2113         return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2114 }
2115
2116 function common_keyize($str) {
2117         $str = strtolower($str);
2118         $str = preg_replace('/\s/', '_', $str);
2119         return $str;
2120 }
2121
2122 function common_message_form($content, $user, $to) {
2123
2124         common_element_start('form', array('id' => 'message_form',
2125                                                                            'method' => 'post',
2126                                                                            'action' => common_local_url('newmessage')));
2127
2128         $mutual_users = $user->mutuallySubscribedUsers();
2129
2130         $mutual = array();
2131
2132         while ($mutual_users->fetch()) {
2133                 if ($mutual_users->id != $user->id) {
2134                         $mutual[$mutual_users->id] = $mutual_users->nickname;
2135                 }
2136         }
2137
2138         $mutual_users->free();
2139         unset($mutual_users);
2140
2141         common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
2142
2143         common_element_start('p');
2144
2145         common_element('textarea', array('id' => 'message_content',
2146                                                                          'cols' => 60,
2147                                                                          'rows' => 3,
2148                                                                          'name' => 'content'),
2149                                    ($content) ? $content : '');
2150
2151         common_element('input', array('id' => 'message_send',
2152                                                                   'name' => 'message_send',
2153                                                                   'type' => 'submit',
2154                                                                   'value' => _('Send')));
2155
2156         common_hidden('token', common_session_token());
2157
2158         common_element_end('p');
2159         common_element_end('form');
2160 }
2161
2162 function common_memcache() {
2163         static $cache = NULL;
2164         if (!common_config('memcached', 'enabled')) {
2165                 return NULL;
2166         } else {
2167                 if (!$cache) {
2168                         $cache = new Memcache();
2169                         $servers = common_config('memcached', 'server');
2170                         if (is_array($servers)) {
2171                                 foreach($servers as $server) {
2172                                         $cache->addServer($server);
2173                                 }
2174                         } else {
2175                                 $cache->addServer($servers);
2176                         }
2177                 }
2178                 return $cache;
2179         }
2180 }
2181
2182 function common_compatible_license($from, $to) {
2183         # XXX: better compatibility check needed here!
2184         return ($from == $to);
2185 }