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);
84 // Start an HTML element
85 function common_element_start($tag, $attrs=null)
88 $xw->startElement($tag);
89 if (is_array($attrs)) {
90 foreach ($attrs as $name => $value) {
91 $xw->writeAttribute($name, $value);
93 } else if (is_string($attrs)) {
94 $xw->writeAttribute('class', $attrs);
98 function common_element_end($tag)
100 static $empty_tag = array('base', 'meta', 'link', 'hr',
101 'br', 'param', 'img', 'area',
104 // XXX: check namespace
105 if (in_array($tag, $empty_tag)) {
108 $xw->fullEndElement();
112 function common_element($tag, $attrs=null, $content=null)
114 common_element_start($tag, $attrs);
116 if (!is_null($content)) {
119 common_element_end($tag);
122 function common_start_xml($doc=null, $public=null, $system=null, $indent=true)
125 $xw = new XMLWriter();
126 $xw->openURI('php://output');
127 $xw->setIndent($indent);
128 $xw->startDocument('1.0', 'UTF-8');
130 $xw->writeDTD($doc, $public, $system);
134 function common_end_xml()
141 function common_init_locale($language=null)
144 $language = common_language();
146 putenv('LANGUAGE='.$language);
147 putenv('LANG='.$language);
148 return setlocale(LC_ALL, $language . ".utf8",
150 $language . ".utf-8",
151 $language . ".UTF-8",
155 function common_init_language()
157 mb_internal_encoding('UTF-8');
158 $language = common_language();
159 // So we don't have to make people install the gettext locales
160 $locale_set = common_init_locale($language);
161 bindtextdomain("laconica", common_config('site','locale_path'));
162 bind_textdomain_codeset("laconica", "UTF-8");
163 textdomain("laconica");
164 setlocale(LC_CTYPE, 'C');
166 common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
170 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
172 function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null)
176 global $action; /* XXX: kind of cheating here. */
180 common_element_start('head');
181 common_element('title', null,
182 $pagetitle . " - " . $config['site']['name']);
183 common_element('link', array('rel' => 'stylesheet',
184 'type' => 'text/css',
185 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
186 'media' => 'screen, projection, tv'));
187 foreach (array(6,7) as $ver) {
188 if (file_exists(theme_file('ie'.$ver.'.css'))) {
189 // Yes, IE people should be put in jail.
190 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
191 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
195 common_element('script', array('type' => 'text/javascript',
196 'src' => common_path('js/jquery.min.js')),
198 common_element('script', array('type' => 'text/javascript',
199 'src' => common_path('js/jquery.form.js')),
201 common_element('script', array('type' => 'text/javascript',
202 'src' => common_path('js/xbImportNode.js')),
204 common_element('script', array('type' => 'text/javascript',
205 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
207 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
208 'href' => common_local_url('opensearch', array('type' => 'people')),
209 'title' => common_config('site', 'name').' People Search'));
211 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
212 'href' => common_local_url('opensearch', array('type' => 'notice')),
213 'title' => common_config('site', 'name').' Notice Search'));
217 call_user_func($callable, $data);
219 call_user_func($callable);
222 common_element_end('head');
223 common_element_start('body', $action);
224 common_element_start('div', array('id' => 'wrap'));
225 common_element_start('div', array('id' => 'header'));
227 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
228 || file_exists(theme_file('logo.png')))
230 common_element_start('a', array('href' => common_local_url('public')));
231 common_element('img', array('src' => isset($config['site']['logo']) ?
232 ($config['site']['logo']) : theme_path('logo.png'),
233 'alt' => $config['site']['name'],
235 common_element_end('a');
237 common_element_start('p', array('id' => 'branding'));
238 common_element('a', array('href' => common_local_url('public')),
239 $config['site']['name']);
240 common_element_end('p');
243 common_element('h1', 'pagetitle', $pagetitle);
247 call_user_func($headercall, $data);
249 call_user_func($headercall);
252 common_element_end('div');
253 common_element_start('div', array('id' => 'content'));
256 function common_start_html($type=null, $indent=true)
260 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null;
262 // XXX: allow content negotiation for RDF, RSS, or XRDS
264 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
265 common_accept_to_prefs(PAGE_TYPE_PREFS));
268 common_user_error(_('This page is not available in a media type you accept'), 406);
273 header('Content-Type: '.$type);
275 common_start_xml('html',
276 '-//W3C//DTD XHTML 1.0 Strict//EN',
277 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent);
279 // FIXME: correct language for interface
281 $language = common_language();
283 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
284 'xml:lang' => $language,
285 'lang' => $language));
288 function common_show_footer()
291 common_element_end('div'); // content div
293 common_element_start('div', array('id' => 'footer'));
294 common_element_start('div', 'laconica');
295 if (common_config('site', 'broughtby')) {
296 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
298 $instr = _('**%%site.name%%** is a microblogging service. ');
300 $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);
301 $output = common_markup_to_html($instr);
303 common_element_end('div');
304 common_element('img', array('id' => 'cc',
305 'src' => $config['license']['image'],
306 'alt' => $config['license']['title']));
307 common_element_start('p');
308 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
309 common_element('a', array('class' => 'license',
311 'href' => $config['license']['url']),
312 $config['license']['title']);
313 common_text(_('. Contributors should be attributed by full name or nickname.'));
314 common_element_end('p');
315 common_element_end('div');
316 common_element_end('div');
317 common_element_end('body');
318 common_element_end('html');
322 function common_text($txt)
328 function common_raw($xml)
334 function common_nav_menu()
336 $user = common_current_user();
337 common_element_start('ul', array('id' => 'nav'));
339 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
342 common_menu_item(common_local_url('peoplesearch'), _('Search'));
344 common_menu_item(common_local_url('profilesettings'),
346 common_menu_item(common_local_url('invite'),
348 common_menu_item(common_local_url('logout'),
351 common_menu_item(common_local_url('login'), _('Login'));
352 if (!common_config('site', 'closed')) {
353 common_menu_item(common_local_url('register'), _('Register'));
355 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
357 common_menu_item(common_local_url('doc', array('title' => 'help')),
359 common_element_end('ul');
362 function common_foot_menu()
364 common_element_start('ul', array('id' => 'nav_sub'));
365 common_menu_item(common_local_url('doc', array('title' => 'help')),
367 common_menu_item(common_local_url('doc', array('title' => 'about')),
369 common_menu_item(common_local_url('doc', array('title' => 'faq')),
371 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
373 common_menu_item(common_local_url('doc', array('title' => 'source')),
375 common_menu_item(common_local_url('doc', array('title' => 'contact')),
377 common_element_end('ul');
380 function common_menu_item($url, $text, $title=null, $is_selected=false)
384 $lattrs['class'] = 'current';
386 common_element_start('li', $lattrs);
387 $attrs['href'] = $url;
389 $attrs['title'] = $title;
391 common_element('a', $attrs, $text);
392 common_element_end('li');
395 function common_input($id, $label, $value=null,$instructions=null)
397 common_element_start('p');
398 common_element('label', array('for' => $id), $label);
399 $attrs = array('name' => $id,
401 'class' => 'input_text',
404 $attrs['value'] = htmlspecialchars($value);
406 common_element('input', $attrs);
408 common_element('span', 'input_instructions', $instructions);
410 common_element_end('p');
413 function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false)
415 common_element_start('p');
416 $attrs = array('name' => $id,
417 'type' => 'checkbox',
418 'class' => 'checkbox',
421 $attrs['value'] = htmlspecialchars($value);
424 $attrs['checked'] = 'checked';
427 $attrs['disabled'] = 'true';
429 common_element('input', $attrs);
431 common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label);
434 common_element('span', 'input_instructions', $instructions);
436 common_element_end('p');
439 function common_dropdown($id, $label, $content, $instructions=null, $blank_select=false, $selected=null)
441 common_element_start('p');
442 common_element('label', array('for' => $id), $label);
443 common_element_start('select', array('id' => $id, 'name' => $id));
445 common_element('option', array('value' => ''));
447 foreach ($content as $value => $option) {
448 if ($value == $selected) {
449 common_element('option', array('value' => $value, 'selected' => $value), $option);
451 common_element('option', array('value' => $value), $option);
454 common_element_end('select');
456 common_element('span', 'input_instructions', $instructions);
458 common_element_end('p');
460 function common_hidden($id, $value)
462 common_element('input', array('name' => $id,
468 function common_password($id, $label, $instructions=null)
470 common_element_start('p');
471 common_element('label', array('for' => $id), $label);
472 $attrs = array('name' => $id,
473 'type' => 'password',
474 'class' => 'password',
476 common_element('input', $attrs);
478 common_element('span', 'input_instructions', $instructions);
480 common_element_end('p');
483 function common_submit($id, $label, $cls='submit')
486 common_element_start('p');
487 common_element('input', array('type' => 'submit',
492 common_element_end('p');
495 function common_textarea($id, $label, $content=null, $instructions=null)
497 common_element_start('p');
498 common_element('label', array('for' => $id), $label);
499 common_element('textarea', array('rows' => 3,
503 ($content) ? $content : '');
505 common_element('span', 'input_instructions', $instructions);
507 common_element_end('p');
510 function common_timezone()
512 if (common_logged_in()) {
513 $user = common_current_user();
514 if ($user->timezone) {
515 return $user->timezone;
520 return $config['site']['timezone'];
523 function common_language()
526 // If there is a user logged in and they've set a language preference
527 // then return that one...
528 if (common_logged_in()) {
529 $user = common_current_user();
530 $user_language = $user->language;
532 return $user_language;
535 // Otherwise, find the best match for the languages requested by the
537 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
538 if (!empty($httplang)) {
539 $language = client_prefered_language($httplang);
544 // Finally, if none of the above worked, use the site's default...
545 return common_config('site', 'language');
547 // salted, hashed passwords are stored in the DB
549 function common_munge_password($password, $id)
551 return md5($password . $id);
554 // check if a username exists and has matching password
555 function common_check_user($nickname, $password)
557 // NEVER allow blank passwords, even if they match the DB
558 if (mb_strlen($password) == 0) {
561 $user = User::staticGet('nickname', $nickname);
562 if (is_null($user)) {
565 if (0 == strcmp(common_munge_password($password, $user->id),
574 // is the current user logged in?
575 function common_logged_in()
577 return (!is_null(common_current_user()));
580 function common_have_session()
582 return (0 != strcmp(session_id(), ''));
585 function common_ensure_session()
587 if (!common_have_session()) {
592 // Three kinds of arguments:
597 // Initialize to false; set to null if none found
601 function common_set_user($user)
606 if (is_null($user) && common_have_session()) {
608 unset($_SESSION['userid']);
610 } else if (is_string($user)) {
612 $user = User::staticGet('nickname', $nickname);
613 } else if (!($user instanceof User)) {
618 common_ensure_session();
619 $_SESSION['userid'] = $user->id;
626 function common_set_cookie($key, $value, $expiration=0)
628 $path = common_config('site', 'path');
629 $server = common_config('site', 'server');
631 if ($path && ($path != '/')) {
632 $cookiepath = '/' . $path . '/';
636 return setcookie($key,
643 define('REMEMBERME', 'rememberme');
644 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
646 function common_rememberme($user=null)
649 $user = common_current_user();
651 common_debug('No current user to remember', __FILE__);
656 $rm = new Remember_me();
658 $rm->code = common_good_rand(16);
659 $rm->user_id = $user->id;
661 // Wrap the insert in some good ol' fashioned transaction code
665 $result = $rm->insert();
668 common_log_db_error($rm, 'INSERT', __FILE__);
669 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
673 $rm->query('COMMIT');
675 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
677 $cookieval = $rm->user_id . ':' . $rm->code;
679 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
681 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
686 function common_remembered_user()
691 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
697 list($id, $code) = explode(':', $packed);
699 if (!$id || !$code) {
700 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
705 $rm = Remember_me::staticGet($code);
708 common_log(LOG_WARNING, 'No such remember code: ' . $code);
713 if ($rm->user_id != $id) {
714 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
719 $user = User::staticGet($rm->user_id);
722 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
728 $result = $rm->delete();
731 common_log_db_error($rm, 'DELETE', __FILE__);
732 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
737 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
739 common_set_user($user);
740 common_real_login(false);
742 // We issue a new cookie, so they can log in
743 // automatically again after this session
745 common_rememberme($user);
750 // must be called with a valid user!
752 function common_forgetme()
754 common_set_cookie(REMEMBERME, '', 0);
757 // who is the current user?
758 function common_current_user()
762 if ($_cur === false) {
764 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
765 common_ensure_session();
766 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
768 $_cur = User::staticGet($id);
773 // that didn't work; try to remember; will init $_cur to null on failure
774 $_cur = common_remembered_user();
777 common_debug("Got User " . $_cur->nickname);
778 common_debug("Faking session on remembered user");
779 // XXX: Is this necessary?
780 $_SESSION['userid'] = $_cur->id;
787 // Logins that are 'remembered' aren't 'real' -- they're subject to
788 // cookie-stealing. So, we don't let them do certain things. New reg,
789 // OpenID, and password logins _are_ real.
791 function common_real_login($real=true)
793 common_ensure_session();
794 $_SESSION['real_login'] = $real;
797 function common_is_real_login()
799 return common_logged_in() && $_SESSION['real_login'];
802 // get canonical version of nickname for comparison
803 function common_canonical_nickname($nickname)
805 // XXX: UTF-8 canonicalization (like combining chars)
806 return strtolower($nickname);
809 // get canonical version of email for comparison
810 function common_canonical_email($email)
812 // XXX: canonicalize UTF-8
813 // XXX: lcase the domain part
817 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$_+!*();/?:~-]))');
819 function common_render_content($text, $notice)
821 $r = common_render_text($text);
822 $id = $notice->profile_id;
823 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
824 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
825 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
829 function common_render_text($text)
831 $r = htmlspecialchars($text);
833 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
834 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
835 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
840 function common_render_uri_thingy($matches)
845 // Some heuristics for extracting URIs from surrounding punctuation
846 // Strip from trailing text...
847 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
849 $trailer = $matches[2];
853 ']' => '[', // technically disallowed in URIs, but used in Java docs
854 ')' => '(', // far too frequent in Wikipedia and MSDN
856 $final = substr($uri, -1, 1);
857 if (isset($pairs[$final])) {
858 $openers = substr_count($uri, $pairs[$final]);
859 $closers = substr_count($uri, $final);
860 if ($closers > $openers) {
861 // Assume the paren was opened outside the URI
862 $uri = substr($uri, 0, -1);
863 $trailer = $final . $trailer;
866 if ($longurl = common_longurl($uri)) {
867 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
868 $title = " title='$longurl'";
872 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
875 function common_longurl($short_url)
877 $long_url = common_shorten_link($short_url, true);
878 if ($long_url === $short_url) return false;
882 function common_longurl2($uri)
884 $uri_e = urlencode($uri);
885 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
886 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
887 return stripslashes($longurl['long_url']);
890 function common_shorten_links($text)
892 if (mb_strlen($text) <= 140) return $text;
893 static $cache = array();
894 if (isset($cache[$text])) return $cache[$text];
895 // \s = not a horizontal whitespace character (since PHP 5.2.4)
896 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
899 function common_shorten_link($url, $reverse = false)
901 static $url_cache = array();
902 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
904 $user = common_current_user();
906 $curlh = curl_init();
907 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
908 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
909 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
911 switch($user->urlshorteningservice) {
913 $short_url_service = new LilUrl;
914 $short_url = $short_url_service->shorten($url);
918 $short_url_service = new TightUrl;
919 $short_url = $short_url_service->shorten($url);
923 $short_url_service = new PtitUrl;
924 $short_url = $short_url_service->shorten($url);
928 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
929 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
933 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
934 $short_url = curl_exec($curlh);
937 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
938 $short_url = curl_exec($curlh);
941 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
942 $short_url = curl_exec($curlh);
945 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
946 $short_url = curl_exec($curlh);
955 $url_cache[(string)$short_url] = $url;
956 return (string)$short_url;
961 function common_xml_safe_str($str)
963 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
965 // Replace control, formatting, and surrogate characters with '*', ala Twitter
966 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
969 function common_tag_link($tag)
971 $canonical = common_canonical_tag($tag);
972 $url = common_local_url('tag', array('tag' => $canonical));
973 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
976 function common_canonical_tag($tag)
978 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
981 function common_valid_profile_tag($str)
983 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
986 function common_at_link($sender_id, $nickname)
988 $sender = Profile::staticGet($sender_id);
989 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
991 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
997 function common_at_hash_link($sender_id, $tag)
999 $user = User::staticGet($sender_id);
1003 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
1005 $url = common_local_url('subscriptions',
1006 array('nickname' => $user->nickname,
1008 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
1014 function common_relative_profile($sender, $nickname, $dt=null)
1016 // Try to find profiles this profile is subscribed to that have this nickname
1017 $recipient = new Profile();
1018 // XXX: use a join instead of a subquery
1019 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1020 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
1021 if ($recipient->find(true)) {
1022 // XXX: should probably differentiate between profiles with
1023 // the same name by date of most recent update
1026 // Try to find profiles that listen to this profile and that have this nickname
1027 $recipient = new Profile();
1028 // XXX: use a join instead of a subquery
1029 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1030 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
1031 if ($recipient->find(true)) {
1032 // XXX: should probably differentiate between profiles with
1033 // the same name by date of most recent update
1036 // If this is a local user, try to find a local user with that nickname.
1037 $sender = User::staticGet($sender->id);
1039 $recipient_user = User::staticGet('nickname', $nickname);
1040 if ($recipient_user) {
1041 return $recipient_user->getProfile();
1044 // Otherwise, no links. @messages from local users to remote users,
1045 // or from remote users to other remote users, are just
1046 // outside our ability to make intelligent guesses about
1050 // where should the avatar go for this user?
1052 function common_avatar_filename($id, $extension, $size=null, $extra=null)
1057 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
1059 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
1063 function common_avatar_path($filename)
1066 return INSTALLDIR . '/avatar/' . $filename;
1069 function common_avatar_url($filename)
1071 return common_path('avatar/'.$filename);
1074 function common_avatar_display_url($avatar)
1076 $server = common_config('avatar', 'server');
1078 return 'http://'.$server.'/'.$avatar->filename;
1080 return $avatar->url;
1084 function common_default_avatar($size)
1086 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
1087 AVATAR_STREAM_SIZE => 'stream',
1088 AVATAR_MINI_SIZE => 'mini');
1089 return theme_path('default-avatar-'.$sizenames[$size].'.png');
1092 function common_local_url($action, $args=null, $fragment=null)
1095 if (common_config('site','fancy')) {
1096 $url = common_fancy_url($action, $args);
1098 $url = common_simple_url($action, $args);
1100 if (!is_null($fragment)) {
1101 $url .= '#'.$fragment;
1106 function common_fancy_url($action, $args=null)
1108 switch (strtolower($action)) {
1110 if ($args && isset($args['page'])) {
1111 return common_path('?page=' . $args['page']);
1113 return common_path('');
1116 if ($args && isset($args['page'])) {
1117 return common_path('featured?page=' . $args['page']);
1119 return common_path('featured');
1122 if ($args && isset($args['page'])) {
1123 return common_path('favorited?page=' . $args['page']);
1125 return common_path('favorited');
1128 return common_path('rss');
1130 return common_path("api/statuses/public_timeline.atom");
1132 return common_path('xrds');
1134 return common_path('featuredrss');
1135 case 'favoritedrss':
1136 return common_path('favoritedrss');
1138 if ($args && $args['type']) {
1139 return common_path('opensearch/'.$args['type']);
1141 return common_path('opensearch/people');
1144 return common_path('doc/'.$args['title']);
1151 return common_path('main/'.$action);
1153 return common_path('main/tagother?id='.$args['id']);
1155 if ($args && $args['code']) {
1156 return common_path('main/register/'.$args['code']);
1158 return common_path('main/register');
1160 case 'remotesubscribe':
1161 if ($args && $args['nickname']) {
1162 return common_path('main/remote?nickname=' . $args['nickname']);
1164 return common_path('main/remote');
1167 return common_path($args['nickname'].'/nudge');
1169 return common_path('main/openid');
1170 case 'profilesettings':
1171 return common_path('settings/profile');
1172 case 'emailsettings':
1173 return common_path('settings/email');
1174 case 'openidsettings':
1175 return common_path('settings/openid');
1177 return common_path('settings/sms');
1178 case 'twittersettings':
1179 return common_path('settings/twitter');
1180 case 'othersettings':
1181 return common_path('settings/other');
1182 case 'deleteprofile':
1183 return common_path('settings/delete');
1185 if ($args && $args['replyto']) {
1186 return common_path('notice/new?replyto='.$args['replyto']);
1188 return common_path('notice/new');
1191 return common_path('notice/'.$args['notice']);
1192 case 'deletenotice':
1193 if ($args && $args['notice']) {
1194 return common_path('notice/delete/'.$args['notice']);
1196 return common_path('notice/delete');
1198 case 'microsummary':
1201 return common_path($args['nickname'].'/'.$action);
1206 if ($args && isset($args['page'])) {
1207 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1209 return common_path($args['nickname'].'/'.$action);
1211 case 'subscriptions':
1213 $nickname = $args['nickname'];
1214 unset($args['nickname']);
1215 if (isset($args['tag'])) {
1216 $tag = $args['tag'];
1217 unset($args['tag']);
1219 $params = http_build_query($args);
1221 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1223 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1226 return common_path($args['nickname'].'/all/rss');
1228 return common_path($args['nickname'].'/replies/rss');
1230 if (isset($args['limit']))
1231 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1232 return common_path($args['nickname'].'/rss');
1234 if ($args && isset($args['page'])) {
1235 return common_path($args['nickname'].'?page=' . $args['page']);
1237 return common_path($args['nickname']);
1240 case 'usertimeline':
1241 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1242 case 'confirmaddress':
1243 return common_path('main/confirmaddress/'.$args['code']);
1245 return common_path('user/'.$args['id']);
1246 case 'recoverpassword':
1247 $path = 'main/recoverpassword';
1248 if ($args['code']) {
1249 $path .= '/' . $args['code'];
1251 return common_path($path);
1253 return common_path('settings/im');
1254 case 'peoplesearch':
1255 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1256 case 'noticesearch':
1257 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1258 case 'noticesearchrss':
1259 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1260 case 'avatarbynickname':
1261 return common_path($args['nickname'].'/avatar/'.$args['size']);
1263 if (isset($args['tag']) && $args['tag']) {
1264 $path = 'tag/' . $args['tag'];
1265 unset($args['tag']);
1269 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1271 $path = 'peopletag/' . $args['tag'];
1272 unset($args['tag']);
1273 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1275 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1277 return common_path('main/favor');
1279 return common_path('main/disfavor');
1280 case 'showfavorites':
1281 if ($args && isset($args['page'])) {
1282 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1284 return common_path($args['nickname'].'/favorites');
1286 case 'favoritesrss':
1287 return common_path($args['nickname'].'/favorites/rss');
1289 return common_path('message/' . $args['message']);
1291 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1293 // XXX: do fancy URLs for all the API methods
1294 switch (strtolower($args['apiaction'])) {
1296 switch (strtolower($args['method'])) {
1297 case 'user_timeline.rss':
1298 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1299 case 'user_timeline.atom':
1300 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1301 case 'user_timeline.json':
1302 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1303 case 'user_timeline.xml':
1304 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1305 default: return common_simple_url($action, $args);
1307 default: return common_simple_url($action, $args);
1310 if ($args && isset($args['seconds'])) {
1311 return common_path('main/sup?seconds='.$args['seconds']);
1313 return common_path('main/sup');
1316 return common_simple_url($action, $args);
1320 function common_simple_url($action, $args=null)
1323 /* XXX: pretty URLs */
1326 foreach ($args as $key => $value) {
1327 $extra .= "&${key}=${value}";
1330 return common_path("index.php?action=${action}${extra}");
1333 function common_path($relative)
1336 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1337 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1340 function common_date_string($dt)
1342 // XXX: do some sexy date formatting
1343 // return date(DATE_RFC822, $dt);
1344 $t = strtotime($dt);
1348 if ($now < $t) { // that shouldn't happen!
1349 return common_exact_date($dt);
1350 } else if ($diff < 60) {
1351 return _('a few seconds ago');
1352 } else if ($diff < 92) {
1353 return _('about a minute ago');
1354 } else if ($diff < 3300) {
1355 return sprintf(_('about %d minutes ago'), round($diff/60));
1356 } else if ($diff < 5400) {
1357 return _('about an hour ago');
1358 } else if ($diff < 22 * 3600) {
1359 return sprintf(_('about %d hours ago'), round($diff/3600));
1360 } else if ($diff < 37 * 3600) {
1361 return _('about a day ago');
1362 } else if ($diff < 24 * 24 * 3600) {
1363 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1364 } else if ($diff < 46 * 24 * 3600) {
1365 return _('about a month ago');
1366 } else if ($diff < 330 * 24 * 3600) {
1367 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1368 } else if ($diff < 480 * 24 * 3600) {
1369 return _('about a year ago');
1371 return common_exact_date($dt);
1375 function common_exact_date($dt)
1381 $_utc = new DateTimeZone('UTC');
1382 $_siteTz = new DateTimeZone(common_timezone());
1385 $dateStr = date('d F Y H:i:s', strtotime($dt));
1386 $d = new DateTime($dateStr, $_utc);
1387 $d->setTimezone($_siteTz);
1388 return $d->format(DATE_RFC850);
1391 function common_date_w3dtf($dt)
1393 $dateStr = date('d F Y H:i:s', strtotime($dt));
1394 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1395 $d->setTimezone(new DateTimeZone(common_timezone()));
1396 return $d->format(DATE_W3C);
1399 function common_date_rfc2822($dt)
1401 $dateStr = date('d F Y H:i:s', strtotime($dt));
1402 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1403 $d->setTimezone(new DateTimeZone(common_timezone()));
1404 return $d->format('r');
1407 function common_date_iso8601($dt)
1409 $dateStr = date('d F Y H:i:s', strtotime($dt));
1410 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1411 $d->setTimezone(new DateTimeZone(common_timezone()));
1412 return $d->format('c');
1415 function common_sql_now()
1417 return strftime('%Y-%m-%d %H:%M:%S', time());
1420 function common_redirect($url, $code=307)
1422 static $status = array(301 => "Moved Permanently",
1425 307 => "Temporary Redirect");
1426 header("Status: ${code} $status[$code]");
1427 header("Location: $url");
1429 common_start_xml('a',
1430 '-//W3C//DTD XHTML 1.0 Strict//EN',
1431 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1432 common_element('a', array('href' => $url), $url);
1437 function common_save_replies($notice)
1439 // Alternative reply format
1441 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1444 // extract all @messages
1445 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1449 if ($cnt || $tname) {
1450 // XXX: is there another way to make an array copy?
1451 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1454 $sender = Profile::staticGet($notice->profile_id);
1458 // store replied only for first @ (what user/notice what the reply directed,
1459 // we assume first @ is it)
1461 for ($i=0; $i<count($names); $i++) {
1462 $nickname = $names[$i];
1463 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1467 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self
1468 $reply_for = $recipient;
1469 $recipient_notice = $reply_for->getCurrentNotice();
1470 if ($recipient_notice) {
1471 $orig = clone($notice);
1472 $notice->reply_to = $recipient_notice->id;
1473 $notice->update($orig);
1476 // Don't save replies from blocked profile to local user
1477 $recipient_user = User::staticGet('id', $recipient->id);
1478 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1481 $reply = new Reply();
1482 $reply->notice_id = $notice->id;
1483 $reply->profile_id = $recipient->id;
1484 $id = $reply->insert();
1486 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1487 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1488 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1491 $replied[$recipient->id] = 1;
1495 // Hash format replies, too
1496 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1498 foreach ($match[1] as $tag) {
1499 $tagged = Profile_tag::getTagged($sender->id, $tag);
1500 foreach ($tagged as $t) {
1501 if (!$replied[$t->id]) {
1502 // Don't save replies from blocked profile to local user
1503 $t_user = User::staticGet('id', $t->id);
1504 if ($t_user && $t_user->hasBlocked($sender)) {
1507 $reply = new Reply();
1508 $reply->notice_id = $notice->id;
1509 $reply->profile_id = $t->id;
1510 $id = $reply->insert();
1512 common_log_db_error($reply, 'INSERT', __FILE__);
1521 function common_broadcast_notice($notice, $remote=false)
1524 // Check to see if notice should go to Twitter
1525 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1526 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1528 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1530 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1531 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1533 $result = common_twitter_broadcast($notice, $flink);
1536 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1541 if (common_config('queue', 'enabled')) {
1543 return common_enqueue_notice($notice);
1545 return common_real_broadcast($notice, $remote);
1549 function common_twitter_broadcast($notice, $flink)
1553 $fuser = $flink->getForeignUser();
1554 $twitter_user = $fuser->nickname;
1555 $twitter_password = $flink->credentials;
1556 $uri = 'http://www.twitter.com/statuses/update.json';
1558 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1559 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1562 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1563 CURLOPT_POST => true,
1564 CURLOPT_POSTFIELDS => array(
1565 'status' => $statustxt,
1566 'source' => $config['integration']['source']
1568 CURLOPT_RETURNTRANSFER => true,
1569 CURLOPT_FAILONERROR => true,
1570 CURLOPT_HEADER => false,
1571 CURLOPT_FOLLOWLOCATION => true,
1572 CURLOPT_USERAGENT => "Laconica",
1573 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1574 CURLOPT_TIMEOUT => 120
1577 $ch = curl_init($uri);
1578 curl_setopt_array($ch, $options);
1579 $data = curl_exec($ch);
1580 $errmsg = curl_error($ch);
1583 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1591 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1596 // Twitter should return a status
1597 $status = json_decode($data);
1600 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1608 // Stick the notice on the queue
1610 function common_enqueue_notice($notice)
1612 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1613 $qi = new Queue_item();
1614 $qi->notice_id = $notice->id;
1615 $qi->transport = $transport;
1616 $qi->created = $notice->created;
1617 $result = $qi->insert();
1619 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1620 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1623 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1628 function common_dequeue_notice($notice)
1630 $qi = Queue_item::staticGet($notice->id);
1632 $result = $qi->delete();
1634 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1635 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1638 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1645 function common_real_broadcast($notice, $remote=false)
1649 // Make sure we have the OMB stuff
1650 require_once(INSTALLDIR.'/lib/omb.php');
1651 $success = omb_broadcast_remote_subscribers($notice);
1653 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1657 require_once(INSTALLDIR.'/lib/jabber.php');
1658 $success = jabber_broadcast_notice($notice);
1660 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1664 require_once(INSTALLDIR.'/lib/mail.php');
1665 $success = mail_broadcast_notice_sms($notice);
1667 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1671 $success = jabber_public_notice($notice);
1673 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1676 // XXX: broadcast notices to other IM
1680 function common_broadcast_profile($profile)
1682 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1683 require_once(INSTALLDIR.'/lib/omb.php');
1684 omb_broadcast_profile($profile);
1685 // XXX: Other broadcasts...?
1689 function common_profile_url($nickname)
1691 return common_local_url('showstream', array('nickname' => $nickname));
1694 // Don't call if nobody's logged in
1696 function common_notice_form($action=null, $content=null)
1698 $user = common_current_user();
1699 assert(!is_null($user));
1700 common_element_start('form', array('id' => 'status_form',
1702 'action' => common_local_url('newnotice')));
1703 common_element_start('p');
1704 common_element('label', array('for' => 'status_textarea',
1705 'id' => 'status_label'),
1706 sprintf(_('What\'s up, %s?'), $user->nickname));
1707 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1708 common_element('textarea', array('id' => 'status_textarea',
1711 'name' => 'status_textarea'),
1712 ($content) ? $content : '');
1713 common_hidden('token', common_session_token());
1715 common_hidden('returnto', $action);
1717 // set by JavaScript
1718 common_hidden('inreplyto', 'false');
1719 common_element('input', array('id' => 'status_submit',
1720 'name' => 'status_submit',
1722 'value' => _('Send')));
1723 common_element_end('p');
1724 common_element_end('form');
1727 // Should make up a reasonable root URL
1729 function common_root_url()
1731 return common_path('');
1734 // returns $bytes bytes of random data as a hexadecimal string
1735 // "good" here is a goal and not a guarantee
1737 function common_good_rand($bytes)
1739 // XXX: use random.org...?
1740 if (file_exists('/dev/urandom')) {
1741 return common_urandom($bytes);
1742 } else { // FIXME: this is probably not good enough
1743 return common_mtrand($bytes);
1747 function common_urandom($bytes)
1749 $h = fopen('/dev/urandom', 'rb');
1751 $src = fread($h, $bytes);
1754 for ($i = 0; $i < $bytes; $i++) {
1755 $enc .= sprintf("%02x", (ord($src[$i])));
1760 function common_mtrand($bytes)
1763 for ($i = 0; $i < $bytes; $i++) {
1764 $enc .= sprintf("%02x", mt_rand(0, 255));
1769 function common_set_returnto($url)
1771 common_ensure_session();
1772 $_SESSION['returnto'] = $url;
1775 function common_get_returnto()
1777 common_ensure_session();
1778 return $_SESSION['returnto'];
1781 function common_timestamp()
1783 return date('YmdHis');
1786 function common_ensure_syslog()
1788 static $initialized = false;
1789 if (!$initialized) {
1791 openlog($config['syslog']['appname'], 0, LOG_USER);
1792 $initialized = true;
1796 function common_log($priority, $msg, $filename=null)
1798 $logfile = common_config('site', 'logfile');
1800 $log = fopen($logfile, "a");
1802 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1803 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1804 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1805 fwrite($log, $output);
1809 common_ensure_syslog();
1810 syslog($priority, $msg);
1814 function common_debug($msg, $filename=null)
1817 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1819 common_log(LOG_DEBUG, $msg);
1823 function common_log_db_error(&$object, $verb, $filename=null)
1825 $objstr = common_log_objstring($object);
1826 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1827 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1830 function common_log_objstring(&$object)
1832 if (is_null($object)) {
1835 $arr = $object->toArray();
1837 foreach ($arr as $k => $v) {
1838 $fields[] = "$k='$v'";
1840 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1844 function common_valid_http_url($url)
1846 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1849 function common_valid_tag($tag)
1851 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1852 return (Validate::email($matches[1]) ||
1853 preg_match('/^([\w-\.]+)$/', $matches[1]));
1858 // Does a little before-after block for next/prev page
1860 function common_pagination($have_before, $have_after, $page, $action, $args=null)
1863 if ($have_before || $have_after) {
1864 common_element_start('div', array('id' => 'pagination'));
1865 common_element_start('ul', array('id' => 'nav_pagination'));
1869 $pargs = array('page' => $page-1);
1870 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1872 common_element_start('li', 'before');
1873 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1875 common_element_end('li');
1879 $pargs = array('page' => $page+1);
1880 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1881 common_element_start('li', 'after');
1882 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1884 common_element_end('li');
1887 if ($have_before || $have_after) {
1888 common_element_end('ul');
1889 common_element_end('div');
1893 /* Following functions are copied from MediaWiki GlobalFunctions.php
1894 * and written by Evan Prodromou. */
1896 function common_accept_to_prefs($accept, $def = '*/*')
1898 // No arg means accept anything (per HTTP spec)
1900 return array($def => 1);
1905 $parts = explode(',', $accept);
1907 foreach($parts as $part) {
1908 // FIXME: doesn't deal with params like 'text/html; level=1'
1909 @list($value, $qpart) = explode(';', $part);
1911 if(!isset($qpart)) {
1913 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1914 $prefs[$value] = $match[1];
1921 function common_mime_type_match($type, $avail)
1923 if(array_key_exists($type, $avail)) {
1926 $parts = explode('/', $type);
1927 if(array_key_exists($parts[0] . '/*', $avail)) {
1928 return $parts[0] . '/*';
1929 } elseif(array_key_exists('*/*', $avail)) {
1937 function common_negotiate_type($cprefs, $sprefs)
1941 foreach(array_keys($sprefs) as $type) {
1942 $parts = explode('/', $type);
1943 if($parts[1] != '*') {
1944 $ckey = common_mime_type_match($type, $cprefs);
1946 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1951 foreach(array_keys($cprefs) as $type) {
1952 $parts = explode('/', $type);
1953 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1954 $skey = common_mime_type_match($type, $sprefs);
1956 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1962 $besttype = "text/html";
1964 foreach(array_keys($combine) as $type) {
1965 if($combine[$type] > $bestq) {
1967 $bestq = $combine[$type];
1974 function common_config($main, $sub)
1977 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1980 function common_copy_args($from)
1983 $strip = get_magic_quotes_gpc();
1984 foreach ($from as $k => $v) {
1985 $to[$k] = ($strip) ? stripslashes($v) : $v;
1990 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1991 // This is used before handing a request off to OAuthRequest::from_request.
1992 function common_remove_magic_from_request()
1994 if(get_magic_quotes_gpc()) {
1995 $_POST=array_map('stripslashes',$_POST);
1996 $_GET=array_map('stripslashes',$_GET);
2000 function common_user_uri(&$user)
2002 return common_local_url('userbyid', array('id' => $user->id));
2005 function common_notice_uri(&$notice)
2007 return common_local_url('shownotice',
2008 array('notice' => $notice->id));
2011 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
2013 function common_confirmation_code($bits)
2015 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
2016 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
2017 $chars = ceil($bits/5);
2019 for ($i = 0; $i < $chars; $i++) {
2020 // XXX: convert to string and back
2021 $num = hexdec(common_good_rand(1));
2022 // XXX: randomness is too precious to throw away almost
2023 // 40% of the bits we get!
2024 $code .= $codechars[$num%32];
2029 // convert markup to HTML
2031 function common_markup_to_html($c)
2033 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
2034 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
2035 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
2036 return Markdown($c);
2039 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
2041 $avatar = $profile->getAvatar($size);
2043 return common_avatar_display_url($avatar);
2045 return common_default_avatar($size);
2049 function common_profile_uri($profile)
2054 $user = User::staticGet($profile->id);
2059 $remote = Remote_profile::staticGet($profile->id);
2061 return $remote->uri;
2063 // XXX: this is a very bad profile!
2067 function common_canonical_sms($sms)
2070 preg_replace('/\D/', '', $sms);
2074 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
2078 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
2082 case E_USER_WARNING:
2083 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
2087 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
2091 // FIXME: show error page if we're on the Web
2092 /* Don't execute PHP internal error handler */
2096 function common_session_token()
2098 common_ensure_session();
2099 if (!array_key_exists('token', $_SESSION)) {
2100 $_SESSION['token'] = common_good_rand(64);
2102 return $_SESSION['token'];
2105 function common_disfavor_form($notice)
2107 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
2109 'class' => 'disfavor',
2110 'action' => common_local_url('disfavor')));
2112 common_element('input', array('type' => 'hidden',
2113 'name' => 'token-'. $notice->id,
2114 'id' => 'token-'. $notice->id,
2116 'value' => common_session_token()));
2118 common_element('input', array('type' => 'hidden',
2120 'id' => 'notice-n'. $notice->id,
2121 'class' => 'notice',
2122 'value' => $notice->id));
2124 common_element('input', array('type' => 'submit',
2125 'id' => 'disfavor-submit-' . $notice->id,
2126 'name' => 'disfavor-submit-' . $notice->id,
2127 'class' => 'disfavor',
2128 'value' => 'Disfavor favorite',
2129 'title' => 'Remove this message from favorites'));
2130 common_element_end('form');
2133 function common_favor_form($notice)
2135 common_element_start('form', array('id' => 'favor-' . $notice->id,
2138 'action' => common_local_url('favor')));
2140 common_element('input', array('type' => 'hidden',
2141 'name' => 'token-'. $notice->id,
2142 'id' => 'token-'. $notice->id,
2144 'value' => common_session_token()));
2146 common_element('input', array('type' => 'hidden',
2148 'id' => 'notice-n'. $notice->id,
2149 'class' => 'notice',
2150 'value' => $notice->id));
2152 common_element('input', array('type' => 'submit',
2153 'id' => 'favor-submit-' . $notice->id,
2154 'name' => 'favor-submit-' . $notice->id,
2156 'value' => 'Add to favorites',
2157 'title' => 'Add this message to favorites'));
2158 common_element_end('form');
2161 function common_nudge_form($profile)
2163 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2164 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2165 common_hidden('token', common_session_token());
2166 common_element('input', array('type' => 'submit',
2167 'class' => 'submit',
2168 'value' => _('Send a nudge')));
2169 common_element_end('form');
2171 function common_nudge_response()
2173 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2176 function common_subscribe_form($profile)
2178 common_element_start('form', array('id' => 'subscribe-' . $profile->id,
2180 'class' => 'subscribe',
2181 'action' => common_local_url('subscribe')));
2182 common_hidden('token', common_session_token());
2183 common_element('input', array('id' => 'subscribeto-' . $profile->id,
2184 'name' => 'subscribeto',
2186 'value' => $profile->id));
2187 common_element('input', array('type' => 'submit',
2188 'class' => 'submit',
2189 'value' => _('Subscribe')));
2190 common_element_end('form');
2193 function common_unsubscribe_form($profile)
2195 common_element_start('form', array('id' => 'unsubscribe-' . $profile->id,
2197 'class' => 'unsubscribe',
2198 'action' => common_local_url('unsubscribe')));
2199 common_hidden('token', common_session_token());
2200 common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
2201 'name' => 'unsubscribeto',
2203 'value' => $profile->id));
2204 common_element('input', array('type' => 'submit',
2205 'class' => 'submit',
2206 'value' => _('Unsubscribe')));
2207 common_element_end('form');
2210 // XXX: Refactor this code
2211 function common_profile_new_message_nudge ($cur, $profile)
2213 $user = User::staticGet('id', $profile->id);
2215 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2216 common_element_start('li', array('id' => 'profile_send_a_new_message'));
2217 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2218 _('Send a message'));
2219 common_element_end('li');
2221 if ($user->email && $user->emailnotifynudge) {
2222 common_element_start('li', array('id' => 'profile_nudge'));
2223 common_nudge_form($user);
2224 common_element_end('li');
2229 function common_cache_key($extra)
2231 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2234 function common_keyize($str)
2236 $str = strtolower($str);
2237 $str = preg_replace('/\s/', '_', $str);
2241 function common_message_form($content, $user, $to)
2244 common_element_start('form', array('id' => 'message_form',
2246 'action' => common_local_url('newmessage')));
2248 $mutual_users = $user->mutuallySubscribedUsers();
2252 while ($mutual_users->fetch()) {
2253 if ($mutual_users->id != $user->id) {
2254 $mutual[$mutual_users->id] = $mutual_users->nickname;
2258 $mutual_users->free();
2259 unset($mutual_users);
2261 common_dropdown('to', _('To'), $mutual, null, false, $to->id);
2263 common_element_start('p');
2265 common_element('textarea', array('id' => 'message_content',
2268 'name' => 'content'),
2269 ($content) ? $content : '');
2271 common_element('input', array('id' => 'message_send',
2272 'name' => 'message_send',
2274 'value' => _('Send')));
2276 common_hidden('token', common_session_token());
2278 common_element_end('p');
2279 common_element_end('form');
2282 function common_memcache()
2284 static $cache = null;
2285 if (!common_config('memcached', 'enabled')) {
2289 $cache = new Memcache();
2290 $servers = common_config('memcached', 'server');
2291 if (is_array($servers)) {
2292 foreach($servers as $server) {
2293 $cache->addServer($server);
2296 $cache->addServer($servers);
2303 function common_compatible_license($from, $to)
2305 // XXX: better compatibility check needed here!
2306 return ($from == $to);
2309 /* These are almost identical, so we use a helper function */
2311 function common_block_form($profile, $args=null)
2313 common_blocking_form('block', _('Block'), $profile, $args);
2316 function common_unblock_form($profile, $args=null)
2318 common_blocking_form('unblock', _('Unblock'), $profile, $args);
2321 function common_blocking_form($type, $label, $profile, $args=null)
2323 common_element_start('form', array('id' => $type . '-' . $profile->id,
2326 'action' => common_local_url($type)));
2327 common_hidden('token', common_session_token());
2328 common_element('input', array('id' => $type . 'to-' . $profile->id,
2329 'name' => $type . 'to',
2331 'value' => $profile->id));
2332 common_element('input', array('type' => 'submit',
2333 'class' => 'submit',
2335 'value' => $label));
2337 foreach ($args as $k => $v) {
2338 common_hidden('returnto-' . $k, $v);
2341 common_element_end('form');