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