]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
common_warning() doesn't exist
[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);
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         $rm = new Remember_me();
616         $rm->code = common_good_rand(16);
617         $rm->user_id = $user->id;
618         $result = $rm->insert();
619         if (!$result) {
620                 common_log_db_error($rm, 'INSERT', __FILE__);
621                 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
622                 return false;
623         }
624         common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
625         common_set_cookie(REMEMBERME,
626                                           implode(':', array($rm->user_id, $rm->code)),
627                                           time() + REMEMBERME_EXPIRY);
628         return true;
629 }
630
631 function common_remembered_user() {
632
633         $user = NULL;
634
635         $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : NULL;
636
637         if (!$packed) {
638         return NULL;
639     }
640
641     list($id, $code) = explode(':', $packed);
642
643     if (!$id || !$code) {
644         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
645         common_forgetme();
646         return NULL;
647     }
648
649     $rm = Remember_me::staticGet($code);
650
651     if (!$rm) {
652         common_log(LOG_WARNING, 'No such remember code: ' . $code);
653         common_forgetme();
654         return NULL;
655     }
656
657     if ($rm->user_id != $id) {
658         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
659         common_forgetme();
660         return NULL;
661     }
662
663     $user = User::staticGet($rm->user_id);
664
665     if (!$user) {
666         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
667         common_forgetme();
668         return NULL;
669     }
670
671         # successful!
672     $result = $rm->delete();
673
674     if (!$result) {
675         common_log_db_error($rm, 'DELETE', __FILE__);
676         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
677         common_forgetme();
678         return NULL;
679     }
680
681     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
682
683     common_set_user($user);
684     common_real_login(false);
685
686     # We issue a new cookie, so they can log in
687     # automatically again after this session
688
689     common_rememberme($user);
690
691         return $user;
692 }
693
694 # must be called with a valid user!
695
696 function common_forgetme() {
697         common_set_cookie(REMEMBERME, '', 0);
698 }
699
700 # who is the current user?
701 function common_current_user() {
702     global $_cur;
703
704     if ($_cur === false) {
705
706         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
707             common_ensure_session();
708             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
709             if ($id) {
710                 $_cur = User::staticGet($id);
711                 return $_cur;
712             }
713         }
714
715         # that didn't work; try to remember; will init $_cur to NULL on failure
716         $_cur = common_remembered_user();
717
718         if ($_cur) {
719             common_debug("Got User " . $_cur->nickname);
720             common_debug("Faking session on remembered user");
721             # XXX: Is this necessary?
722             $_SESSION['userid'] = $_cur->id;
723         }
724     }
725
726         return $_cur;
727 }
728
729 # Logins that are 'remembered' aren't 'real' -- they're subject to
730 # cookie-stealing. So, we don't let them do certain things. New reg,
731 # OpenID, and password logins _are_ real.
732
733 function common_real_login($real=true) {
734         common_ensure_session();
735         $_SESSION['real_login'] = $real;
736 }
737
738 function common_is_real_login() {
739         return common_logged_in() && $_SESSION['real_login'];
740 }
741
742 # get canonical version of nickname for comparison
743 function common_canonical_nickname($nickname) {
744         # XXX: UTF-8 canonicalization (like combining chars)
745         return strtolower($nickname);
746 }
747
748 # get canonical version of email for comparison
749 function common_canonical_email($email) {
750         # XXX: canonicalize UTF-8
751         # XXX: lcase the domain part
752         return $email;
753 }
754
755 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$_+!*();/?:~-]))');
756
757 function common_render_content($text, $notice) {
758         $r = common_render_text($text);
759         $id = $notice->profile_id;
760         $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
761         $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
762         $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
763         return $r;
764 }
765
766 function common_render_text($text) {
767         $r = htmlspecialchars($text);
768
769         $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
770         $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
771         $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
772         # XXX: machine tags
773         return $r;
774 }
775
776 function common_render_uri_thingy($matches) {
777         $uri = $matches[0];
778         $trailer = '';
779
780         # Some heuristics for extracting URIs from surrounding punctuation
781         # Strip from trailing text...
782         if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
783                 $uri = $matches[1];
784                 $trailer = $matches[2];
785         }
786
787         $pairs = array(
788                 ']' => '[', # technically disallowed in URIs, but used in Java docs
789                 ')' => '(', # far too frequent in Wikipedia and MSDN
790         );
791         $final = substr($uri, -1, 1);
792         if (isset($pairs[$final])) {
793                 $openers = substr_count($uri, $pairs[$final]);
794                 $closers = substr_count($uri, $final);
795                 if ($closers > $openers) {
796                         // Assume the paren was opened outside the URI
797                         $uri = substr($uri, 0, -1);
798                         $trailer = $final . $trailer;
799                 }
800         }
801         if ($longurl = common_longurl($uri)) {
802                 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
803                 $title = " title='$longurl'";
804         }
805         else $title = '';
806
807         return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
808 }
809
810 function common_longurl($uri)  {
811         $uri_e = urlencode($uri);
812         $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
813         if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
814         return stripslashes($longurl['long_url']);
815 }
816
817 function common_shorten_links($text) {
818     // \s = not a horizontal whitespace character (since PHP 5.2.4)
819         // RYM this should prevent * preceded URLs from being processed but it its a char
820 //      $r = preg_replace('@[^*](https?://[^)\]>\s]+)@e', "common_shorten_link('\\1')", $r);
821         return preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
822 }
823
824 function common_shorten_link($long_url) {
825
826         $user = common_current_user();
827
828         $curlh = curl_init();
829         curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
830         curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
831         curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
832
833         switch($user->urlshorteningservice) {
834         case 'ur1.ca':
835             $short_url_service = new LilUrl;
836             $short_url = $short_url_service->shorten($long_url);
837             break;
838
839         case '2tu.us':
840             $short_url_service = new TightUrl;
841             $short_url = $short_url_service->shorten($long_url);
842             break;
843
844         case 'ptiturl.com':
845             $short_url_service = new PtitUrl;
846             $short_url = $short_url_service->shorten($long_url);
847             break;
848
849         case 'bit.ly':
850                         curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($long_url));
851                         $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
852             break;
853
854                 case 'is.gd':
855                         curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($long_url));
856                         $short_url = curl_exec($curlh);
857                         break;
858                 case 'snipr.com':
859                         curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($long_url));
860                         $short_url = curl_exec($curlh);
861                         break;
862                 case 'metamark.net':
863                         curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($long_url));
864                         $short_url = curl_exec($curlh);
865                         break;
866                 case 'tinyurl.com':
867                         curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($long_url));
868                         $short_url = curl_exec($curlh);
869                         break;
870                 default:
871                         $short_url = false;
872         }
873
874         curl_close($curlh);
875
876         if ($short_url) {
877                 return $short_url;
878         }
879         return $long_url;
880 }
881
882 function common_xml_safe_str($str) {
883         $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
884
885         // Replace control, formatting, and surrogate characters with '*', ala Twitter
886         return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
887 }
888
889 function common_tag_link($tag) {
890         $canonical = common_canonical_tag($tag);
891         $url = common_local_url('tag', array('tag' => $canonical));
892         return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
893 }
894
895 function common_canonical_tag($tag) {
896         return strtolower(str_replace(array('-', '_', '.'), '', $tag));
897 }
898
899 function common_valid_profile_tag($str) {
900         return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
901 }
902
903 function common_at_link($sender_id, $nickname) {
904         $sender = Profile::staticGet($sender_id);
905         $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
906         if ($recipient) {
907                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
908         } else {
909                 return $nickname;
910         }
911 }
912
913 function common_at_hash_link($sender_id, $tag) {
914         $user = User::staticGet($sender_id);
915         if (!$user) {
916                 return $tag;
917         }
918         $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
919         if ($tagged) {
920                 $url = common_local_url('subscriptions',
921                                                                 array('nickname' => $user->nickname,
922                                                                           'tag' => $tag));
923                 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
924         } else {
925                 return $tag;
926         }
927 }
928
929 function common_relative_profile($sender, $nickname, $dt=NULL) {
930         # Try to find profiles this profile is subscribed to that have this nickname
931         $recipient = new Profile();
932         # XXX: use a join instead of a subquery
933         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
934         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
935         if ($recipient->find(TRUE)) {
936                 # XXX: should probably differentiate between profiles with
937                 # the same name by date of most recent update
938                 return $recipient;
939         }
940         # Try to find profiles that listen to this profile and that have this nickname
941         $recipient = new Profile();
942         # XXX: use a join instead of a subquery
943         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
944         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
945         if ($recipient->find(TRUE)) {
946                 # XXX: should probably differentiate between profiles with
947                 # the same name by date of most recent update
948                 return $recipient;
949         }
950         # If this is a local user, try to find a local user with that nickname.
951         $sender = User::staticGet($sender->id);
952         if ($sender) {
953                 $recipient_user = User::staticGet('nickname', $nickname);
954                 if ($recipient_user) {
955                         return $recipient_user->getProfile();
956                 }
957         }
958         # Otherwise, no links. @messages from local users to remote users,
959         # or from remote users to other remote users, are just
960         # outside our ability to make intelligent guesses about
961         return NULL;
962 }
963
964 // where should the avatar go for this user?
965
966 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
967         global $config;
968
969         if ($size) {
970                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
971         } else {
972                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
973         }
974 }
975
976 function common_avatar_path($filename) {
977         global $config;
978         return INSTALLDIR . '/avatar/' . $filename;
979 }
980
981 function common_avatar_url($filename) {
982         return common_path('avatar/'.$filename);
983 }
984
985 function common_avatar_display_url($avatar) {
986         $server = common_config('avatar', 'server');
987         if ($server) {
988                 return 'http://'.$server.'/'.$avatar->filename;
989         } else {
990                 return $avatar->url;
991         }
992 }
993
994 function common_default_avatar($size) {
995         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
996                                                           AVATAR_STREAM_SIZE => 'stream',
997                                                           AVATAR_MINI_SIZE => 'mini');
998         return theme_path('default-avatar-'.$sizenames[$size].'.png');
999 }
1000
1001 function common_local_url($action, $args=NULL, $fragment=NULL) {
1002         $url = NULL;
1003         if (common_config('site','fancy')) {
1004                 $url = common_fancy_url($action, $args);
1005         } else {
1006                 $url = common_simple_url($action, $args);
1007         }
1008         if (!is_null($fragment)) {
1009                 $url .= '#'.$fragment;
1010         }
1011         return $url;
1012 }
1013
1014 function common_fancy_url($action, $args=NULL) {
1015         switch (strtolower($action)) {
1016          case 'public':
1017                 if ($args && isset($args['page'])) {
1018                         return common_path('?page=' . $args['page']);
1019                 } else {
1020                         return common_path('');
1021                 }
1022          case 'featured':
1023                 if ($args && isset($args['page'])) {
1024                         return common_path('featured?page=' . $args['page']);
1025                 } else {
1026                         return common_path('featured');
1027                 }
1028          case 'favorited':
1029                 if ($args && isset($args['page'])) {
1030                         return common_path('favorited?page=' . $args['page']);
1031                 } else {
1032                         return common_path('favorited');
1033                 }
1034          case 'publicrss':
1035                 return common_path('rss');
1036          case 'publicxrds':
1037                 return common_path('xrds');
1038          case 'featuredrss':
1039                 return common_path('featuredrss');
1040          case 'favoritedrss':
1041                 return common_path('favoritedrss');
1042          case 'opensearch':
1043                 if ($args && $args['type']) {
1044                         return common_path('opensearch/'.$args['type']);
1045                 } else {
1046                         return common_path('opensearch/people');
1047                 }
1048          case 'doc':
1049                 return common_path('doc/'.$args['title']);
1050          case 'login':
1051          case 'logout':
1052          case 'subscribe':
1053          case 'unsubscribe':
1054          case 'invite':
1055                 return common_path('main/'.$action);
1056          case 'tagother':
1057                 return common_path('main/tagother?id='.$args['id']);
1058          case 'register':
1059                 if ($args && $args['code']) {
1060                         return common_path('main/register/'.$args['code']);
1061                 } else {
1062                         return common_path('main/register');
1063                 }
1064          case 'remotesubscribe':
1065                 if ($args && $args['nickname']) {
1066                         return common_path('main/remote?nickname=' . $args['nickname']);
1067                 } else {
1068                         return common_path('main/remote');
1069                 }
1070          case 'nudge':
1071                 return common_path($args['nickname'].'/nudge');
1072          case 'openidlogin':
1073                 return common_path('main/openid');
1074          case 'profilesettings':
1075                 return common_path('settings/profile');
1076          case 'emailsettings':
1077                 return common_path('settings/email');
1078          case 'openidsettings':
1079                 return common_path('settings/openid');
1080          case 'smssettings':
1081                 return common_path('settings/sms');
1082          case 'twittersettings':
1083                 return common_path('settings/twitter');
1084          case 'othersettings':
1085                 return common_path('settings/other');
1086          case 'newnotice':
1087                 if ($args && $args['replyto']) {
1088                         return common_path('notice/new?replyto='.$args['replyto']);
1089                 } else {
1090                         return common_path('notice/new');
1091                 }
1092          case 'shownotice':
1093                 return common_path('notice/'.$args['notice']);
1094          case 'deletenotice':
1095                 if ($args && $args['notice']) {
1096                         return common_path('notice/delete/'.$args['notice']);
1097                 } else {
1098                         return common_path('notice/delete');
1099                 }
1100          case 'microsummary':
1101          case 'xrds':
1102          case 'foaf':
1103                 return common_path($args['nickname'].'/'.$action);
1104          case 'all':
1105          case 'replies':
1106          case 'inbox':
1107          case 'outbox':
1108                 if ($args && isset($args['page'])) {
1109                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1110                 } else {
1111                         return common_path($args['nickname'].'/'.$action);
1112                 }
1113          case 'subscriptions':
1114          case 'subscribers':
1115                 $nickname = $args['nickname'];
1116                 unset($args['nickname']);
1117                 if (isset($args['tag'])) {
1118                         $tag = $args['tag'];
1119                         unset($args['tag']);
1120                 }
1121                 $params = http_build_query($args);
1122                 if ($params) {
1123                         return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1124                 } else {
1125                         return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1126                 }
1127          case 'allrss':
1128                 return common_path($args['nickname'].'/all/rss');
1129          case 'repliesrss':
1130                 return common_path($args['nickname'].'/replies/rss');
1131          case 'userrss':
1132                 return common_path($args['nickname'].'/rss');
1133          case 'showstream':
1134                 if ($args && isset($args['page'])) {
1135                         return common_path($args['nickname'].'?page=' . $args['page']);
1136                 } else {
1137                         return common_path($args['nickname']);
1138                 }
1139
1140          case 'usertimeline':
1141                 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1142          case 'confirmaddress':
1143                 return common_path('main/confirmaddress/'.$args['code']);
1144          case 'userbyid':
1145                 return common_path('user/'.$args['id']);
1146          case 'recoverpassword':
1147             $path = 'main/recoverpassword';
1148             if ($args['code']) {
1149                 $path .= '/' . $args['code'];
1150                 }
1151             return common_path($path);
1152          case 'imsettings':
1153                 return common_path('settings/im');
1154          case 'peoplesearch':
1155                 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1156          case 'noticesearch':
1157                 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1158          case 'noticesearchrss':
1159                 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1160          case 'avatarbynickname':
1161                 return common_path($args['nickname'].'/avatar/'.$args['size']);
1162          case 'tag':
1163             if (isset($args['tag']) && $args['tag']) {
1164                         $path = 'tag/' . $args['tag'];
1165                         unset($args['tag']);
1166                 } else {
1167                         $path = 'tags';
1168                 }
1169                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1170          case 'peopletag':
1171                 $path = 'peopletag/' . $args['tag'];
1172                 unset($args['tag']);
1173                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1174          case 'tags':
1175                 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1176          case 'favor':
1177                 return common_path('main/favor');
1178          case 'disfavor':
1179                 return common_path('main/disfavor');
1180          case 'showfavorites':
1181                 if ($args && isset($args['page'])) {
1182                         return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1183                 } else {
1184                         return common_path($args['nickname'].'/favorites');
1185                 }
1186          case 'favoritesrss':
1187                 return common_path($args['nickname'].'/favorites/rss');
1188          case 'showmessage':
1189                 return common_path('message/' . $args['message']);
1190          case 'newmessage':
1191                 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1192          case 'api':
1193                 # XXX: do fancy URLs for all the API methods
1194                 switch (strtolower($args['apiaction'])) {
1195                  case 'statuses':
1196                         switch (strtolower($args['method'])) {
1197                          case 'user_timeline.rss':
1198                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1199                          case 'user_timeline.atom':
1200                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1201                          case 'user_timeline.json':
1202                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1203                          case 'user_timeline.xml':
1204                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1205                          default: return common_simple_url($action, $args);
1206                         }
1207                  default: return common_simple_url($action, $args);
1208                 }
1209          case 'sup':
1210                 if ($args && isset($args['seconds'])) {
1211                         return common_path('main/sup?seconds='.$args['seconds']);
1212                 } else {
1213                         return common_path('main/sup');
1214                 }
1215          default:
1216                 return common_simple_url($action, $args);
1217         }
1218 }
1219
1220 function common_simple_url($action, $args=NULL) {
1221         global $config;
1222         /* XXX: pretty URLs */
1223         $extra = '';
1224         if ($args) {
1225                 foreach ($args as $key => $value) {
1226                         $extra .= "&${key}=${value}";
1227                 }
1228         }
1229         return common_path("index.php?action=${action}${extra}");
1230 }
1231
1232 function common_path($relative) {
1233         global $config;
1234         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1235         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1236 }
1237
1238 function common_date_string($dt) {
1239         // XXX: do some sexy date formatting
1240         // return date(DATE_RFC822, $dt);
1241         $t = strtotime($dt);
1242         $now = time();
1243         $diff = $now - $t;
1244
1245         if ($now < $t) { # that shouldn't happen!
1246                 return common_exact_date($dt);
1247         } else if ($diff < 60) {
1248                 return _('a few seconds ago');
1249         } else if ($diff < 92) {
1250                 return _('about a minute ago');
1251         } else if ($diff < 3300) {
1252                 return sprintf(_('about %d minutes ago'), round($diff/60));
1253         } else if ($diff < 5400) {
1254                 return _('about an hour ago');
1255         } else if ($diff < 22 * 3600) {
1256                 return sprintf(_('about %d hours ago'), round($diff/3600));
1257         } else if ($diff < 37 * 3600) {
1258                 return _('about a day ago');
1259         } else if ($diff < 24 * 24 * 3600) {
1260                 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1261         } else if ($diff < 46 * 24 * 3600) {
1262                 return _('about a month ago');
1263         } else if ($diff < 330 * 24 * 3600) {
1264                 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1265         } else if ($diff < 480 * 24 * 3600) {
1266                 return _('about a year ago');
1267         } else {
1268                 return common_exact_date($dt);
1269         }
1270 }
1271
1272 function common_exact_date($dt) {
1273     static $_utc;
1274     static $_siteTz;
1275
1276     if (!$_utc) {
1277         $_utc = new DateTimeZone('UTC');
1278         $_siteTz = new DateTimeZone(common_timezone());
1279     }
1280
1281         $dateStr = date('d F Y H:i:s', strtotime($dt));
1282         $d = new DateTime($dateStr, $_utc);
1283         $d->setTimezone($_siteTz);
1284         return $d->format(DATE_RFC850);
1285 }
1286
1287 function common_date_w3dtf($dt) {
1288         $dateStr = date('d F Y H:i:s', strtotime($dt));
1289         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1290         $d->setTimezone(new DateTimeZone(common_timezone()));
1291         return $d->format(DATE_W3C);
1292 }
1293
1294 function common_date_rfc2822($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('r');
1299 }
1300
1301 function common_date_iso8601($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('c');
1306 }
1307
1308 function common_sql_now() {
1309         return strftime('%Y-%m-%d %H:%M:%S', time());
1310 }
1311
1312 function common_redirect($url, $code=307) {
1313         static $status = array(301 => "Moved Permanently",
1314                                                    302 => "Found",
1315                                                    303 => "See Other",
1316                                                    307 => "Temporary Redirect");
1317         header("Status: ${code} $status[$code]");
1318         header("Location: $url");
1319
1320         common_start_xml('a',
1321                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
1322                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1323         common_element('a', array('href' => $url), $url);
1324         common_end_xml();
1325     exit;
1326 }
1327
1328 function common_save_replies($notice) {
1329         # Alternative reply format
1330         $tname = false;
1331         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1332                 $tname = $match[1];
1333         }
1334         # extract all @messages
1335         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1336
1337         $names = array();
1338
1339         if ($cnt || $tname) {
1340                 # XXX: is there another way to make an array copy?
1341                 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1342         }
1343
1344         $sender = Profile::staticGet($notice->profile_id);
1345
1346         $replied = array();
1347
1348         # store replied only for first @ (what user/notice what the reply directed,
1349         # we assume first @ is it)
1350
1351         for ($i=0; $i<count($names); $i++) {
1352                 $nickname = $names[$i];
1353                 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1354                 if (!$recipient) {
1355                         continue;
1356                 }
1357                 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1358                         $reply_for = $recipient;
1359                         $recipient_notice = $reply_for->getCurrentNotice();
1360                         if ($recipient_notice) {
1361                                 $orig = clone($notice);
1362                                 $notice->reply_to = $recipient_notice->id;
1363                                 $notice->update($orig);
1364                         }
1365                 }
1366                 $reply = new Reply();
1367                 $reply->notice_id = $notice->id;
1368                 $reply->profile_id = $recipient->id;
1369                 $id = $reply->insert();
1370                 if (!$id) {
1371                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1372                         common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1373                         common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1374                         return;
1375                 } else {
1376                         $replied[$recipient->id] = 1;
1377                 }
1378         }
1379
1380         # Hash format replies, too
1381         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1382         if ($cnt) {
1383                 foreach ($match[1] as $tag) {
1384                         $tagged = Profile_tag::getTagged($sender->id, $tag);
1385                         foreach ($tagged as $t) {
1386                                 if (!$replied[$t->id]) {
1387                                         $reply = new Reply();
1388                                         $reply->notice_id = $notice->id;
1389                                         $reply->profile_id = $t->id;
1390                                         $id = $reply->insert();
1391                                         if (!$id) {
1392                                                 common_log_db_error($reply, 'INSERT', __FILE__);
1393                                                 return;
1394                                         }
1395                                 }
1396                         }
1397                 }
1398         }
1399 }
1400
1401 function common_broadcast_notice($notice, $remote=false) {
1402
1403         // Check to see if notice should go to Twitter
1404         $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1405         if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1406
1407                 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1408
1409                 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1410                         (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1411
1412                         $result = common_twitter_broadcast($notice, $flink);
1413
1414                         if (!$result) {
1415                                 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1416                         }
1417                 }
1418         }
1419
1420         if (common_config('queue', 'enabled')) {
1421                 # Do it later!
1422                 return common_enqueue_notice($notice);
1423         } else {
1424                 return common_real_broadcast($notice, $remote);
1425         }
1426 }
1427
1428 function common_twitter_broadcast($notice, $flink) {
1429         global $config;
1430         $success = true;
1431         $fuser = $flink->getForeignUser();
1432         $twitter_user = $fuser->nickname;
1433         $twitter_password = $flink->credentials;
1434         $uri = 'http://www.twitter.com/statuses/update.json';
1435
1436         // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1437         $statustxt = preg_replace('/^@/', ' @', $notice->content);
1438
1439         $options = array(
1440                 CURLOPT_USERPWD                 => "$twitter_user:$twitter_password",
1441                 CURLOPT_POST                    => true,
1442                 CURLOPT_POSTFIELDS              => array(
1443                                                                         'status'        => $statustxt,
1444                                                                         'source'        => $config['integration']['source']
1445                                                                         ),
1446                 CURLOPT_RETURNTRANSFER  => true,
1447                 CURLOPT_FAILONERROR             => true,
1448                 CURLOPT_HEADER                  => false,
1449                 CURLOPT_FOLLOWLOCATION  => true,
1450                 CURLOPT_USERAGENT               => "Laconica",
1451                 CURLOPT_CONNECTTIMEOUT  => 120,  // XXX: Scary!!!! How long should this be?
1452                 CURLOPT_TIMEOUT                 => 120
1453         );
1454
1455         $ch = curl_init($uri);
1456     curl_setopt_array($ch, $options);
1457     $data = curl_exec($ch);
1458     $errmsg = curl_error($ch);
1459
1460         if ($errmsg) {
1461                 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1462                         __FILE__);
1463                 $success = false;
1464         }
1465
1466         curl_close($ch);
1467
1468         if (!$data) {
1469                 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1470                         __FILE__);
1471                 $success = false;
1472         }
1473
1474         // Twitter should return a status
1475         $status = json_decode($data);
1476
1477         if (!$status->id) {
1478                 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1479                         __FILE__);
1480                 $success = false;
1481         }
1482
1483         return $success;
1484 }
1485
1486 # Stick the notice on the queue
1487
1488 function common_enqueue_notice($notice) {
1489         foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1490                 $qi = new Queue_item();
1491                 $qi->notice_id = $notice->id;
1492                 $qi->transport = $transport;
1493                 $qi->created = $notice->created;
1494         $result = $qi->insert();
1495                 if (!$result) {
1496                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1497                         common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1498                         return false;
1499                 }
1500                 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1501         }
1502         return $result;
1503 }
1504
1505 function common_dequeue_notice($notice) {
1506         $qi = Queue_item::staticGet($notice->id);
1507         if ($qi) {
1508                 $result = $qi->delete();
1509                 if (!$result) {
1510                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1511                     common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1512                     return false;
1513                 }
1514                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1515                 return $result;
1516         } else {
1517             return false;
1518         }
1519 }
1520
1521 function common_real_broadcast($notice, $remote=false) {
1522         $success = true;
1523         if (!$remote) {
1524                 # Make sure we have the OMB stuff
1525                 require_once(INSTALLDIR.'/lib/omb.php');
1526                 $success = omb_broadcast_remote_subscribers($notice);
1527                 if (!$success) {
1528                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1529                 }
1530         }
1531         if ($success) {
1532                 require_once(INSTALLDIR.'/lib/jabber.php');
1533                 $success = jabber_broadcast_notice($notice);
1534                 if (!$success) {
1535                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1536                 }
1537         }
1538         if ($success) {
1539                 require_once(INSTALLDIR.'/lib/mail.php');
1540                 $success = mail_broadcast_notice_sms($notice);
1541                 if (!$success) {
1542                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1543                 }
1544         }
1545         if ($success) {
1546                 $success = jabber_public_notice($notice);
1547                 if (!$success) {
1548                         common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1549                 }
1550         }
1551         // XXX: broadcast notices to other IM
1552         return $success;
1553 }
1554
1555 function common_broadcast_profile($profile) {
1556         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1557         require_once(INSTALLDIR.'/lib/omb.php');
1558         omb_broadcast_profile($profile);
1559         // XXX: Other broadcasts...?
1560         return true;
1561 }
1562
1563 function common_profile_url($nickname) {
1564         return common_local_url('showstream', array('nickname' => $nickname));
1565 }
1566
1567 # Don't call if nobody's logged in
1568
1569 function common_notice_form($action=NULL, $content=NULL) {
1570         $user = common_current_user();
1571         assert(!is_null($user));
1572         common_element_start('form', array('id' => 'status_form',
1573                                                                            'method' => 'post',
1574                                                                            'action' => common_local_url('newnotice')));
1575         common_element_start('p');
1576         common_element('label', array('for' => 'status_textarea',
1577                                                                   'id' => 'status_label'),
1578                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1579     common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1580         common_element('textarea', array('id' => 'status_textarea',
1581                                                                          'cols' => 60,
1582                                                                          'rows' => 3,
1583                                                                          'name' => 'status_textarea'),
1584                                    ($content) ? $content : '');
1585         common_hidden('token', common_session_token());
1586         if ($action) {
1587                 common_hidden('returnto', $action);
1588         }
1589         # set by JavaScript
1590         common_hidden('inreplyto', 'false');
1591         common_element('input', array('id' => 'status_submit',
1592                                                                   'name' => 'status_submit',
1593                                                                   'type' => 'submit',
1594                                                                   'value' => _('Send')));
1595         common_element_end('p');
1596         common_element_end('form');
1597 }
1598
1599 # Should make up a reasonable root URL
1600
1601 function common_root_url() {
1602         return common_path('');
1603 }
1604
1605 # returns $bytes bytes of random data as a hexadecimal string
1606 # "good" here is a goal and not a guarantee
1607
1608 function common_good_rand($bytes) {
1609         # XXX: use random.org...?
1610         if (file_exists('/dev/urandom')) {
1611                 return common_urandom($bytes);
1612         } else { # FIXME: this is probably not good enough
1613                 return common_mtrand($bytes);
1614         }
1615 }
1616
1617 function common_urandom($bytes) {
1618         $h = fopen('/dev/urandom', 'rb');
1619         # should not block
1620         $src = fread($h, $bytes);
1621         fclose($h);
1622         $enc = '';
1623         for ($i = 0; $i < $bytes; $i++) {
1624                 $enc .= sprintf("%02x", (ord($src[$i])));
1625         }
1626         return $enc;
1627 }
1628
1629 function common_mtrand($bytes) {
1630         $enc = '';
1631         for ($i = 0; $i < $bytes; $i++) {
1632                 $enc .= sprintf("%02x", mt_rand(0, 255));
1633         }
1634         return $enc;
1635 }
1636
1637 function common_set_returnto($url) {
1638         common_ensure_session();
1639         $_SESSION['returnto'] = $url;
1640 }
1641
1642 function common_get_returnto() {
1643         common_ensure_session();
1644         return $_SESSION['returnto'];
1645 }
1646
1647 function common_timestamp() {
1648         return date('YmdHis');
1649 }
1650
1651 function common_ensure_syslog() {
1652         static $initialized = false;
1653         if (!$initialized) {
1654                 global $config;
1655                 openlog($config['syslog']['appname'], 0, LOG_USER);
1656                 $initialized = true;
1657         }
1658 }
1659
1660 function common_log($priority, $msg, $filename=NULL) {
1661         $logfile = common_config('site', 'logfile');
1662         if ($logfile) {
1663                 $log = fopen($logfile, "a");
1664                 if ($log) {
1665                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1666                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1667                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1668                         fwrite($log, $output);
1669                         fclose($log);
1670                 }
1671         } else {
1672                 common_ensure_syslog();
1673                 syslog($priority, $msg);
1674         }
1675 }
1676
1677 function common_debug($msg, $filename=NULL) {
1678         if ($filename) {
1679                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1680         } else {
1681                 common_log(LOG_DEBUG, $msg);
1682         }
1683 }
1684
1685 function common_log_db_error(&$object, $verb, $filename=NULL) {
1686         $objstr = common_log_objstring($object);
1687         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1688         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1689 }
1690
1691 function common_log_objstring(&$object) {
1692         if (is_null($object)) {
1693                 return "NULL";
1694         }
1695         $arr = $object->toArray();
1696         $fields = array();
1697         foreach ($arr as $k => $v) {
1698                 $fields[] = "$k='$v'";
1699         }
1700         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1701         return $objstring;
1702 }
1703
1704 function common_valid_http_url($url) {
1705         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1706 }
1707
1708 function common_valid_tag($tag) {
1709         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1710                 return (Validate::email($matches[1]) ||
1711                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1712         }
1713         return false;
1714 }
1715
1716 # Does a little before-after block for next/prev page
1717
1718 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1719
1720         if ($have_before || $have_after) {
1721                 common_element_start('div', array('id' => 'pagination'));
1722                 common_element_start('ul', array('id' => 'nav_pagination'));
1723         }
1724
1725         if ($have_before) {
1726                 $pargs = array('page' => $page-1);
1727                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1728
1729                 common_element_start('li', 'before');
1730                 common_element('a', array('href' => common_local_url($action, $newargs)),
1731                                            _('« After'));
1732                 common_element_end('li');
1733         }
1734
1735         if ($have_after) {
1736                 $pargs = array('page' => $page+1);
1737                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1738                 common_element_start('li', 'after');
1739                 common_element('a', array('href' => common_local_url($action, $newargs)),
1740                                                    _('Before Â»'));
1741                 common_element_end('li');
1742         }
1743
1744         if ($have_before || $have_after) {
1745                 common_element_end('ul');
1746                 common_element_end('div');
1747         }
1748 }
1749
1750 /* Following functions are copied from MediaWiki GlobalFunctions.php
1751  * and written by Evan Prodromou. */
1752
1753 function common_accept_to_prefs($accept, $def = '*/*') {
1754         # No arg means accept anything (per HTTP spec)
1755         if(!$accept) {
1756                 return array($def => 1);
1757         }
1758
1759         $prefs = array();
1760
1761         $parts = explode(',', $accept);
1762
1763         foreach($parts as $part) {
1764                 # FIXME: doesn't deal with params like 'text/html; level=1'
1765                 @list($value, $qpart) = explode(';', $part);
1766                 $match = array();
1767                 if(!isset($qpart)) {
1768                         $prefs[$value] = 1;
1769                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1770                         $prefs[$value] = $match[1];
1771                 }
1772         }
1773
1774         return $prefs;
1775 }
1776
1777 function common_mime_type_match($type, $avail) {
1778         if(array_key_exists($type, $avail)) {
1779                 return $type;
1780         } else {
1781                 $parts = explode('/', $type);
1782                 if(array_key_exists($parts[0] . '/*', $avail)) {
1783                         return $parts[0] . '/*';
1784                 } elseif(array_key_exists('*/*', $avail)) {
1785                         return '*/*';
1786                 } else {
1787                         return NULL;
1788                 }
1789         }
1790 }
1791
1792 function common_negotiate_type($cprefs, $sprefs) {
1793         $combine = array();
1794
1795         foreach(array_keys($sprefs) as $type) {
1796                 $parts = explode('/', $type);
1797                 if($parts[1] != '*') {
1798                         $ckey = common_mime_type_match($type, $cprefs);
1799                         if($ckey) {
1800                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1801                         }
1802                 }
1803         }
1804
1805         foreach(array_keys($cprefs) as $type) {
1806                 $parts = explode('/', $type);
1807                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1808                         $skey = common_mime_type_match($type, $sprefs);
1809                         if($skey) {
1810                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1811                         }
1812                 }
1813         }
1814
1815         $bestq = 0;
1816         $besttype = "text/html";
1817
1818         foreach(array_keys($combine) as $type) {
1819                 if($combine[$type] > $bestq) {
1820                         $besttype = $type;
1821                         $bestq = $combine[$type];
1822                 }
1823         }
1824
1825         return $besttype;
1826 }
1827
1828 function common_config($main, $sub) {
1829         global $config;
1830         return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1831 }
1832
1833 function common_copy_args($from) {
1834         $to = array();
1835         $strip = get_magic_quotes_gpc();
1836         foreach ($from as $k => $v) {
1837                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1838         }
1839         return $to;
1840 }
1841
1842 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1843 // This is used before handing a request off to OAuthRequest::from_request.
1844 function common_remove_magic_from_request() {
1845         if(get_magic_quotes_gpc()) {
1846                 $_POST=array_map('stripslashes',$_POST);
1847                 $_GET=array_map('stripslashes',$_GET);
1848         }
1849 }
1850
1851 function common_user_uri(&$user) {
1852         return common_local_url('userbyid', array('id' => $user->id));
1853 }
1854
1855 function common_notice_uri(&$notice) {
1856         return common_local_url('shownotice',
1857                 array('notice' => $notice->id));
1858 }
1859
1860 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1861
1862 function common_confirmation_code($bits) {
1863         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1864         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1865         $chars = ceil($bits/5);
1866         $code = '';
1867         for ($i = 0; $i < $chars; $i++) {
1868                 # XXX: convert to string and back
1869                 $num = hexdec(common_good_rand(1));
1870                 # XXX: randomness is too precious to throw away almost
1871                 # 40% of the bits we get!
1872                 $code .= $codechars[$num%32];
1873         }
1874         return $code;
1875 }
1876
1877 # convert markup to HTML
1878
1879 function common_markup_to_html($c) {
1880         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1881         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1882         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1883         return Markdown($c);
1884 }
1885
1886 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1887         $avatar = $profile->getAvatar($size);
1888         if ($avatar) {
1889                 return common_avatar_display_url($avatar);
1890         } else {
1891                 return common_default_avatar($size);
1892         }
1893 }
1894
1895 function common_profile_uri($profile) {
1896         if (!$profile) {
1897                 return NULL;
1898         }
1899         $user = User::staticGet($profile->id);
1900         if ($user) {
1901                 return $user->uri;
1902         }
1903
1904         $remote = Remote_profile::staticGet($profile->id);
1905         if ($remote) {
1906                 return $remote->uri;
1907         }
1908         # XXX: this is a very bad profile!
1909         return NULL;
1910 }
1911
1912 function common_canonical_sms($sms) {
1913         # strip non-digits
1914         preg_replace('/\D/', '', $sms);
1915         return $sms;
1916 }
1917
1918 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1919     switch ($errno) {
1920      case E_USER_ERROR:
1921                 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1922                 exit(1);
1923                 break;
1924
1925          case E_USER_WARNING:
1926                 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1927                 break;
1928
1929      case E_USER_NOTICE:
1930                 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1931                 break;
1932     }
1933
1934         # FIXME: show error page if we're on the Web
1935     /* Don't execute PHP internal error handler */
1936     return true;
1937 }
1938
1939 function common_session_token() {
1940         common_ensure_session();
1941         if (!array_key_exists('token', $_SESSION)) {
1942                 $_SESSION['token'] = common_good_rand(64);
1943         }
1944         return $_SESSION['token'];
1945 }
1946
1947 function common_disfavor_form($notice) {
1948         common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1949                                                                            'method' => 'post',
1950                                                                            'class' => 'disfavor',
1951                                                                            'action' => common_local_url('disfavor')));
1952
1953         common_element('input', array('type' => 'hidden',
1954                                                                   'name' => 'token-'. $notice->id,
1955                                                                   'id' => 'token-'. $notice->id,
1956                                                                   'class' => 'token',
1957                                                                   'value' => common_session_token()));
1958
1959         common_element('input', array('type' => 'hidden',
1960                                                                   'name' => 'notice',
1961                                                                   'id' => 'notice-n'. $notice->id,
1962                                                                   'class' => 'notice',
1963                                                                   'value' => $notice->id));
1964
1965         common_element('input', array('type' => 'submit',
1966                                                                   'id' => 'disfavor-submit-' . $notice->id,
1967                                                                   'name' => 'disfavor-submit-' . $notice->id,
1968                                                                   'class' => 'disfavor',
1969                                                                   'value' => 'Disfavor favorite',
1970                                                                   'title' => 'Remove this message from favorites'));
1971         common_element_end('form');
1972 }
1973
1974 function common_favor_form($notice) {
1975         common_element_start('form', array('id' => 'favor-' . $notice->id,
1976                                                                            'method' => 'post',
1977                                                                            'class' => 'favor',
1978                                                                            'action' => common_local_url('favor')));
1979
1980         common_element('input', array('type' => 'hidden',
1981                                                                   'name' => 'token-'. $notice->id,
1982                                                                   'id' => 'token-'. $notice->id,
1983                                                                   'class' => 'token',
1984                                                                   'value' => common_session_token()));
1985
1986         common_element('input', array('type' => 'hidden',
1987                                                                   'name' => 'notice',
1988                                                                   'id' => 'notice-n'. $notice->id,
1989                                                                   'class' => 'notice',
1990                                                                   'value' => $notice->id));
1991
1992         common_element('input', array('type' => 'submit',
1993                                                                   'id' => 'favor-submit-' . $notice->id,
1994                                                                   'name' => 'favor-submit-' . $notice->id,
1995                                                                   'class' => 'favor',
1996                                                                   'value' => 'Add to favorites',
1997                                                                   'title' => 'Add this message to favorites'));
1998         common_element_end('form');
1999 }
2000
2001 function common_nudge_form($profile) {
2002         common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2003                                                                            'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2004         common_hidden('token', common_session_token());
2005         common_element('input', array('type' => 'submit',
2006                                                                   'class' => 'submit',
2007                                                                   'value' => _('Send a nudge')));
2008         common_element_end('form');
2009 }
2010 function common_nudge_response() {
2011         common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2012 }
2013
2014 function common_subscribe_form($profile) {
2015         common_element_start('form', array('id' => 'subscribe-' . $profile->nickname,
2016                                                                            'method' => 'post',
2017                                                                            'class' => 'subscribe',
2018                                                                            'action' => common_local_url('subscribe')));
2019         common_hidden('token', common_session_token());
2020         common_element('input', array('id' => 'subscribeto-' . $profile->nickname,
2021                                                                   'name' => 'subscribeto',
2022                                                                   'type' => 'hidden',
2023                                                                   'value' => $profile->nickname));
2024         common_element('input', array('type' => 'submit',
2025                                                                   'class' => 'submit',
2026                                                                   'value' => _('Subscribe')));
2027         common_element_end('form');
2028 }
2029
2030 function common_unsubscribe_form($profile) {
2031         common_element_start('form', array('id' => 'unsubscribe-' . $profile->nickname,
2032                                                                            'method' => 'post',
2033                                                                            'class' => 'unsubscribe',
2034                                                                            'action' => common_local_url('unsubscribe')));
2035         common_hidden('token', common_session_token());
2036         common_element('input', array('id' => 'unsubscribeto-' . $profile->nickname,
2037                                                                   'name' => 'unsubscribeto',
2038                                                                   'type' => 'hidden',
2039                                                                   'value' => $profile->nickname));
2040         common_element('input', array('type' => 'submit',
2041                                                                   'class' => 'submit',
2042                                                                   'value' => _('Unsubscribe')));
2043         common_element_end('form');
2044 }
2045
2046 // XXX: Refactor this code
2047 function common_profile_new_message_nudge ($cur, $profile) {
2048         $user = User::staticGet('id', $profile->id);
2049
2050         if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2051         common_element_start('li', array('id' => 'profile_send_a_new_message'));
2052                 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2053                                            _('Send a message'));
2054         common_element_end('li');
2055
2056             if ($user->email && $user->emailnotifynudge) {
2057             common_element_start('li', array('id' => 'profile_nudge'));
2058             common_nudge_form($user);
2059             common_element_end('li');
2060         }
2061         }
2062 }
2063
2064 function common_cache_key($extra) {
2065         return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2066 }
2067
2068 function common_keyize($str) {
2069         $str = strtolower($str);
2070         $str = preg_replace('/\s/', '_', $str);
2071         return $str;
2072 }
2073
2074 function common_message_form($content, $user, $to) {
2075
2076         common_element_start('form', array('id' => 'message_form',
2077                                                                            'method' => 'post',
2078                                                                            'action' => common_local_url('newmessage')));
2079
2080         $mutual_users = $user->mutuallySubscribedUsers();
2081
2082         $mutual = array();
2083
2084         while ($mutual_users->fetch()) {
2085                 if ($mutual_users->id != $user->id) {
2086                         $mutual[$mutual_users->id] = $mutual_users->nickname;
2087                 }
2088         }
2089
2090         $mutual_users->free();
2091         unset($mutual_users);
2092
2093         common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
2094
2095         common_element_start('p');
2096
2097         common_element('textarea', array('id' => 'message_content',
2098                                                                          'cols' => 60,
2099                                                                          'rows' => 3,
2100                                                                          'name' => 'content'),
2101                                    ($content) ? $content : '');
2102
2103         common_element('input', array('id' => 'message_send',
2104                                                                   'name' => 'message_send',
2105                                                                   'type' => 'submit',
2106                                                                   'value' => _('Send')));
2107
2108         common_hidden('token', common_session_token());
2109
2110         common_element_end('p');
2111         common_element_end('form');
2112 }
2113
2114 function common_memcache() {
2115         static $cache = NULL;
2116         if (!common_config('memcached', 'enabled')) {
2117                 return NULL;
2118         } else {
2119                 if (!$cache) {
2120                         $cache = new Memcache();
2121                         $servers = common_config('memcached', 'server');
2122                         if (is_array($servers)) {
2123                                 foreach($servers as $server) {
2124                                         $cache->addServer($server);
2125                                 }
2126                         } else {
2127                                 $cache->addServer($servers);
2128                         }
2129                 }
2130                 return $cache;
2131         }
2132 }
2133
2134 function common_compatible_license($from, $to) {
2135         # XXX: better compatibility check needed here!
2136         return ($from == $to);
2137 }