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