3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
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.
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.
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/>.
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
22 // Show a server error
24 function common_server_error($msg, $code=500)
26 static $status = array(500 => 'Internal Server Error',
27 501 => 'Not Implemented',
29 503 => 'Service Unavailable',
30 504 => 'Gateway Timeout',
31 505 => 'HTTP Version Not Supported');
33 if (!array_key_exists($code, $status)) {
37 $status_string = $status[$code];
39 header('HTTP/1.1 '.$code.' '.$status_string);
40 header('Content-type: text/plain');
48 function common_user_error($msg, $code=400)
50 static $status = array(400 => 'Bad Request',
51 401 => 'Unauthorized',
52 402 => 'Payment Required',
55 405 => 'Method Not Allowed',
56 406 => 'Not Acceptable',
57 407 => 'Proxy Authentication Required',
58 408 => 'Request Timeout',
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');
69 if (!array_key_exists($code, $status)) {
73 $status_string = $status[$code];
75 header('HTTP/1.1 '.$code.' '.$status_string);
77 common_show_header('Error');
78 common_element('div', array('class' => 'error'), $msg);
82 function common_init_locale($language=null)
85 $language = common_language();
87 putenv('LANGUAGE='.$language);
88 putenv('LANG='.$language);
89 return setlocale(LC_ALL, $language . ".utf8",
96 function common_init_language()
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');
107 common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
111 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
113 function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null)
117 global $action; /* XXX: kind of cheating here. */
121 common_element_start('head');
122 common_element('title', null,
123 $pagetitle . " - " . $config['site']['name']);
124 common_element('link', array('rel' => 'stylesheet',
125 'type' => 'text/css',
126 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
127 'media' => 'screen, projection, tv'));
128 foreach (array(6,7) as $ver) {
129 if (file_exists(theme_file('ie'.$ver.'.css'))) {
130 // Yes, IE people should be put in jail.
131 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
132 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
136 common_element('script', array('type' => 'text/javascript',
137 'src' => common_path('js/jquery.min.js')),
139 common_element('script', array('type' => 'text/javascript',
140 'src' => common_path('js/jquery.form.js')),
142 common_element('script', array('type' => 'text/javascript',
143 'src' => common_path('js/xbImportNode.js')),
145 common_element('script', array('type' => 'text/javascript',
146 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
148 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
149 'href' => common_local_url('opensearch', array('type' => 'people')),
150 'title' => common_config('site', 'name').' People Search'));
152 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
153 'href' => common_local_url('opensearch', array('type' => 'notice')),
154 'title' => common_config('site', 'name').' Notice Search'));
158 call_user_func($callable, $data);
160 call_user_func($callable);
163 common_element_end('head');
164 common_element_start('body', $action);
165 common_element_start('div', array('id' => 'wrap'));
166 common_element_start('div', array('id' => 'header'));
168 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
169 || file_exists(theme_file('logo.png')))
171 common_element_start('a', array('href' => common_local_url('public')));
172 common_element('img', array('src' => isset($config['site']['logo']) ?
173 ($config['site']['logo']) : theme_path('logo.png'),
174 'alt' => $config['site']['name'],
176 common_element_end('a');
178 common_element_start('p', array('id' => 'branding'));
179 common_element('a', array('href' => common_local_url('public')),
180 $config['site']['name']);
181 common_element_end('p');
184 common_element('h1', 'pagetitle', $pagetitle);
188 call_user_func($headercall, $data);
190 call_user_func($headercall);
193 common_element_end('div');
194 common_element_start('div', array('id' => 'content'));
197 function common_start_html($type=null, $indent=true)
201 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null;
203 // XXX: allow content negotiation for RDF, RSS, or XRDS
205 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
206 common_accept_to_prefs(PAGE_TYPE_PREFS));
209 common_user_error(_('This page is not available in a media type you accept'), 406);
214 header('Content-Type: '.$type);
216 common_start_xml('html',
217 '-//W3C//DTD XHTML 1.0 Strict//EN',
218 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent);
220 // FIXME: correct language for interface
222 $language = common_language();
224 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
225 'xml:lang' => $language,
226 'lang' => $language));
229 function common_show_footer()
232 common_element_end('div'); // content div
234 common_element_start('div', array('id' => 'footer'));
235 common_element_start('div', 'laconica');
236 if (common_config('site', 'broughtby')) {
237 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
239 $instr = _('**%%site.name%%** is a microblogging service. ');
241 $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);
242 $output = common_markup_to_html($instr);
244 common_element_end('div');
245 common_element('img', array('id' => 'cc',
246 'src' => $config['license']['image'],
247 'alt' => $config['license']['title']));
248 common_element_start('p');
249 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
250 common_element('a', array('class' => 'license',
252 'href' => $config['license']['url']),
253 $config['license']['title']);
254 common_text(_('. Contributors should be attributed by full name or nickname.'));
255 common_element_end('p');
256 common_element_end('div');
257 common_element_end('div');
258 common_element_end('body');
259 common_element_end('html');
263 function common_nav_menu()
265 $user = common_current_user();
266 common_element_start('ul', array('id' => 'nav'));
268 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
271 common_menu_item(common_local_url('peoplesearch'), _('Search'));
273 common_menu_item(common_local_url('profilesettings'),
275 common_menu_item(common_local_url('invite'),
277 common_menu_item(common_local_url('logout'),
280 common_menu_item(common_local_url('login'), _('Login'));
281 if (!common_config('site', 'closed')) {
282 common_menu_item(common_local_url('register'), _('Register'));
284 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
286 common_menu_item(common_local_url('doc', array('title' => 'help')),
288 common_element_end('ul');
291 function common_foot_menu()
293 common_element_start('ul', array('id' => 'nav_sub'));
294 common_menu_item(common_local_url('doc', array('title' => 'help')),
296 common_menu_item(common_local_url('doc', array('title' => 'about')),
298 common_menu_item(common_local_url('doc', array('title' => 'faq')),
300 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
302 common_menu_item(common_local_url('doc', array('title' => 'source')),
304 common_menu_item(common_local_url('doc', array('title' => 'contact')),
306 common_element_end('ul');
309 function common_menu_item($url, $text, $title=null, $is_selected=false)
313 $lattrs['class'] = 'current';
315 common_element_start('li', $lattrs);
316 $attrs['href'] = $url;
318 $attrs['title'] = $title;
320 common_element('a', $attrs, $text);
321 common_element_end('li');
324 function common_input($id, $label, $value=null,$instructions=null)
326 common_element_start('p');
327 common_element('label', array('for' => $id), $label);
328 $attrs = array('name' => $id,
330 'class' => 'input_text',
333 $attrs['value'] = htmlspecialchars($value);
335 common_element('input', $attrs);
337 common_element('span', 'input_instructions', $instructions);
339 common_element_end('p');
342 function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false)
344 common_element_start('p');
345 $attrs = array('name' => $id,
346 'type' => 'checkbox',
347 'class' => 'checkbox',
350 $attrs['value'] = htmlspecialchars($value);
353 $attrs['checked'] = 'checked';
356 $attrs['disabled'] = 'true';
358 common_element('input', $attrs);
360 common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label);
363 common_element('span', 'input_instructions', $instructions);
365 common_element_end('p');
368 function common_dropdown($id, $label, $content, $instructions=null, $blank_select=false, $selected=null)
370 common_element_start('p');
371 common_element('label', array('for' => $id), $label);
372 common_element_start('select', array('id' => $id, 'name' => $id));
374 common_element('option', array('value' => ''));
376 foreach ($content as $value => $option) {
377 if ($value == $selected) {
378 common_element('option', array('value' => $value, 'selected' => $value), $option);
380 common_element('option', array('value' => $value), $option);
383 common_element_end('select');
385 common_element('span', 'input_instructions', $instructions);
387 common_element_end('p');
389 function common_hidden($id, $value)
391 common_element('input', array('name' => $id,
397 function common_password($id, $label, $instructions=null)
399 common_element_start('p');
400 common_element('label', array('for' => $id), $label);
401 $attrs = array('name' => $id,
402 'type' => 'password',
403 'class' => 'password',
405 common_element('input', $attrs);
407 common_element('span', 'input_instructions', $instructions);
409 common_element_end('p');
412 function common_submit($id, $label, $cls='submit')
415 common_element_start('p');
416 common_element('input', array('type' => 'submit',
421 common_element_end('p');
424 function common_textarea($id, $label, $content=null, $instructions=null)
426 common_element_start('p');
427 common_element('label', array('for' => $id), $label);
428 common_element('textarea', array('rows' => 3,
432 ($content) ? $content : '');
434 common_element('span', 'input_instructions', $instructions);
436 common_element_end('p');
439 function common_timezone()
441 if (common_logged_in()) {
442 $user = common_current_user();
443 if ($user->timezone) {
444 return $user->timezone;
449 return $config['site']['timezone'];
452 function common_language()
455 // If there is a user logged in and they've set a language preference
456 // then return that one...
457 if (common_logged_in()) {
458 $user = common_current_user();
459 $user_language = $user->language;
461 return $user_language;
464 // Otherwise, find the best match for the languages requested by the
466 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
467 if (!empty($httplang)) {
468 $language = client_prefered_language($httplang);
473 // Finally, if none of the above worked, use the site's default...
474 return common_config('site', 'language');
476 // salted, hashed passwords are stored in the DB
478 function common_munge_password($password, $id)
480 return md5($password . $id);
483 // check if a username exists and has matching password
484 function common_check_user($nickname, $password)
486 // NEVER allow blank passwords, even if they match the DB
487 if (mb_strlen($password) == 0) {
490 $user = User::staticGet('nickname', $nickname);
491 if (is_null($user)) {
494 if (0 == strcmp(common_munge_password($password, $user->id),
503 // is the current user logged in?
504 function common_logged_in()
506 return (!is_null(common_current_user()));
509 function common_have_session()
511 return (0 != strcmp(session_id(), ''));
514 function common_ensure_session()
516 if (!common_have_session()) {
521 // Three kinds of arguments:
526 // Initialize to false; set to null if none found
530 function common_set_user($user)
535 if (is_null($user) && common_have_session()) {
537 unset($_SESSION['userid']);
539 } else if (is_string($user)) {
541 $user = User::staticGet('nickname', $nickname);
542 } else if (!($user instanceof User)) {
547 common_ensure_session();
548 $_SESSION['userid'] = $user->id;
555 function common_set_cookie($key, $value, $expiration=0)
557 $path = common_config('site', 'path');
558 $server = common_config('site', 'server');
560 if ($path && ($path != '/')) {
561 $cookiepath = '/' . $path . '/';
565 return setcookie($key,
572 define('REMEMBERME', 'rememberme');
573 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
575 function common_rememberme($user=null)
578 $user = common_current_user();
580 common_debug('No current user to remember', __FILE__);
585 $rm = new Remember_me();
587 $rm->code = common_good_rand(16);
588 $rm->user_id = $user->id;
590 // Wrap the insert in some good ol' fashioned transaction code
594 $result = $rm->insert();
597 common_log_db_error($rm, 'INSERT', __FILE__);
598 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
602 $rm->query('COMMIT');
604 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
606 $cookieval = $rm->user_id . ':' . $rm->code;
608 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
610 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
615 function common_remembered_user()
620 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
626 list($id, $code) = explode(':', $packed);
628 if (!$id || !$code) {
629 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
634 $rm = Remember_me::staticGet($code);
637 common_log(LOG_WARNING, 'No such remember code: ' . $code);
642 if ($rm->user_id != $id) {
643 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
648 $user = User::staticGet($rm->user_id);
651 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
657 $result = $rm->delete();
660 common_log_db_error($rm, 'DELETE', __FILE__);
661 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
666 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
668 common_set_user($user);
669 common_real_login(false);
671 // We issue a new cookie, so they can log in
672 // automatically again after this session
674 common_rememberme($user);
679 // must be called with a valid user!
681 function common_forgetme()
683 common_set_cookie(REMEMBERME, '', 0);
686 // who is the current user?
687 function common_current_user()
691 if ($_cur === false) {
693 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
694 common_ensure_session();
695 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
697 $_cur = User::staticGet($id);
702 // that didn't work; try to remember; will init $_cur to null on failure
703 $_cur = common_remembered_user();
706 common_debug("Got User " . $_cur->nickname);
707 common_debug("Faking session on remembered user");
708 // XXX: Is this necessary?
709 $_SESSION['userid'] = $_cur->id;
716 // Logins that are 'remembered' aren't 'real' -- they're subject to
717 // cookie-stealing. So, we don't let them do certain things. New reg,
718 // OpenID, and password logins _are_ real.
720 function common_real_login($real=true)
722 common_ensure_session();
723 $_SESSION['real_login'] = $real;
726 function common_is_real_login()
728 return common_logged_in() && $_SESSION['real_login'];
731 // get canonical version of nickname for comparison
732 function common_canonical_nickname($nickname)
734 // XXX: UTF-8 canonicalization (like combining chars)
735 return strtolower($nickname);
738 // get canonical version of email for comparison
739 function common_canonical_email($email)
741 // XXX: canonicalize UTF-8
742 // XXX: lcase the domain part
746 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$_+!*();/?:~-]))');
748 function common_render_content($text, $notice)
750 $r = common_render_text($text);
751 $id = $notice->profile_id;
752 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
753 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
754 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
758 function common_render_text($text)
760 $r = htmlspecialchars($text);
762 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
763 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
764 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
769 function common_render_uri_thingy($matches)
774 // Some heuristics for extracting URIs from surrounding punctuation
775 // Strip from trailing text...
776 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
778 $trailer = $matches[2];
782 ']' => '[', // technically disallowed in URIs, but used in Java docs
783 ')' => '(', // far too frequent in Wikipedia and MSDN
785 $final = substr($uri, -1, 1);
786 if (isset($pairs[$final])) {
787 $openers = substr_count($uri, $pairs[$final]);
788 $closers = substr_count($uri, $final);
789 if ($closers > $openers) {
790 // Assume the paren was opened outside the URI
791 $uri = substr($uri, 0, -1);
792 $trailer = $final . $trailer;
795 if ($longurl = common_longurl($uri)) {
796 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
797 $title = " title='$longurl'";
801 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
804 function common_longurl($short_url)
806 $long_url = common_shorten_link($short_url, true);
807 if ($long_url === $short_url) return false;
811 function common_longurl2($uri)
813 $uri_e = urlencode($uri);
814 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
815 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
816 return stripslashes($longurl['long_url']);
819 function common_shorten_links($text)
821 if (mb_strlen($text) <= 140) return $text;
822 static $cache = array();
823 if (isset($cache[$text])) return $cache[$text];
824 // \s = not a horizontal whitespace character (since PHP 5.2.4)
825 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
828 function common_shorten_link($url, $reverse = false)
830 static $url_cache = array();
831 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
833 $user = common_current_user();
835 $curlh = curl_init();
836 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
837 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
838 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
840 switch($user->urlshorteningservice) {
842 $short_url_service = new LilUrl;
843 $short_url = $short_url_service->shorten($url);
847 $short_url_service = new TightUrl;
848 $short_url = $short_url_service->shorten($url);
852 $short_url_service = new PtitUrl;
853 $short_url = $short_url_service->shorten($url);
857 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
858 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
862 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
863 $short_url = curl_exec($curlh);
866 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
867 $short_url = curl_exec($curlh);
870 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
871 $short_url = curl_exec($curlh);
874 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
875 $short_url = curl_exec($curlh);
884 $url_cache[(string)$short_url] = $url;
885 return (string)$short_url;
890 function common_xml_safe_str($str)
892 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
894 // Replace control, formatting, and surrogate characters with '*', ala Twitter
895 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
898 function common_tag_link($tag)
900 $canonical = common_canonical_tag($tag);
901 $url = common_local_url('tag', array('tag' => $canonical));
902 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
905 function common_canonical_tag($tag)
907 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
910 function common_valid_profile_tag($str)
912 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
915 function common_at_link($sender_id, $nickname)
917 $sender = Profile::staticGet($sender_id);
918 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
920 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
926 function common_at_hash_link($sender_id, $tag)
928 $user = User::staticGet($sender_id);
932 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
934 $url = common_local_url('subscriptions',
935 array('nickname' => $user->nickname,
937 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
943 function common_relative_profile($sender, $nickname, $dt=null)
945 // Try to find profiles this profile is subscribed to that have this nickname
946 $recipient = new Profile();
947 // XXX: use a join instead of a subquery
948 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
949 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
950 if ($recipient->find(true)) {
951 // XXX: should probably differentiate between profiles with
952 // the same name by date of most recent update
955 // Try to find profiles that listen to this profile and that have this nickname
956 $recipient = new Profile();
957 // XXX: use a join instead of a subquery
958 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
959 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
960 if ($recipient->find(true)) {
961 // XXX: should probably differentiate between profiles with
962 // the same name by date of most recent update
965 // If this is a local user, try to find a local user with that nickname.
966 $sender = User::staticGet($sender->id);
968 $recipient_user = User::staticGet('nickname', $nickname);
969 if ($recipient_user) {
970 return $recipient_user->getProfile();
973 // Otherwise, no links. @messages from local users to remote users,
974 // or from remote users to other remote users, are just
975 // outside our ability to make intelligent guesses about
979 // where should the avatar go for this user?
981 function common_avatar_filename($id, $extension, $size=null, $extra=null)
986 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
988 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
992 function common_avatar_path($filename)
995 return INSTALLDIR . '/avatar/' . $filename;
998 function common_avatar_url($filename)
1000 return common_path('avatar/'.$filename);
1003 function common_avatar_display_url($avatar)
1005 $server = common_config('avatar', 'server');
1007 return 'http://'.$server.'/'.$avatar->filename;
1009 return $avatar->url;
1013 function common_default_avatar($size)
1015 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
1016 AVATAR_STREAM_SIZE => 'stream',
1017 AVATAR_MINI_SIZE => 'mini');
1018 return theme_path('default-avatar-'.$sizenames[$size].'.png');
1021 function common_local_url($action, $args=null, $fragment=null)
1024 if (common_config('site','fancy')) {
1025 $url = common_fancy_url($action, $args);
1027 $url = common_simple_url($action, $args);
1029 if (!is_null($fragment)) {
1030 $url .= '#'.$fragment;
1035 function common_fancy_url($action, $args=null)
1037 switch (strtolower($action)) {
1039 if ($args && isset($args['page'])) {
1040 return common_path('?page=' . $args['page']);
1042 return common_path('');
1045 if ($args && isset($args['page'])) {
1046 return common_path('featured?page=' . $args['page']);
1048 return common_path('featured');
1051 if ($args && isset($args['page'])) {
1052 return common_path('favorited?page=' . $args['page']);
1054 return common_path('favorited');
1057 return common_path('rss');
1059 return common_path("api/statuses/public_timeline.atom");
1061 return common_path('xrds');
1063 return common_path('featuredrss');
1064 case 'favoritedrss':
1065 return common_path('favoritedrss');
1067 if ($args && $args['type']) {
1068 return common_path('opensearch/'.$args['type']);
1070 return common_path('opensearch/people');
1073 return common_path('doc/'.$args['title']);
1080 return common_path('main/'.$action);
1082 return common_path('main/tagother?id='.$args['id']);
1084 if ($args && $args['code']) {
1085 return common_path('main/register/'.$args['code']);
1087 return common_path('main/register');
1089 case 'remotesubscribe':
1090 if ($args && $args['nickname']) {
1091 return common_path('main/remote?nickname=' . $args['nickname']);
1093 return common_path('main/remote');
1096 return common_path($args['nickname'].'/nudge');
1098 return common_path('main/openid');
1099 case 'profilesettings':
1100 return common_path('settings/profile');
1101 case 'emailsettings':
1102 return common_path('settings/email');
1103 case 'openidsettings':
1104 return common_path('settings/openid');
1106 return common_path('settings/sms');
1107 case 'twittersettings':
1108 return common_path('settings/twitter');
1109 case 'othersettings':
1110 return common_path('settings/other');
1111 case 'deleteprofile':
1112 return common_path('settings/delete');
1114 if ($args && $args['replyto']) {
1115 return common_path('notice/new?replyto='.$args['replyto']);
1117 return common_path('notice/new');
1120 return common_path('notice/'.$args['notice']);
1121 case 'deletenotice':
1122 if ($args && $args['notice']) {
1123 return common_path('notice/delete/'.$args['notice']);
1125 return common_path('notice/delete');
1127 case 'microsummary':
1130 return common_path($args['nickname'].'/'.$action);
1135 if ($args && isset($args['page'])) {
1136 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1138 return common_path($args['nickname'].'/'.$action);
1140 case 'subscriptions':
1142 $nickname = $args['nickname'];
1143 unset($args['nickname']);
1144 if (isset($args['tag'])) {
1145 $tag = $args['tag'];
1146 unset($args['tag']);
1148 $params = http_build_query($args);
1150 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1152 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1155 return common_path($args['nickname'].'/all/rss');
1157 return common_path($args['nickname'].'/replies/rss');
1159 if (isset($args['limit']))
1160 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1161 return common_path($args['nickname'].'/rss');
1163 if ($args && isset($args['page'])) {
1164 return common_path($args['nickname'].'?page=' . $args['page']);
1166 return common_path($args['nickname']);
1169 case 'usertimeline':
1170 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1171 case 'confirmaddress':
1172 return common_path('main/confirmaddress/'.$args['code']);
1174 return common_path('user/'.$args['id']);
1175 case 'recoverpassword':
1176 $path = 'main/recoverpassword';
1177 if ($args['code']) {
1178 $path .= '/' . $args['code'];
1180 return common_path($path);
1182 return common_path('settings/im');
1183 case 'peoplesearch':
1184 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1185 case 'noticesearch':
1186 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1187 case 'noticesearchrss':
1188 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1189 case 'avatarbynickname':
1190 return common_path($args['nickname'].'/avatar/'.$args['size']);
1192 if (isset($args['tag']) && $args['tag']) {
1193 $path = 'tag/' . $args['tag'];
1194 unset($args['tag']);
1198 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1200 $path = 'peopletag/' . $args['tag'];
1201 unset($args['tag']);
1202 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1204 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1206 return common_path('main/favor');
1208 return common_path('main/disfavor');
1209 case 'showfavorites':
1210 if ($args && isset($args['page'])) {
1211 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1213 return common_path($args['nickname'].'/favorites');
1215 case 'favoritesrss':
1216 return common_path($args['nickname'].'/favorites/rss');
1218 return common_path('message/' . $args['message']);
1220 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1222 // XXX: do fancy URLs for all the API methods
1223 switch (strtolower($args['apiaction'])) {
1225 switch (strtolower($args['method'])) {
1226 case 'user_timeline.rss':
1227 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1228 case 'user_timeline.atom':
1229 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1230 case 'user_timeline.json':
1231 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1232 case 'user_timeline.xml':
1233 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1234 default: return common_simple_url($action, $args);
1236 default: return common_simple_url($action, $args);
1239 if ($args && isset($args['seconds'])) {
1240 return common_path('main/sup?seconds='.$args['seconds']);
1242 return common_path('main/sup');
1245 return common_simple_url($action, $args);
1249 function common_simple_url($action, $args=null)
1252 /* XXX: pretty URLs */
1255 foreach ($args as $key => $value) {
1256 $extra .= "&${key}=${value}";
1259 return common_path("index.php?action=${action}${extra}");
1262 function common_path($relative)
1265 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1266 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1269 function common_date_string($dt)
1271 // XXX: do some sexy date formatting
1272 // return date(DATE_RFC822, $dt);
1273 $t = strtotime($dt);
1277 if ($now < $t) { // that shouldn't happen!
1278 return common_exact_date($dt);
1279 } else if ($diff < 60) {
1280 return _('a few seconds ago');
1281 } else if ($diff < 92) {
1282 return _('about a minute ago');
1283 } else if ($diff < 3300) {
1284 return sprintf(_('about %d minutes ago'), round($diff/60));
1285 } else if ($diff < 5400) {
1286 return _('about an hour ago');
1287 } else if ($diff < 22 * 3600) {
1288 return sprintf(_('about %d hours ago'), round($diff/3600));
1289 } else if ($diff < 37 * 3600) {
1290 return _('about a day ago');
1291 } else if ($diff < 24 * 24 * 3600) {
1292 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1293 } else if ($diff < 46 * 24 * 3600) {
1294 return _('about a month ago');
1295 } else if ($diff < 330 * 24 * 3600) {
1296 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1297 } else if ($diff < 480 * 24 * 3600) {
1298 return _('about a year ago');
1300 return common_exact_date($dt);
1304 function common_exact_date($dt)
1310 $_utc = new DateTimeZone('UTC');
1311 $_siteTz = new DateTimeZone(common_timezone());
1314 $dateStr = date('d F Y H:i:s', strtotime($dt));
1315 $d = new DateTime($dateStr, $_utc);
1316 $d->setTimezone($_siteTz);
1317 return $d->format(DATE_RFC850);
1320 function common_date_w3dtf($dt)
1322 $dateStr = date('d F Y H:i:s', strtotime($dt));
1323 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1324 $d->setTimezone(new DateTimeZone(common_timezone()));
1325 return $d->format(DATE_W3C);
1328 function common_date_rfc2822($dt)
1330 $dateStr = date('d F Y H:i:s', strtotime($dt));
1331 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1332 $d->setTimezone(new DateTimeZone(common_timezone()));
1333 return $d->format('r');
1336 function common_date_iso8601($dt)
1338 $dateStr = date('d F Y H:i:s', strtotime($dt));
1339 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1340 $d->setTimezone(new DateTimeZone(common_timezone()));
1341 return $d->format('c');
1344 function common_sql_now()
1346 return strftime('%Y-%m-%d %H:%M:%S', time());
1349 function common_redirect($url, $code=307)
1351 static $status = array(301 => "Moved Permanently",
1354 307 => "Temporary Redirect");
1355 header("Status: ${code} $status[$code]");
1356 header("Location: $url");
1358 common_start_xml('a',
1359 '-//W3C//DTD XHTML 1.0 Strict//EN',
1360 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1361 common_element('a', array('href' => $url), $url);
1366 function common_save_replies($notice)
1368 // Alternative reply format
1370 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1373 // extract all @messages
1374 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1378 if ($cnt || $tname) {
1379 // XXX: is there another way to make an array copy?
1380 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1383 $sender = Profile::staticGet($notice->profile_id);
1387 // store replied only for first @ (what user/notice what the reply directed,
1388 // we assume first @ is it)
1390 for ($i=0; $i<count($names); $i++) {
1391 $nickname = $names[$i];
1392 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1396 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self
1397 $reply_for = $recipient;
1398 $recipient_notice = $reply_for->getCurrentNotice();
1399 if ($recipient_notice) {
1400 $orig = clone($notice);
1401 $notice->reply_to = $recipient_notice->id;
1402 $notice->update($orig);
1405 // Don't save replies from blocked profile to local user
1406 $recipient_user = User::staticGet('id', $recipient->id);
1407 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1410 $reply = new Reply();
1411 $reply->notice_id = $notice->id;
1412 $reply->profile_id = $recipient->id;
1413 $id = $reply->insert();
1415 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1416 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1417 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1420 $replied[$recipient->id] = 1;
1424 // Hash format replies, too
1425 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1427 foreach ($match[1] as $tag) {
1428 $tagged = Profile_tag::getTagged($sender->id, $tag);
1429 foreach ($tagged as $t) {
1430 if (!$replied[$t->id]) {
1431 // Don't save replies from blocked profile to local user
1432 $t_user = User::staticGet('id', $t->id);
1433 if ($t_user && $t_user->hasBlocked($sender)) {
1436 $reply = new Reply();
1437 $reply->notice_id = $notice->id;
1438 $reply->profile_id = $t->id;
1439 $id = $reply->insert();
1441 common_log_db_error($reply, 'INSERT', __FILE__);
1450 function common_broadcast_notice($notice, $remote=false)
1453 // Check to see if notice should go to Twitter
1454 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1455 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1457 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1459 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1460 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1462 $result = common_twitter_broadcast($notice, $flink);
1465 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1470 if (common_config('queue', 'enabled')) {
1472 return common_enqueue_notice($notice);
1474 return common_real_broadcast($notice, $remote);
1478 function common_twitter_broadcast($notice, $flink)
1482 $fuser = $flink->getForeignUser();
1483 $twitter_user = $fuser->nickname;
1484 $twitter_password = $flink->credentials;
1485 $uri = 'http://www.twitter.com/statuses/update.json';
1487 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1488 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1491 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1492 CURLOPT_POST => true,
1493 CURLOPT_POSTFIELDS => array(
1494 'status' => $statustxt,
1495 'source' => $config['integration']['source']
1497 CURLOPT_RETURNTRANSFER => true,
1498 CURLOPT_FAILONERROR => true,
1499 CURLOPT_HEADER => false,
1500 CURLOPT_FOLLOWLOCATION => true,
1501 CURLOPT_USERAGENT => "Laconica",
1502 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1503 CURLOPT_TIMEOUT => 120,
1505 # Twitter is strict about accepting invalid "Expect" headers
1506 CURLOPT_HTTPHEADER => array('Expect:')
1509 $ch = curl_init($uri);
1510 curl_setopt_array($ch, $options);
1511 $data = curl_exec($ch);
1512 $errmsg = curl_error($ch);
1515 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1523 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1528 // Twitter should return a status
1529 $status = json_decode($data);
1532 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1540 // Stick the notice on the queue
1542 function common_enqueue_notice($notice)
1544 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1545 $qi = new Queue_item();
1546 $qi->notice_id = $notice->id;
1547 $qi->transport = $transport;
1548 $qi->created = $notice->created;
1549 $result = $qi->insert();
1551 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1552 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1555 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1560 function common_dequeue_notice($notice)
1562 $qi = Queue_item::staticGet($notice->id);
1564 $result = $qi->delete();
1566 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1567 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1570 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1577 function common_real_broadcast($notice, $remote=false)
1581 // Make sure we have the OMB stuff
1582 require_once(INSTALLDIR.'/lib/omb.php');
1583 $success = omb_broadcast_remote_subscribers($notice);
1585 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1589 require_once(INSTALLDIR.'/lib/jabber.php');
1590 $success = jabber_broadcast_notice($notice);
1592 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1596 require_once(INSTALLDIR.'/lib/mail.php');
1597 $success = mail_broadcast_notice_sms($notice);
1599 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1603 $success = jabber_public_notice($notice);
1605 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1608 // XXX: broadcast notices to other IM
1612 function common_broadcast_profile($profile)
1614 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1615 require_once(INSTALLDIR.'/lib/omb.php');
1616 omb_broadcast_profile($profile);
1617 // XXX: Other broadcasts...?
1621 function common_profile_url($nickname)
1623 return common_local_url('showstream', array('nickname' => $nickname));
1626 // Don't call if nobody's logged in
1628 function common_notice_form($action=null, $content=null)
1630 $user = common_current_user();
1631 assert(!is_null($user));
1632 common_element_start('form', array('id' => 'status_form',
1634 'action' => common_local_url('newnotice')));
1635 common_element_start('p');
1636 common_element('label', array('for' => 'status_textarea',
1637 'id' => 'status_label'),
1638 sprintf(_('What\'s up, %s?'), $user->nickname));
1639 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1640 common_element('textarea', array('id' => 'status_textarea',
1643 'name' => 'status_textarea'),
1644 ($content) ? $content : '');
1645 common_hidden('token', common_session_token());
1647 common_hidden('returnto', $action);
1649 // set by JavaScript
1650 common_hidden('inreplyto', 'false');
1651 common_element('input', array('id' => 'status_submit',
1652 'name' => 'status_submit',
1654 'value' => _('Send')));
1655 common_element_end('p');
1656 common_element_end('form');
1659 // Should make up a reasonable root URL
1661 function common_root_url()
1663 return common_path('');
1666 // returns $bytes bytes of random data as a hexadecimal string
1667 // "good" here is a goal and not a guarantee
1669 function common_good_rand($bytes)
1671 // XXX: use random.org...?
1672 if (file_exists('/dev/urandom')) {
1673 return common_urandom($bytes);
1674 } else { // FIXME: this is probably not good enough
1675 return common_mtrand($bytes);
1679 function common_urandom($bytes)
1681 $h = fopen('/dev/urandom', 'rb');
1683 $src = fread($h, $bytes);
1686 for ($i = 0; $i < $bytes; $i++) {
1687 $enc .= sprintf("%02x", (ord($src[$i])));
1692 function common_mtrand($bytes)
1695 for ($i = 0; $i < $bytes; $i++) {
1696 $enc .= sprintf("%02x", mt_rand(0, 255));
1701 function common_set_returnto($url)
1703 common_ensure_session();
1704 $_SESSION['returnto'] = $url;
1707 function common_get_returnto()
1709 common_ensure_session();
1710 return $_SESSION['returnto'];
1713 function common_timestamp()
1715 return date('YmdHis');
1718 function common_ensure_syslog()
1720 static $initialized = false;
1721 if (!$initialized) {
1723 openlog($config['syslog']['appname'], 0, LOG_USER);
1724 $initialized = true;
1728 function common_log($priority, $msg, $filename=null)
1730 $logfile = common_config('site', 'logfile');
1732 $log = fopen($logfile, "a");
1734 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1735 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1736 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1737 fwrite($log, $output);
1741 common_ensure_syslog();
1742 syslog($priority, $msg);
1746 function common_debug($msg, $filename=null)
1749 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1751 common_log(LOG_DEBUG, $msg);
1755 function common_log_db_error(&$object, $verb, $filename=null)
1757 $objstr = common_log_objstring($object);
1758 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1759 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1762 function common_log_objstring(&$object)
1764 if (is_null($object)) {
1767 $arr = $object->toArray();
1769 foreach ($arr as $k => $v) {
1770 $fields[] = "$k='$v'";
1772 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1776 function common_valid_http_url($url)
1778 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1781 function common_valid_tag($tag)
1783 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1784 return (Validate::email($matches[1]) ||
1785 preg_match('/^([\w-\.]+)$/', $matches[1]));
1790 // Does a little before-after block for next/prev page
1792 function common_pagination($have_before, $have_after, $page, $action, $args=null)
1795 if ($have_before || $have_after) {
1796 common_element_start('div', array('id' => 'pagination'));
1797 common_element_start('ul', array('id' => 'nav_pagination'));
1801 $pargs = array('page' => $page-1);
1802 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1804 common_element_start('li', 'before');
1805 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1807 common_element_end('li');
1811 $pargs = array('page' => $page+1);
1812 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1813 common_element_start('li', 'after');
1814 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1816 common_element_end('li');
1819 if ($have_before || $have_after) {
1820 common_element_end('ul');
1821 common_element_end('div');
1825 /* Following functions are copied from MediaWiki GlobalFunctions.php
1826 * and written by Evan Prodromou. */
1828 function common_accept_to_prefs($accept, $def = '*/*')
1830 // No arg means accept anything (per HTTP spec)
1832 return array($def => 1);
1837 $parts = explode(',', $accept);
1839 foreach($parts as $part) {
1840 // FIXME: doesn't deal with params like 'text/html; level=1'
1841 @list($value, $qpart) = explode(';', $part);
1843 if(!isset($qpart)) {
1845 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1846 $prefs[$value] = $match[1];
1853 function common_mime_type_match($type, $avail)
1855 if(array_key_exists($type, $avail)) {
1858 $parts = explode('/', $type);
1859 if(array_key_exists($parts[0] . '/*', $avail)) {
1860 return $parts[0] . '/*';
1861 } elseif(array_key_exists('*/*', $avail)) {
1869 function common_negotiate_type($cprefs, $sprefs)
1873 foreach(array_keys($sprefs) as $type) {
1874 $parts = explode('/', $type);
1875 if($parts[1] != '*') {
1876 $ckey = common_mime_type_match($type, $cprefs);
1878 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1883 foreach(array_keys($cprefs) as $type) {
1884 $parts = explode('/', $type);
1885 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1886 $skey = common_mime_type_match($type, $sprefs);
1888 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1894 $besttype = "text/html";
1896 foreach(array_keys($combine) as $type) {
1897 if($combine[$type] > $bestq) {
1899 $bestq = $combine[$type];
1906 function common_config($main, $sub)
1909 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1912 function common_copy_args($from)
1915 $strip = get_magic_quotes_gpc();
1916 foreach ($from as $k => $v) {
1917 $to[$k] = ($strip) ? stripslashes($v) : $v;
1922 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1923 // This is used before handing a request off to OAuthRequest::from_request.
1924 function common_remove_magic_from_request()
1926 if(get_magic_quotes_gpc()) {
1927 $_POST=array_map('stripslashes',$_POST);
1928 $_GET=array_map('stripslashes',$_GET);
1932 function common_user_uri(&$user)
1934 return common_local_url('userbyid', array('id' => $user->id));
1937 function common_notice_uri(&$notice)
1939 return common_local_url('shownotice',
1940 array('notice' => $notice->id));
1943 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1945 function common_confirmation_code($bits)
1947 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1948 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1949 $chars = ceil($bits/5);
1951 for ($i = 0; $i < $chars; $i++) {
1952 // XXX: convert to string and back
1953 $num = hexdec(common_good_rand(1));
1954 // XXX: randomness is too precious to throw away almost
1955 // 40% of the bits we get!
1956 $code .= $codechars[$num%32];
1961 // convert markup to HTML
1963 function common_markup_to_html($c)
1965 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1966 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1967 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1968 return Markdown($c);
1971 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
1973 $avatar = $profile->getAvatar($size);
1975 return common_avatar_display_url($avatar);
1977 return common_default_avatar($size);
1981 function common_profile_uri($profile)
1986 $user = User::staticGet($profile->id);
1991 $remote = Remote_profile::staticGet($profile->id);
1993 return $remote->uri;
1995 // XXX: this is a very bad profile!
1999 function common_canonical_sms($sms)
2002 preg_replace('/\D/', '', $sms);
2006 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
2010 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
2014 case E_USER_WARNING:
2015 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
2019 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
2023 // FIXME: show error page if we're on the Web
2024 /* Don't execute PHP internal error handler */
2028 function common_session_token()
2030 common_ensure_session();
2031 if (!array_key_exists('token', $_SESSION)) {
2032 $_SESSION['token'] = common_good_rand(64);
2034 return $_SESSION['token'];
2037 function common_disfavor_form($notice)
2039 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
2041 'class' => 'disfavor',
2042 'action' => common_local_url('disfavor')));
2044 common_element('input', array('type' => 'hidden',
2045 'name' => 'token-'. $notice->id,
2046 'id' => 'token-'. $notice->id,
2048 'value' => common_session_token()));
2050 common_element('input', array('type' => 'hidden',
2052 'id' => 'notice-n'. $notice->id,
2053 'class' => 'notice',
2054 'value' => $notice->id));
2056 common_element('input', array('type' => 'submit',
2057 'id' => 'disfavor-submit-' . $notice->id,
2058 'name' => 'disfavor-submit-' . $notice->id,
2059 'class' => 'disfavor',
2060 'value' => 'Disfavor favorite',
2061 'title' => 'Remove this message from favorites'));
2062 common_element_end('form');
2065 function common_favor_form($notice)
2067 common_element_start('form', array('id' => 'favor-' . $notice->id,
2070 'action' => common_local_url('favor')));
2072 common_element('input', array('type' => 'hidden',
2073 'name' => 'token-'. $notice->id,
2074 'id' => 'token-'. $notice->id,
2076 'value' => common_session_token()));
2078 common_element('input', array('type' => 'hidden',
2080 'id' => 'notice-n'. $notice->id,
2081 'class' => 'notice',
2082 'value' => $notice->id));
2084 common_element('input', array('type' => 'submit',
2085 'id' => 'favor-submit-' . $notice->id,
2086 'name' => 'favor-submit-' . $notice->id,
2088 'value' => 'Add to favorites',
2089 'title' => 'Add this message to favorites'));
2090 common_element_end('form');
2093 function common_nudge_form($profile)
2095 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2096 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2097 common_hidden('token', common_session_token());
2098 common_element('input', array('type' => 'submit',
2099 'class' => 'submit',
2100 'value' => _('Send a nudge')));
2101 common_element_end('form');
2103 function common_nudge_response()
2105 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2108 function common_subscribe_form($profile)
2110 common_element_start('form', array('id' => 'subscribe-' . $profile->id,
2112 'class' => 'subscribe',
2113 'action' => common_local_url('subscribe')));
2114 common_hidden('token', common_session_token());
2115 common_element('input', array('id' => 'subscribeto-' . $profile->id,
2116 'name' => 'subscribeto',
2118 'value' => $profile->id));
2119 common_element('input', array('type' => 'submit',
2120 'class' => 'submit',
2121 'value' => _('Subscribe')));
2122 common_element_end('form');
2125 function common_unsubscribe_form($profile)
2127 common_element_start('form', array('id' => 'unsubscribe-' . $profile->id,
2129 'class' => 'unsubscribe',
2130 'action' => common_local_url('unsubscribe')));
2131 common_hidden('token', common_session_token());
2132 common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
2133 'name' => 'unsubscribeto',
2135 'value' => $profile->id));
2136 common_element('input', array('type' => 'submit',
2137 'class' => 'submit',
2138 'value' => _('Unsubscribe')));
2139 common_element_end('form');
2142 // XXX: Refactor this code
2143 function common_profile_new_message_nudge ($cur, $profile)
2145 $user = User::staticGet('id', $profile->id);
2147 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2148 common_element_start('li', array('id' => 'profile_send_a_new_message'));
2149 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2150 _('Send a message'));
2151 common_element_end('li');
2153 if ($user->email && $user->emailnotifynudge) {
2154 common_element_start('li', array('id' => 'profile_nudge'));
2155 common_nudge_form($user);
2156 common_element_end('li');
2161 function common_cache_key($extra)
2163 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2166 function common_keyize($str)
2168 $str = strtolower($str);
2169 $str = preg_replace('/\s/', '_', $str);
2173 function common_message_form($content, $user, $to)
2176 common_element_start('form', array('id' => 'message_form',
2178 'action' => common_local_url('newmessage')));
2180 $mutual_users = $user->mutuallySubscribedUsers();
2184 while ($mutual_users->fetch()) {
2185 if ($mutual_users->id != $user->id) {
2186 $mutual[$mutual_users->id] = $mutual_users->nickname;
2190 $mutual_users->free();
2191 unset($mutual_users);
2193 common_dropdown('to', _('To'), $mutual, null, false, $to->id);
2195 common_element_start('p');
2197 common_element('textarea', array('id' => 'message_content',
2200 'name' => 'content'),
2201 ($content) ? $content : '');
2203 common_element('input', array('id' => 'message_send',
2204 'name' => 'message_send',
2206 'value' => _('Send')));
2208 common_hidden('token', common_session_token());
2210 common_element_end('p');
2211 common_element_end('form');
2214 function common_memcache()
2216 static $cache = null;
2217 if (!common_config('memcached', 'enabled')) {
2221 $cache = new Memcache();
2222 $servers = common_config('memcached', 'server');
2223 if (is_array($servers)) {
2224 foreach($servers as $server) {
2225 $cache->addServer($server);
2228 $cache->addServer($servers);
2235 function common_compatible_license($from, $to)
2237 // XXX: better compatibility check needed here!
2238 return ($from == $to);
2241 /* These are almost identical, so we use a helper function */
2243 function common_block_form($profile, $args=null)
2245 common_blocking_form('block', _('Block'), $profile, $args);
2248 function common_unblock_form($profile, $args=null)
2250 common_blocking_form('unblock', _('Unblock'), $profile, $args);
2253 function common_blocking_form($type, $label, $profile, $args=null)
2255 common_element_start('form', array('id' => $type . '-' . $profile->id,
2258 'action' => common_local_url($type)));
2259 common_hidden('token', common_session_token());
2260 common_element('input', array('id' => $type . 'to-' . $profile->id,
2261 'name' => $type . 'to',
2263 'value' => $profile->id));
2264 common_element('input', array('type' => 'submit',
2265 'class' => 'submit',
2267 'value' => $label));
2269 foreach ($args as $k => $v) {
2270 common_hidden('returnto-' . $k, $v);
2273 common_element_end('form');