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