]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch 'master' of http://goukihq.org/misc/git/laconica-locales
[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 '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
940         } else {
941                 return $nickname;
942         }
943 }
944
945 function common_at_hash_link($sender_id, $tag) {
946         $user = User::staticGet($sender_id);
947         if (!$user) {
948                 return $tag;
949         }
950         $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
951         if ($tagged) {
952                 $url = common_local_url('subscriptions',
953                                                                 array('nickname' => $user->nickname,
954                                                                           'tag' => $tag));
955                 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
956         } else {
957                 return $tag;
958         }
959 }
960
961 function common_relative_profile($sender, $nickname, $dt=NULL) {
962         # Try to find profiles this profile is subscribed to that have this nickname
963         $recipient = new Profile();
964         # XXX: use a join instead of a subquery
965         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
966         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
967         if ($recipient->find(TRUE)) {
968                 # XXX: should probably differentiate between profiles with
969                 # the same name by date of most recent update
970                 return $recipient;
971         }
972         # Try to find profiles that listen to this profile and that have this nickname
973         $recipient = new Profile();
974         # XXX: use a join instead of a subquery
975         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
976         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
977         if ($recipient->find(TRUE)) {
978                 # XXX: should probably differentiate between profiles with
979                 # the same name by date of most recent update
980                 return $recipient;
981         }
982         # If this is a local user, try to find a local user with that nickname.
983         $sender = User::staticGet($sender->id);
984         if ($sender) {
985                 $recipient_user = User::staticGet('nickname', $nickname);
986                 if ($recipient_user) {
987                         return $recipient_user->getProfile();
988                 }
989         }
990         # Otherwise, no links. @messages from local users to remote users,
991         # or from remote users to other remote users, are just
992         # outside our ability to make intelligent guesses about
993         return NULL;
994 }
995
996 // where should the avatar go for this user?
997
998 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
999         global $config;
1000
1001         if ($size) {
1002                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
1003         } else {
1004                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
1005         }
1006 }
1007
1008 function common_avatar_path($filename) {
1009         global $config;
1010         return INSTALLDIR . '/avatar/' . $filename;
1011 }
1012
1013 function common_avatar_url($filename) {
1014         return common_path('avatar/'.$filename);
1015 }
1016
1017 function common_avatar_display_url($avatar) {
1018         $server = common_config('avatar', 'server');
1019         if ($server) {
1020                 return 'http://'.$server.'/'.$avatar->filename;
1021         } else {
1022                 return $avatar->url;
1023         }
1024 }
1025
1026 function common_default_avatar($size) {
1027         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
1028                                                           AVATAR_STREAM_SIZE => 'stream',
1029                                                           AVATAR_MINI_SIZE => 'mini');
1030         return theme_path('default-avatar-'.$sizenames[$size].'.png');
1031 }
1032
1033 function common_local_url($action, $args=NULL, $fragment=NULL) {
1034         $url = NULL;
1035         if (common_config('site','fancy')) {
1036                 $url = common_fancy_url($action, $args);
1037         } else {
1038                 $url = common_simple_url($action, $args);
1039         }
1040         if (!is_null($fragment)) {
1041                 $url .= '#'.$fragment;
1042         }
1043         return $url;
1044 }
1045
1046 function common_fancy_url($action, $args=NULL) {
1047         switch (strtolower($action)) {
1048          case 'public':
1049                 if ($args && isset($args['page'])) {
1050                         return common_path('?page=' . $args['page']);
1051                 } else {
1052                         return common_path('');
1053                 }
1054          case 'featured':
1055                 if ($args && isset($args['page'])) {
1056                         return common_path('featured?page=' . $args['page']);
1057                 } else {
1058                         return common_path('featured');
1059                 }
1060          case 'favorited':
1061                 if ($args && isset($args['page'])) {
1062                         return common_path('favorited?page=' . $args['page']);
1063                 } else {
1064                         return common_path('favorited');
1065                 }
1066          case 'publicrss':
1067                 return common_path('rss');
1068          case 'publicatom':
1069                 return common_path("api/statuses/public_timeline.atom");
1070          case 'publicxrds':
1071                 return common_path('xrds');
1072          case 'featuredrss':
1073                 return common_path('featuredrss');
1074          case 'favoritedrss':
1075                 return common_path('favoritedrss');
1076          case 'opensearch':
1077                 if ($args && $args['type']) {
1078                         return common_path('opensearch/'.$args['type']);
1079                 } else {
1080                         return common_path('opensearch/people');
1081                 }
1082          case 'doc':
1083                 return common_path('doc/'.$args['title']);
1084      case 'block':
1085          case 'login':
1086          case 'logout':
1087          case 'subscribe':
1088          case 'unsubscribe':
1089          case 'invite':
1090                 return common_path('main/'.$action);
1091          case 'tagother':
1092                 return common_path('main/tagother?id='.$args['id']);
1093          case 'register':
1094                 if ($args && $args['code']) {
1095                         return common_path('main/register/'.$args['code']);
1096                 } else {
1097                         return common_path('main/register');
1098                 }
1099          case 'remotesubscribe':
1100                 if ($args && $args['nickname']) {
1101                         return common_path('main/remote?nickname=' . $args['nickname']);
1102                 } else {
1103                         return common_path('main/remote');
1104                 }
1105          case 'nudge':
1106                 return common_path($args['nickname'].'/nudge');
1107          case 'openidlogin':
1108                 return common_path('main/openid');
1109          case 'profilesettings':
1110                 return common_path('settings/profile');
1111          case 'emailsettings':
1112                 return common_path('settings/email');
1113          case 'openidsettings':
1114                 return common_path('settings/openid');
1115          case 'smssettings':
1116                 return common_path('settings/sms');
1117          case 'twittersettings':
1118                 return common_path('settings/twitter');
1119          case 'othersettings':
1120                 return common_path('settings/other');
1121      case 'deleteprofile':
1122         return common_path('settings/delete');
1123          case 'newnotice':
1124                 if ($args && $args['replyto']) {
1125                         return common_path('notice/new?replyto='.$args['replyto']);
1126                 } else {
1127                         return common_path('notice/new');
1128                 }
1129          case 'shownotice':
1130                 return common_path('notice/'.$args['notice']);
1131          case 'deletenotice':
1132                 if ($args && $args['notice']) {
1133                         return common_path('notice/delete/'.$args['notice']);
1134                 } else {
1135                         return common_path('notice/delete');
1136                 }
1137          case 'microsummary':
1138          case 'xrds':
1139          case 'foaf':
1140                 return common_path($args['nickname'].'/'.$action);
1141          case 'all':
1142          case 'replies':
1143          case 'inbox':
1144          case 'outbox':
1145                 if ($args && isset($args['page'])) {
1146                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1147                 } else {
1148                         return common_path($args['nickname'].'/'.$action);
1149                 }
1150          case 'subscriptions':
1151          case 'subscribers':
1152                 $nickname = $args['nickname'];
1153                 unset($args['nickname']);
1154                 if (isset($args['tag'])) {
1155                         $tag = $args['tag'];
1156                         unset($args['tag']);
1157                 }
1158                 $params = http_build_query($args);
1159                 if ($params) {
1160                         return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1161                 } else {
1162                         return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1163                 }
1164          case 'allrss':
1165                 return common_path($args['nickname'].'/all/rss');
1166          case 'repliesrss':
1167                 return common_path($args['nickname'].'/replies/rss');
1168          case 'userrss':
1169         if (isset($args['limit']))
1170                     return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1171                 return common_path($args['nickname'].'/rss');
1172          case 'showstream':
1173                 if ($args && isset($args['page'])) {
1174                         return common_path($args['nickname'].'?page=' . $args['page']);
1175                 } else {
1176                         return common_path($args['nickname']);
1177                 }
1178
1179          case 'usertimeline':
1180                 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1181          case 'confirmaddress':
1182                 return common_path('main/confirmaddress/'.$args['code']);
1183          case 'userbyid':
1184                 return common_path('user/'.$args['id']);
1185          case 'recoverpassword':
1186             $path = 'main/recoverpassword';
1187             if ($args['code']) {
1188                 $path .= '/' . $args['code'];
1189                 }
1190             return common_path($path);
1191          case 'imsettings':
1192                 return common_path('settings/im');
1193          case 'peoplesearch':
1194                 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1195          case 'noticesearch':
1196                 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1197          case 'noticesearchrss':
1198                 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1199          case 'avatarbynickname':
1200                 return common_path($args['nickname'].'/avatar/'.$args['size']);
1201          case 'tag':
1202             if (isset($args['tag']) && $args['tag']) {
1203                         $path = 'tag/' . $args['tag'];
1204                         unset($args['tag']);
1205                 } else {
1206                         $path = 'tags';
1207                 }
1208                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1209          case 'tagrss':
1210         $path = 'tag/' . $args['tag'] . '/rss';
1211         unset($args['tag']);
1212                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1213          case 'peopletag':
1214                 $path = 'peopletag/' . $args['tag'];
1215                 unset($args['tag']);
1216                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1217          case 'tags':
1218                 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1219          case 'favor':
1220                 return common_path('main/favor');
1221          case 'disfavor':
1222                 return common_path('main/disfavor');
1223          case 'showfavorites':
1224                 if ($args && isset($args['page'])) {
1225                         return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1226                 } else {
1227                         return common_path($args['nickname'].'/favorites');
1228                 }
1229          case 'favoritesrss':
1230                 return common_path($args['nickname'].'/favorites/rss');
1231          case 'showmessage':
1232                 return common_path('message/' . $args['message']);
1233          case 'newmessage':
1234                 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1235          case 'api':
1236                 # XXX: do fancy URLs for all the API methods
1237                 switch (strtolower($args['apiaction'])) {
1238                  case 'statuses':
1239                         switch (strtolower($args['method'])) {
1240                          case 'user_timeline.rss':
1241                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1242                          case 'user_timeline.atom':
1243                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1244                          case 'user_timeline.json':
1245                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1246                          case 'user_timeline.xml':
1247                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1248                          default: return common_simple_url($action, $args);
1249                         }
1250                  default: return common_simple_url($action, $args);
1251                 }
1252          case 'sup':
1253                 if ($args && isset($args['seconds'])) {
1254                         return common_path('main/sup?seconds='.$args['seconds']);
1255                 } else {
1256                         return common_path('main/sup');
1257                 }
1258          default:
1259                 return common_simple_url($action, $args);
1260         }
1261 }
1262
1263 function common_simple_url($action, $args=NULL) {
1264         global $config;
1265         /* XXX: pretty URLs */
1266         $extra = '';
1267         if ($args) {
1268                 foreach ($args as $key => $value) {
1269                         $extra .= "&${key}=${value}";
1270                 }
1271         }
1272         return common_path("index.php?action=${action}${extra}");
1273 }
1274
1275 function common_path($relative) {
1276         global $config;
1277         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1278         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1279 }
1280
1281 function common_date_string($dt) {
1282         // XXX: do some sexy date formatting
1283         // return date(DATE_RFC822, $dt);
1284         $t = strtotime($dt);
1285         $now = time();
1286         $diff = $now - $t;
1287
1288         if ($now < $t) { # that shouldn't happen!
1289                 return common_exact_date($dt);
1290         } else if ($diff < 60) {
1291                 return _('a few seconds ago');
1292         } else if ($diff < 92) {
1293                 return _('about a minute ago');
1294         } else if ($diff < 3300) {
1295                 return sprintf(_('about %d minutes ago'), round($diff/60));
1296         } else if ($diff < 5400) {
1297                 return _('about an hour ago');
1298         } else if ($diff < 22 * 3600) {
1299                 return sprintf(_('about %d hours ago'), round($diff/3600));
1300         } else if ($diff < 37 * 3600) {
1301                 return _('about a day ago');
1302         } else if ($diff < 24 * 24 * 3600) {
1303                 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1304         } else if ($diff < 46 * 24 * 3600) {
1305                 return _('about a month ago');
1306         } else if ($diff < 330 * 24 * 3600) {
1307                 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1308         } else if ($diff < 480 * 24 * 3600) {
1309                 return _('about a year ago');
1310         } else {
1311                 return common_exact_date($dt);
1312         }
1313 }
1314
1315 function common_exact_date($dt) {
1316     static $_utc;
1317     static $_siteTz;
1318
1319     if (!$_utc) {
1320         $_utc = new DateTimeZone('UTC');
1321         $_siteTz = new DateTimeZone(common_timezone());
1322     }
1323
1324         $dateStr = date('d F Y H:i:s', strtotime($dt));
1325         $d = new DateTime($dateStr, $_utc);
1326         $d->setTimezone($_siteTz);
1327         return $d->format(DATE_RFC850);
1328 }
1329
1330 function common_date_w3dtf($dt) {
1331         $dateStr = date('d F Y H:i:s', strtotime($dt));
1332         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1333         $d->setTimezone(new DateTimeZone(common_timezone()));
1334         return $d->format(DATE_W3C);
1335 }
1336
1337 function common_date_rfc2822($dt) {
1338         $dateStr = date('d F Y H:i:s', strtotime($dt));
1339         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1340         $d->setTimezone(new DateTimeZone(common_timezone()));
1341         return $d->format('r');
1342 }
1343
1344 function common_date_iso8601($dt) {
1345         $dateStr = date('d F Y H:i:s', strtotime($dt));
1346         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1347         $d->setTimezone(new DateTimeZone(common_timezone()));
1348         return $d->format('c');
1349 }
1350
1351 function common_sql_now() {
1352         return strftime('%Y-%m-%d %H:%M:%S', time());
1353 }
1354
1355 function common_redirect($url, $code=307) {
1356         static $status = array(301 => "Moved Permanently",
1357                                                    302 => "Found",
1358                                                    303 => "See Other",
1359                                                    307 => "Temporary Redirect");
1360         header("Status: ${code} $status[$code]");
1361         header("Location: $url");
1362
1363         common_start_xml('a',
1364                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
1365                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1366         common_element('a', array('href' => $url), $url);
1367         common_end_xml();
1368     exit;
1369 }
1370
1371 function common_save_replies($notice) {
1372         # Alternative reply format
1373         $tname = false;
1374         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1375                 $tname = $match[1];
1376         }
1377         # extract all @messages
1378         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1379
1380         $names = array();
1381
1382         if ($cnt || $tname) {
1383                 # XXX: is there another way to make an array copy?
1384                 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1385         }
1386
1387         $sender = Profile::staticGet($notice->profile_id);
1388
1389         $replied = array();
1390
1391         # store replied only for first @ (what user/notice what the reply directed,
1392         # we assume first @ is it)
1393
1394         for ($i=0; $i<count($names); $i++) {
1395                 $nickname = $names[$i];
1396                 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1397                 if (!$recipient) {
1398                         continue;
1399                 }
1400                 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1401                         $reply_for = $recipient;
1402                         $recipient_notice = $reply_for->getCurrentNotice();
1403                         if ($recipient_notice) {
1404                                 $orig = clone($notice);
1405                                 $notice->reply_to = $recipient_notice->id;
1406                                 $notice->update($orig);
1407                         }
1408                 }
1409         # Don't save replies from blocked profile to local user
1410         $recipient_user = User::staticGet('id', $recipient->id);
1411         if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1412             continue;
1413         }
1414                 $reply = new Reply();
1415                 $reply->notice_id = $notice->id;
1416                 $reply->profile_id = $recipient->id;
1417                 $id = $reply->insert();
1418                 if (!$id) {
1419                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1420                         common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1421                         common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1422                         return;
1423                 } else {
1424                         $replied[$recipient->id] = 1;
1425                 }
1426         }
1427
1428         # Hash format replies, too
1429         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1430         if ($cnt) {
1431                 foreach ($match[1] as $tag) {
1432                         $tagged = Profile_tag::getTagged($sender->id, $tag);
1433                         foreach ($tagged as $t) {
1434                                 if (!$replied[$t->id]) {
1435                     # Don't save replies from blocked profile to local user
1436                     $t_user = User::staticGet('id', $t->id);
1437                     if ($t_user && $t_user->hasBlocked($sender)) {
1438                         continue;
1439                     }
1440                                         $reply = new Reply();
1441                                         $reply->notice_id = $notice->id;
1442                                         $reply->profile_id = $t->id;
1443                                         $id = $reply->insert();
1444                                         if (!$id) {
1445                                                 common_log_db_error($reply, 'INSERT', __FILE__);
1446                                                 return;
1447                                         }
1448                                 }
1449                         }
1450                 }
1451         }
1452 }
1453
1454 function common_broadcast_notice($notice, $remote=false) {
1455
1456         // Check to see if notice should go to Twitter
1457         $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1458         if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1459
1460                 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1461
1462                 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1463                         (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1464
1465                         $result = common_twitter_broadcast($notice, $flink);
1466
1467                         if (!$result) {
1468                                 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1469                         }
1470                 }
1471         }
1472
1473         if (common_config('queue', 'enabled')) {
1474                 # Do it later!
1475                 return common_enqueue_notice($notice);
1476         } else {
1477                 return common_real_broadcast($notice, $remote);
1478         }
1479 }
1480
1481 function common_twitter_broadcast($notice, $flink) {
1482         global $config;
1483         $success = true;
1484         $fuser = $flink->getForeignUser();
1485         $twitter_user = $fuser->nickname;
1486         $twitter_password = $flink->credentials;
1487         $uri = 'http://www.twitter.com/statuses/update.json';
1488
1489         // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1490         $statustxt = preg_replace('/^@/', ' @', $notice->content);
1491
1492         $options = array(
1493                 CURLOPT_USERPWD                 => "$twitter_user:$twitter_password",
1494                 CURLOPT_POST                    => true,
1495                 CURLOPT_POSTFIELDS              => array(
1496                                                                         'status'        => $statustxt,
1497                                                                         'source'        => $config['integration']['source']
1498                                                                         ),
1499                 CURLOPT_RETURNTRANSFER  => true,
1500                 CURLOPT_FAILONERROR             => true,
1501                 CURLOPT_HEADER                  => false,
1502                 CURLOPT_FOLLOWLOCATION  => true,
1503                 CURLOPT_USERAGENT               => "Laconica",
1504                 CURLOPT_CONNECTTIMEOUT  => 120,  // XXX: Scary!!!! How long should this be?
1505         CURLOPT_TIMEOUT            => 120,
1506
1507         # Twitter is strict about accepting invalid "Expect" headers
1508         CURLOPT_HTTPHEADER => array('Expect:')
1509         );
1510
1511         $ch = curl_init($uri);
1512     curl_setopt_array($ch, $options);
1513     $data = curl_exec($ch);
1514     $errmsg = curl_error($ch);
1515
1516         if ($errmsg) {
1517                 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1518                         __FILE__);
1519                 $success = false;
1520         }
1521
1522         curl_close($ch);
1523
1524         if (!$data) {
1525                 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1526                         __FILE__);
1527                 $success = false;
1528         }
1529
1530         // Twitter should return a status
1531         $status = json_decode($data);
1532
1533         if (!$status->id) {
1534                 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1535                         __FILE__);
1536                 $success = false;
1537         }
1538
1539         return $success;
1540 }
1541
1542 # Stick the notice on the queue
1543
1544 function common_enqueue_notice($notice) {
1545         foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1546                 $qi = new Queue_item();
1547                 $qi->notice_id = $notice->id;
1548                 $qi->transport = $transport;
1549                 $qi->created = $notice->created;
1550         $result = $qi->insert();
1551                 if (!$result) {
1552                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1553                         common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1554                         return false;
1555                 }
1556                 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1557         }
1558         return $result;
1559 }
1560
1561 function common_dequeue_notice($notice) {
1562         $qi = Queue_item::staticGet($notice->id);
1563         if ($qi) {
1564                 $result = $qi->delete();
1565                 if (!$result) {
1566                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1567                     common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1568                     return false;
1569                 }
1570                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1571                 return $result;
1572         } else {
1573             return false;
1574         }
1575 }
1576
1577 function common_real_broadcast($notice, $remote=false) {
1578         $success = true;
1579         if (!$remote) {
1580                 # Make sure we have the OMB stuff
1581                 require_once(INSTALLDIR.'/lib/omb.php');
1582                 $success = omb_broadcast_remote_subscribers($notice);
1583                 if (!$success) {
1584                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1585                 }
1586         }
1587         if ($success) {
1588                 require_once(INSTALLDIR.'/lib/jabber.php');
1589                 $success = jabber_broadcast_notice($notice);
1590                 if (!$success) {
1591                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1592                 }
1593         }
1594         if ($success) {
1595                 require_once(INSTALLDIR.'/lib/mail.php');
1596                 $success = mail_broadcast_notice_sms($notice);
1597                 if (!$success) {
1598                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1599                 }
1600         }
1601         if ($success) {
1602                 $success = jabber_public_notice($notice);
1603                 if (!$success) {
1604                         common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1605                 }
1606         }
1607         // XXX: broadcast notices to other IM
1608         return $success;
1609 }
1610
1611 function common_broadcast_profile($profile) {
1612         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1613         require_once(INSTALLDIR.'/lib/omb.php');
1614         omb_broadcast_profile($profile);
1615         // XXX: Other broadcasts...?
1616         return true;
1617 }
1618
1619 function common_profile_url($nickname) {
1620         return common_local_url('showstream', array('nickname' => $nickname));
1621 }
1622
1623 # Don't call if nobody's logged in
1624
1625 function common_notice_form($action=NULL, $content=NULL) {
1626         $user = common_current_user();
1627         assert(!is_null($user));
1628         common_element_start('form', array('id' => 'status_form',
1629                                                                            'method' => 'post',
1630                                                                            'action' => common_local_url('newnotice')));
1631         common_element_start('p');
1632         common_element('label', array('for' => 'status_textarea',
1633                                                                   'id' => 'status_label'),
1634                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1635     common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1636         common_element('textarea', array('id' => 'status_textarea',
1637                                                                          'cols' => 60,
1638                                                                          'rows' => 3,
1639                                                                          'name' => 'status_textarea'),
1640                                    ($content) ? $content : '');
1641         common_hidden('token', common_session_token());
1642         if ($action) {
1643                 common_hidden('returnto', $action);
1644         }
1645         # set by JavaScript
1646         common_hidden('inreplyto', 'false');
1647         common_element('input', array('id' => 'status_submit',
1648                                                                   'name' => 'status_submit',
1649                                                                   'type' => 'submit',
1650                                                                   'value' => _('Send')));
1651         common_element_end('p');
1652         common_element_end('form');
1653 }
1654
1655 # Should make up a reasonable root URL
1656
1657 function common_root_url() {
1658         return common_path('');
1659 }
1660
1661 # returns $bytes bytes of random data as a hexadecimal string
1662 # "good" here is a goal and not a guarantee
1663
1664 function common_good_rand($bytes) {
1665         # XXX: use random.org...?
1666         if (file_exists('/dev/urandom')) {
1667                 return common_urandom($bytes);
1668         } else { # FIXME: this is probably not good enough
1669                 return common_mtrand($bytes);
1670         }
1671 }
1672
1673 function common_urandom($bytes) {
1674         $h = fopen('/dev/urandom', 'rb');
1675         # should not block
1676         $src = fread($h, $bytes);
1677         fclose($h);
1678         $enc = '';
1679         for ($i = 0; $i < $bytes; $i++) {
1680                 $enc .= sprintf("%02x", (ord($src[$i])));
1681         }
1682         return $enc;
1683 }
1684
1685 function common_mtrand($bytes) {
1686         $enc = '';
1687         for ($i = 0; $i < $bytes; $i++) {
1688                 $enc .= sprintf("%02x", mt_rand(0, 255));
1689         }
1690         return $enc;
1691 }
1692
1693 function common_set_returnto($url) {
1694         common_ensure_session();
1695         $_SESSION['returnto'] = $url;
1696 }
1697
1698 function common_get_returnto() {
1699         common_ensure_session();
1700         return $_SESSION['returnto'];
1701 }
1702
1703 function common_timestamp() {
1704         return date('YmdHis');
1705 }
1706
1707 function common_ensure_syslog() {
1708         static $initialized = false;
1709         if (!$initialized) {
1710                 global $config;
1711                 openlog($config['syslog']['appname'], 0, LOG_USER);
1712                 $initialized = true;
1713         }
1714 }
1715
1716 function common_log($priority, $msg, $filename=NULL) {
1717         $logfile = common_config('site', 'logfile');
1718         if ($logfile) {
1719                 $log = fopen($logfile, "a");
1720                 if ($log) {
1721                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1722                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1723                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1724                         fwrite($log, $output);
1725                         fclose($log);
1726                 }
1727         } else {
1728                 common_ensure_syslog();
1729                 syslog($priority, $msg);
1730         }
1731 }
1732
1733 function common_debug($msg, $filename=NULL) {
1734         if ($filename) {
1735                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1736         } else {
1737                 common_log(LOG_DEBUG, $msg);
1738         }
1739 }
1740
1741 function common_log_db_error(&$object, $verb, $filename=NULL) {
1742         $objstr = common_log_objstring($object);
1743         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1744         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1745 }
1746
1747 function common_log_objstring(&$object) {
1748         if (is_null($object)) {
1749                 return "NULL";
1750         }
1751         $arr = $object->toArray();
1752         $fields = array();
1753         foreach ($arr as $k => $v) {
1754                 $fields[] = "$k='$v'";
1755         }
1756         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1757         return $objstring;
1758 }
1759
1760 function common_valid_http_url($url) {
1761         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1762 }
1763
1764 function common_valid_tag($tag) {
1765         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1766                 return (Validate::email($matches[1]) ||
1767                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1768         }
1769         return false;
1770 }
1771
1772 # Does a little before-after block for next/prev page
1773
1774 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1775
1776         if ($have_before || $have_after) {
1777                 common_element_start('div', array('id' => 'pagination'));
1778                 common_element_start('ul', array('id' => 'nav_pagination'));
1779         }
1780
1781         if ($have_before) {
1782                 $pargs = array('page' => $page-1);
1783                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1784
1785                 common_element_start('li', 'before');
1786                 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1787                                            _('« After'));
1788                 common_element_end('li');
1789         }
1790
1791         if ($have_after) {
1792                 $pargs = array('page' => $page+1);
1793                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1794                 common_element_start('li', 'after');
1795                 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1796                                                    _('Before Â»'));
1797                 common_element_end('li');
1798         }
1799
1800         if ($have_before || $have_after) {
1801                 common_element_end('ul');
1802                 common_element_end('div');
1803         }
1804 }
1805
1806 /* Following functions are copied from MediaWiki GlobalFunctions.php
1807  * and written by Evan Prodromou. */
1808
1809 function common_accept_to_prefs($accept, $def = '*/*') {
1810         # No arg means accept anything (per HTTP spec)
1811         if(!$accept) {
1812                 return array($def => 1);
1813         }
1814
1815         $prefs = array();
1816
1817         $parts = explode(',', $accept);
1818
1819         foreach($parts as $part) {
1820                 # FIXME: doesn't deal with params like 'text/html; level=1'
1821                 @list($value, $qpart) = explode(';', $part);
1822                 $match = array();
1823                 if(!isset($qpart)) {
1824                         $prefs[$value] = 1;
1825                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1826                         $prefs[$value] = $match[1];
1827                 }
1828         }
1829
1830         return $prefs;
1831 }
1832
1833 function common_mime_type_match($type, $avail) {
1834         if(array_key_exists($type, $avail)) {
1835                 return $type;
1836         } else {
1837                 $parts = explode('/', $type);
1838                 if(array_key_exists($parts[0] . '/*', $avail)) {
1839                         return $parts[0] . '/*';
1840                 } elseif(array_key_exists('*/*', $avail)) {
1841                         return '*/*';
1842                 } else {
1843                         return NULL;
1844                 }
1845         }
1846 }
1847
1848 function common_negotiate_type($cprefs, $sprefs) {
1849         $combine = array();
1850
1851         foreach(array_keys($sprefs) as $type) {
1852                 $parts = explode('/', $type);
1853                 if($parts[1] != '*') {
1854                         $ckey = common_mime_type_match($type, $cprefs);
1855                         if($ckey) {
1856                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1857                         }
1858                 }
1859         }
1860
1861         foreach(array_keys($cprefs) as $type) {
1862                 $parts = explode('/', $type);
1863                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1864                         $skey = common_mime_type_match($type, $sprefs);
1865                         if($skey) {
1866                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1867                         }
1868                 }
1869         }
1870
1871         $bestq = 0;
1872         $besttype = "text/html";
1873
1874         foreach(array_keys($combine) as $type) {
1875                 if($combine[$type] > $bestq) {
1876                         $besttype = $type;
1877                         $bestq = $combine[$type];
1878                 }
1879         }
1880
1881         return $besttype;
1882 }
1883
1884 function common_config($main, $sub) {
1885         global $config;
1886         return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1887 }
1888
1889 function common_copy_args($from) {
1890         $to = array();
1891         $strip = get_magic_quotes_gpc();
1892         foreach ($from as $k => $v) {
1893                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1894         }
1895         return $to;
1896 }
1897
1898 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1899 // This is used before handing a request off to OAuthRequest::from_request.
1900 function common_remove_magic_from_request() {
1901         if(get_magic_quotes_gpc()) {
1902                 $_POST=array_map('stripslashes',$_POST);
1903                 $_GET=array_map('stripslashes',$_GET);
1904         }
1905 }
1906
1907 function common_user_uri(&$user) {
1908         return common_local_url('userbyid', array('id' => $user->id));
1909 }
1910
1911 function common_notice_uri(&$notice) {
1912         return common_local_url('shownotice',
1913                 array('notice' => $notice->id));
1914 }
1915
1916 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1917
1918 function common_confirmation_code($bits) {
1919         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1920         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1921         $chars = ceil($bits/5);
1922         $code = '';
1923         for ($i = 0; $i < $chars; $i++) {
1924                 # XXX: convert to string and back
1925                 $num = hexdec(common_good_rand(1));
1926                 # XXX: randomness is too precious to throw away almost
1927                 # 40% of the bits we get!
1928                 $code .= $codechars[$num%32];
1929         }
1930         return $code;
1931 }
1932
1933 # convert markup to HTML
1934
1935 function common_markup_to_html($c) {
1936         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1937         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1938         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1939         return Markdown($c);
1940 }
1941
1942 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1943         $avatar = $profile->getAvatar($size);
1944         if ($avatar) {
1945                 return common_avatar_display_url($avatar);
1946         } else {
1947                 return common_default_avatar($size);
1948         }
1949 }
1950
1951 function common_profile_uri($profile) {
1952         if (!$profile) {
1953                 return NULL;
1954         }
1955         $user = User::staticGet($profile->id);
1956         if ($user) {
1957                 return $user->uri;
1958         }
1959
1960         $remote = Remote_profile::staticGet($profile->id);
1961         if ($remote) {
1962                 return $remote->uri;
1963         }
1964         # XXX: this is a very bad profile!
1965         return NULL;
1966 }
1967
1968 function common_canonical_sms($sms) {
1969         # strip non-digits
1970         preg_replace('/\D/', '', $sms);
1971         return $sms;
1972 }
1973
1974 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1975     switch ($errno) {
1976      case E_USER_ERROR:
1977                 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1978                 exit(1);
1979                 break;
1980
1981          case E_USER_WARNING:
1982                 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1983                 break;
1984
1985      case E_USER_NOTICE:
1986                 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1987                 break;
1988     }
1989
1990         # FIXME: show error page if we're on the Web
1991     /* Don't execute PHP internal error handler */
1992     return true;
1993 }
1994
1995 function common_session_token() {
1996         common_ensure_session();
1997         if (!array_key_exists('token', $_SESSION)) {
1998                 $_SESSION['token'] = common_good_rand(64);
1999         }
2000         return $_SESSION['token'];
2001 }
2002
2003 function common_disfavor_form($notice) {
2004         common_element_start('form', array('id' => 'disfavor-' . $notice->id,
2005                                                                            'method' => 'post',
2006                                                                            'class' => 'disfavor',
2007                                                                            'action' => common_local_url('disfavor')));
2008
2009         common_element('input', array('type' => 'hidden',
2010                                                                   'name' => 'token-'. $notice->id,
2011                                                                   'id' => 'token-'. $notice->id,
2012                                                                   'class' => 'token',
2013                                                                   'value' => common_session_token()));
2014
2015         common_element('input', array('type' => 'hidden',
2016                                                                   'name' => 'notice',
2017                                                                   'id' => 'notice-n'. $notice->id,
2018                                                                   'class' => 'notice',
2019                                                                   'value' => $notice->id));
2020
2021         common_element('input', array('type' => 'submit',
2022                                                                   'id' => 'disfavor-submit-' . $notice->id,
2023                                                                   'name' => 'disfavor-submit-' . $notice->id,
2024                                                                   'class' => 'disfavor',
2025                                                                   'value' => 'Disfavor favorite',
2026                                                                   'title' => 'Remove this message from favorites'));
2027         common_element_end('form');
2028 }
2029
2030 function common_favor_form($notice) {
2031         common_element_start('form', array('id' => 'favor-' . $notice->id,
2032                                                                            'method' => 'post',
2033                                                                            'class' => 'favor',
2034                                                                            'action' => common_local_url('favor')));
2035
2036         common_element('input', array('type' => 'hidden',
2037                                                                   'name' => 'token-'. $notice->id,
2038                                                                   'id' => 'token-'. $notice->id,
2039                                                                   'class' => 'token',
2040                                                                   'value' => common_session_token()));
2041
2042         common_element('input', array('type' => 'hidden',
2043                                                                   'name' => 'notice',
2044                                                                   'id' => 'notice-n'. $notice->id,
2045                                                                   'class' => 'notice',
2046                                                                   'value' => $notice->id));
2047
2048         common_element('input', array('type' => 'submit',
2049                                                                   'id' => 'favor-submit-' . $notice->id,
2050                                                                   'name' => 'favor-submit-' . $notice->id,
2051                                                                   'class' => 'favor',
2052                                                                   'value' => 'Add to favorites',
2053                                                                   'title' => 'Add this message to favorites'));
2054         common_element_end('form');
2055 }
2056
2057 function common_nudge_form($profile) {
2058         common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2059                                                                            'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2060         common_hidden('token', common_session_token());
2061         common_element('input', array('type' => 'submit',
2062                                                                   'class' => 'submit',
2063                                                                   'value' => _('Send a nudge')));
2064         common_element_end('form');
2065 }
2066 function common_nudge_response() {
2067         common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2068 }
2069
2070 function common_subscribe_form($profile) {
2071         common_element_start('form', array('id' => 'subscribe-' . $profile->id,
2072                                                                            'method' => 'post',
2073                                                                            'class' => 'subscribe',
2074                                                                            'action' => common_local_url('subscribe')));
2075         common_hidden('token', common_session_token());
2076         common_element('input', array('id' => 'subscribeto-' . $profile->id,
2077                                                                   'name' => 'subscribeto',
2078                                                                   'type' => 'hidden',
2079                                                                   'value' => $profile->id));
2080         common_element('input', array('type' => 'submit',
2081                                                                   'class' => 'submit',
2082                                                                   'value' => _('Subscribe')));
2083         common_element_end('form');
2084 }
2085
2086 function common_unsubscribe_form($profile) {
2087         common_element_start('form', array('id' => 'unsubscribe-' . $profile->id,
2088                                                                            'method' => 'post',
2089                                                                            'class' => 'unsubscribe',
2090                                                                            'action' => common_local_url('unsubscribe')));
2091         common_hidden('token', common_session_token());
2092         common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
2093                                                                   'name' => 'unsubscribeto',
2094                                                                   'type' => 'hidden',
2095                                                                   'value' => $profile->id));
2096         common_element('input', array('type' => 'submit',
2097                                                                   'class' => 'submit',
2098                                                                   'value' => _('Unsubscribe')));
2099         common_element_end('form');
2100 }
2101
2102 // XXX: Refactor this code
2103 function common_profile_new_message_nudge ($cur, $profile) {
2104         $user = User::staticGet('id', $profile->id);
2105
2106         if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2107         common_element_start('li', array('id' => 'profile_send_a_new_message'));
2108                 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2109                                            _('Send a message'));
2110         common_element_end('li');
2111
2112             if ($user->email && $user->emailnotifynudge) {
2113             common_element_start('li', array('id' => 'profile_nudge'));
2114             common_nudge_form($user);
2115             common_element_end('li');
2116         }
2117         }
2118 }
2119
2120 function common_cache_key($extra) {
2121         return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2122 }
2123
2124 function common_keyize($str) {
2125         $str = strtolower($str);
2126         $str = preg_replace('/\s/', '_', $str);
2127         return $str;
2128 }
2129
2130 function common_message_form($content, $user, $to) {
2131
2132         common_element_start('form', array('id' => 'message_form',
2133                                                                            'method' => 'post',
2134                                                                            'action' => common_local_url('newmessage')));
2135
2136         $mutual_users = $user->mutuallySubscribedUsers();
2137
2138         $mutual = array();
2139
2140         while ($mutual_users->fetch()) {
2141                 if ($mutual_users->id != $user->id) {
2142                         $mutual[$mutual_users->id] = $mutual_users->nickname;
2143                 }
2144         }
2145
2146         $mutual_users->free();
2147         unset($mutual_users);
2148
2149         common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
2150
2151         common_element_start('p');
2152
2153         common_element('textarea', array('id' => 'message_content',
2154                                                                          'cols' => 60,
2155                                                                          'rows' => 3,
2156                                                                          'name' => 'content'),
2157                                    ($content) ? $content : '');
2158
2159         common_element('input', array('id' => 'message_send',
2160                                                                   'name' => 'message_send',
2161                                                                   'type' => 'submit',
2162                                                                   'value' => _('Send')));
2163
2164         common_hidden('token', common_session_token());
2165
2166         common_element_end('p');
2167         common_element_end('form');
2168 }
2169
2170 function common_memcache() {
2171         static $cache = NULL;
2172         if (!common_config('memcached', 'enabled')) {
2173                 return NULL;
2174         } else {
2175                 if (!$cache) {
2176                         $cache = new Memcache();
2177                         $servers = common_config('memcached', 'server');
2178                         if (is_array($servers)) {
2179                                 foreach($servers as $server) {
2180                                         $cache->addServer($server);
2181                                 }
2182                         } else {
2183                                 $cache->addServer($servers);
2184                         }
2185                 }
2186                 return $cache;
2187         }
2188 }
2189
2190 function common_compatible_license($from, $to) {
2191         # XXX: better compatibility check needed here!
2192         return ($from == $to);
2193 }
2194
2195 /* These are almost identical, so we use a helper function */
2196
2197 function common_block_form($profile, $args=NULL) {
2198     common_blocking_form('block', _('Block'), $profile, $args);
2199 }
2200
2201 function common_unblock_form($profile, $args=NULL) {
2202     common_blocking_form('unblock', _('Unblock'), $profile, $args);
2203 }
2204
2205 function common_blocking_form($type, $label, $profile, $args=NULL) {
2206     common_element_start('form', array('id' => $type . '-' . $profile->id,
2207                                        'method' => 'post',
2208                                        'class' => $type,
2209                                        'action' => common_local_url($type)));
2210     common_hidden('token', common_session_token());
2211     common_element('input', array('id' => $type . 'to-' . $profile->id,
2212                                   'name' => $type . 'to',
2213                                   'type' => 'hidden',
2214                                   'value' => $profile->id));
2215     common_element('input', array('type' => 'submit',
2216                                   'class' => 'submit',
2217                                   'name' => $type,
2218                                   'value' => $label));
2219     if ($args) {
2220         foreach ($args as $k => $v) {
2221             common_hidden('returnto-' . $k, $v);
2222         }
2223     }
2224     common_element_end('form');
2225     return;
2226 }
2227