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