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