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) {
25 static $status = array(500 => 'Internal Server Error',
26 501 => 'Not Implemented',
28 503 => 'Service Unavailable',
29 504 => 'Gateway Timeout',
30 505 => 'HTTP Version Not Supported');
32 if (!array_key_exists($code, $status)) {
36 $status_string = $status[$code];
38 header('HTTP/1.1 '.$code.' '.$status_string);
39 header('Content-type: text/plain');
47 function common_user_error($msg, $code=400) {
48 static $status = array(400 => 'Bad Request',
49 401 => 'Unauthorized',
50 402 => 'Payment Required',
53 405 => 'Method Not Allowed',
54 406 => 'Not Acceptable',
55 407 => 'Proxy Authentication Required',
56 408 => 'Request Timeout',
59 411 => 'Length Required',
60 412 => 'Precondition Failed',
61 413 => 'Request Entity Too Large',
62 414 => 'Request-URI Too Long',
63 415 => 'Unsupported Media Type',
64 416 => 'Requested Range Not Satisfiable',
65 417 => 'Expectation Failed');
67 if (!array_key_exists($code, $status)) {
71 $status_string = $status[$code];
73 header('HTTP/1.1 '.$code.' '.$status_string);
75 common_show_header('Error');
76 common_element('div', array('class' => 'error'), $msg);
82 // Start an HTML element
83 function common_element_start($tag, $attrs=null) {
85 $xw->startElement($tag);
86 if (is_array($attrs)) {
87 foreach ($attrs as $name => $value) {
88 $xw->writeAttribute($name, $value);
90 } else if (is_string($attrs)) {
91 $xw->writeAttribute('class', $attrs);
95 function common_element_end($tag) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 // XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=null, $content=null) {
109 common_element_start($tag, $attrs);
111 if (!is_null($content)) {
114 common_element_end($tag);
117 function common_start_xml($doc=null, $public=null, $system=null, $indent=true) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent($indent);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 function common_init_locale($language=null) {
136 $language = common_language();
138 putenv('LANGUAGE='.$language);
139 putenv('LANG='.$language);
140 return setlocale(LC_ALL, $language . ".utf8",
142 $language . ".utf-8",
143 $language . ".UTF-8",
147 function common_init_language() {
148 mb_internal_encoding('UTF-8');
149 $language = common_language();
150 // So we don't have to make people install the gettext locales
151 $locale_set = common_init_locale($language);
152 bindtextdomain("laconica", common_config('site','locale_path'));
153 bind_textdomain_codeset("laconica", "UTF-8");
154 textdomain("laconica");
155 setlocale(LC_CTYPE, 'C');
157 common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
161 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
163 function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null) {
166 global $action; /* XXX: kind of cheating here. */
170 common_element_start('head');
171 common_element('title', null,
172 $pagetitle . " - " . $config['site']['name']);
173 common_element('link', array('rel' => 'stylesheet',
174 'type' => 'text/css',
175 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
176 'media' => 'screen, projection, tv'));
177 foreach (array(6,7) as $ver) {
178 if (file_exists(theme_file('ie'.$ver.'.css'))) {
179 // Yes, IE people should be put in jail.
180 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
181 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
185 common_element('script', array('type' => 'text/javascript',
186 'src' => common_path('js/jquery.min.js')),
188 common_element('script', array('type' => 'text/javascript',
189 'src' => common_path('js/jquery.form.js')),
191 common_element('script', array('type' => 'text/javascript',
192 'src' => common_path('js/xbImportNode.js')),
194 common_element('script', array('type' => 'text/javascript',
195 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
197 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
198 'href' => common_local_url('opensearch', array('type' => 'people')),
199 'title' => common_config('site', 'name').' People Search'));
201 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
202 'href' => common_local_url('opensearch', array('type' => 'notice')),
203 'title' => common_config('site', 'name').' Notice Search'));
207 call_user_func($callable, $data);
209 call_user_func($callable);
212 common_element_end('head');
213 common_element_start('body', $action);
214 common_element_start('div', array('id' => 'wrap'));
215 common_element_start('div', array('id' => 'header'));
217 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
218 || file_exists(theme_file('logo.png')))
220 common_element_start('a', array('href' => common_local_url('public')));
221 common_element('img', array('src' => isset($config['site']['logo']) ?
222 ($config['site']['logo']) : theme_path('logo.png'),
223 'alt' => $config['site']['name'],
225 common_element_end('a');
227 common_element_start('p', array('id' => 'branding'));
228 common_element('a', array('href' => common_local_url('public')),
229 $config['site']['name']);
230 common_element_end('p');
233 common_element('h1', 'pagetitle', $pagetitle);
237 call_user_func($headercall, $data);
239 call_user_func($headercall);
242 common_element_end('div');
243 common_element_start('div', array('id' => 'content'));
246 function common_start_html($type=null, $indent=true) {
249 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null;
251 // XXX: allow content negotiation for RDF, RSS, or XRDS
253 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
254 common_accept_to_prefs(PAGE_TYPE_PREFS));
257 common_user_error(_('This page is not available in a media type you accept'), 406);
262 header('Content-Type: '.$type);
264 common_start_xml('html',
265 '-//W3C//DTD XHTML 1.0 Strict//EN',
266 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent);
268 // FIXME: correct language for interface
270 $language = common_language();
272 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
273 'xml:lang' => $language,
274 'lang' => $language));
277 function common_show_footer() {
279 common_element_end('div'); // content div
281 common_element_start('div', array('id' => 'footer'));
282 common_element_start('div', 'laconica');
283 if (common_config('site', 'broughtby')) {
284 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
286 $instr = _('**%%site.name%%** is a microblogging service. ');
288 $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);
289 $output = common_markup_to_html($instr);
291 common_element_end('div');
292 common_element('img', array('id' => 'cc',
293 'src' => $config['license']['image'],
294 'alt' => $config['license']['title']));
295 common_element_start('p');
296 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
297 common_element('a', array('class' => 'license',
299 'href' => $config['license']['url']),
300 $config['license']['title']);
301 common_text(_('. Contributors should be attributed by full name or nickname.'));
302 common_element_end('p');
303 common_element_end('div');
304 common_element_end('div');
305 common_element_end('body');
306 common_element_end('html');
310 function common_text($txt) {
315 function common_raw($xml) {
320 function common_nav_menu() {
321 $user = common_current_user();
322 common_element_start('ul', array('id' => 'nav'));
324 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
327 common_menu_item(common_local_url('peoplesearch'), _('Search'));
329 common_menu_item(common_local_url('profilesettings'),
331 common_menu_item(common_local_url('invite'),
333 common_menu_item(common_local_url('logout'),
336 common_menu_item(common_local_url('login'), _('Login'));
337 if (!common_config('site', 'closed')) {
338 common_menu_item(common_local_url('register'), _('Register'));
340 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
342 common_menu_item(common_local_url('doc', array('title' => 'help')),
344 common_element_end('ul');
347 function common_foot_menu() {
348 common_element_start('ul', array('id' => 'nav_sub'));
349 common_menu_item(common_local_url('doc', array('title' => 'help')),
351 common_menu_item(common_local_url('doc', array('title' => 'about')),
353 common_menu_item(common_local_url('doc', array('title' => 'faq')),
355 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
357 common_menu_item(common_local_url('doc', array('title' => 'source')),
359 common_menu_item(common_local_url('doc', array('title' => 'contact')),
361 common_element_end('ul');
364 function common_menu_item($url, $text, $title=null, $is_selected=false) {
367 $lattrs['class'] = 'current';
369 common_element_start('li', $lattrs);
370 $attrs['href'] = $url;
372 $attrs['title'] = $title;
374 common_element('a', $attrs, $text);
375 common_element_end('li');
378 function common_input($id, $label, $value=null,$instructions=null) {
379 common_element_start('p');
380 common_element('label', array('for' => $id), $label);
381 $attrs = array('name' => $id,
383 'class' => 'input_text',
386 $attrs['value'] = htmlspecialchars($value);
388 common_element('input', $attrs);
390 common_element('span', 'input_instructions', $instructions);
392 common_element_end('p');
395 function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false)
397 common_element_start('p');
398 $attrs = array('name' => $id,
399 'type' => 'checkbox',
400 'class' => 'checkbox',
403 $attrs['value'] = htmlspecialchars($value);
406 $attrs['checked'] = 'checked';
409 $attrs['disabled'] = 'true';
411 common_element('input', $attrs);
413 common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label);
416 common_element('span', 'input_instructions', $instructions);
418 common_element_end('p');
421 function common_dropdown($id, $label, $content, $instructions=null, $blank_select=FALSE, $selected=null) {
422 common_element_start('p');
423 common_element('label', array('for' => $id), $label);
424 common_element_start('select', array('id' => $id, 'name' => $id));
426 common_element('option', array('value' => ''));
428 foreach ($content as $value => $option) {
429 if ($value == $selected) {
430 common_element('option', array('value' => $value, 'selected' => $value), $option);
432 common_element('option', array('value' => $value), $option);
435 common_element_end('select');
437 common_element('span', 'input_instructions', $instructions);
439 common_element_end('p');
441 function common_hidden($id, $value) {
442 common_element('input', array('name' => $id,
448 function common_password($id, $label, $instructions=null) {
449 common_element_start('p');
450 common_element('label', array('for' => $id), $label);
451 $attrs = array('name' => $id,
452 'type' => 'password',
453 'class' => 'password',
455 common_element('input', $attrs);
457 common_element('span', 'input_instructions', $instructions);
459 common_element_end('p');
462 function common_submit($id, $label, $cls='submit') {
464 common_element_start('p');
465 common_element('input', array('type' => 'submit',
470 common_element_end('p');
473 function common_textarea($id, $label, $content=null, $instructions=null) {
474 common_element_start('p');
475 common_element('label', array('for' => $id), $label);
476 common_element('textarea', array('rows' => 3,
480 ($content) ? $content : '');
482 common_element('span', 'input_instructions', $instructions);
484 common_element_end('p');
487 function common_timezone() {
488 if (common_logged_in()) {
489 $user = common_current_user();
490 if ($user->timezone) {
491 return $user->timezone;
496 return $config['site']['timezone'];
499 function common_language() {
501 // If there is a user logged in and they've set a language preference
502 // then return that one...
503 if (common_logged_in()) {
504 $user = common_current_user();
505 $user_language = $user->language;
507 return $user_language;
510 // Otherwise, find the best match for the languages requested by the
512 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
513 if (!empty($httplang)) {
514 $language = client_prefered_language($httplang);
519 // Finally, if none of the above worked, use the site's default...
520 return common_config('site', 'language');
522 // salted, hashed passwords are stored in the DB
524 function common_munge_password($password, $id) {
525 return md5($password . $id);
528 // check if a username exists and has matching password
529 function common_check_user($nickname, $password) {
530 // NEVER allow blank passwords, even if they match the DB
531 if (mb_strlen($password) == 0) {
534 $user = User::staticGet('nickname', $nickname);
535 if (is_null($user)) {
538 if (0 == strcmp(common_munge_password($password, $user->id),
547 // is the current user logged in?
548 function common_logged_in() {
549 return (!is_null(common_current_user()));
552 function common_have_session() {
553 return (0 != strcmp(session_id(), ''));
556 function common_ensure_session() {
557 if (!common_have_session()) {
562 // Three kinds of arguments:
567 // Initialize to false; set to null if none found
571 function common_set_user($user) {
575 if (is_null($user) && common_have_session()) {
577 unset($_SESSION['userid']);
579 } else if (is_string($user)) {
581 $user = User::staticGet('nickname', $nickname);
582 } else if (!($user instanceof User)) {
587 common_ensure_session();
588 $_SESSION['userid'] = $user->id;
595 function common_set_cookie($key, $value, $expiration=0) {
596 $path = common_config('site', 'path');
597 $server = common_config('site', 'server');
599 if ($path && ($path != '/')) {
600 $cookiepath = '/' . $path . '/';
604 return setcookie($key,
611 define('REMEMBERME', 'rememberme');
612 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
614 function common_rememberme($user=null) {
616 $user = common_current_user();
618 common_debug('No current user to remember', __FILE__);
623 $rm = new Remember_me();
625 $rm->code = common_good_rand(16);
626 $rm->user_id = $user->id;
628 // Wrap the insert in some good ol' fashioned transaction code
632 $result = $rm->insert();
635 common_log_db_error($rm, 'INSERT', __FILE__);
636 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
640 $rm->query('COMMIT');
642 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
644 $cookieval = $rm->user_id . ':' . $rm->code;
646 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
648 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
653 function common_remembered_user() {
657 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
663 list($id, $code) = explode(':', $packed);
665 if (!$id || !$code) {
666 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
671 $rm = Remember_me::staticGet($code);
674 common_log(LOG_WARNING, 'No such remember code: ' . $code);
679 if ($rm->user_id != $id) {
680 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
685 $user = User::staticGet($rm->user_id);
688 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
694 $result = $rm->delete();
697 common_log_db_error($rm, 'DELETE', __FILE__);
698 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
703 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
705 common_set_user($user);
706 common_real_login(false);
708 // We issue a new cookie, so they can log in
709 // automatically again after this session
711 common_rememberme($user);
716 // must be called with a valid user!
718 function common_forgetme() {
719 common_set_cookie(REMEMBERME, '', 0);
722 // who is the current user?
723 function common_current_user() {
726 if ($_cur === false) {
728 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
729 common_ensure_session();
730 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
732 $_cur = User::staticGet($id);
737 // that didn't work; try to remember; will init $_cur to null on failure
738 $_cur = common_remembered_user();
741 common_debug("Got User " . $_cur->nickname);
742 common_debug("Faking session on remembered user");
743 // XXX: Is this necessary?
744 $_SESSION['userid'] = $_cur->id;
751 // Logins that are 'remembered' aren't 'real' -- they're subject to
752 // cookie-stealing. So, we don't let them do certain things. New reg,
753 // OpenID, and password logins _are_ real.
755 function common_real_login($real=true) {
756 common_ensure_session();
757 $_SESSION['real_login'] = $real;
760 function common_is_real_login() {
761 return common_logged_in() && $_SESSION['real_login'];
764 // get canonical version of nickname for comparison
765 function common_canonical_nickname($nickname) {
766 // XXX: UTF-8 canonicalization (like combining chars)
767 return strtolower($nickname);
770 // get canonical version of email for comparison
771 function common_canonical_email($email) {
772 // XXX: canonicalize UTF-8
773 // XXX: lcase the domain part
777 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$_+!*();/?:~-]))');
779 function common_render_content($text, $notice) {
780 $r = common_render_text($text);
781 $id = $notice->profile_id;
782 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
783 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
784 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
788 function common_render_text($text) {
789 $r = htmlspecialchars($text);
791 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
792 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
793 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
798 function common_render_uri_thingy($matches) {
802 // Some heuristics for extracting URIs from surrounding punctuation
803 // Strip from trailing text...
804 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
806 $trailer = $matches[2];
810 ']' => '[', // technically disallowed in URIs, but used in Java docs
811 ')' => '(', // far too frequent in Wikipedia and MSDN
813 $final = substr($uri, -1, 1);
814 if (isset($pairs[$final])) {
815 $openers = substr_count($uri, $pairs[$final]);
816 $closers = substr_count($uri, $final);
817 if ($closers > $openers) {
818 // Assume the paren was opened outside the URI
819 $uri = substr($uri, 0, -1);
820 $trailer = $final . $trailer;
823 if ($longurl = common_longurl($uri)) {
824 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
825 $title = " title='$longurl'";
829 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
832 function common_longurl($short_url) {
833 $long_url = common_shorten_link($short_url, true);
834 if ($long_url === $short_url) return false;
838 function common_longurl2($uri) {
839 $uri_e = urlencode($uri);
840 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
841 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
842 return stripslashes($longurl['long_url']);
845 function common_shorten_links($text) {
846 if (mb_strlen($text) <= 140) return $text;
847 static $cache = array();
848 if (isset($cache[$text])) return $cache[$text];
849 // \s = not a horizontal whitespace character (since PHP 5.2.4)
850 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
853 function common_shorten_link($url, $reverse = false) {
854 static $url_cache = array();
855 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
857 $user = common_current_user();
859 $curlh = curl_init();
860 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
861 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
862 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
864 switch($user->urlshorteningservice) {
866 $short_url_service = new LilUrl;
867 $short_url = $short_url_service->shorten($url);
871 $short_url_service = new TightUrl;
872 $short_url = $short_url_service->shorten($url);
876 $short_url_service = new PtitUrl;
877 $short_url = $short_url_service->shorten($url);
881 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
882 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
886 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
887 $short_url = curl_exec($curlh);
890 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
891 $short_url = curl_exec($curlh);
894 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
895 $short_url = curl_exec($curlh);
898 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
899 $short_url = curl_exec($curlh);
908 $url_cache[(string)$short_url] = $url;
909 return (string)$short_url;
914 function common_xml_safe_str($str) {
915 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
917 // Replace control, formatting, and surrogate characters with '*', ala Twitter
918 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
921 function common_tag_link($tag) {
922 $canonical = common_canonical_tag($tag);
923 $url = common_local_url('tag', array('tag' => $canonical));
924 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
927 function common_canonical_tag($tag) {
928 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
931 function common_valid_profile_tag($str) {
932 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
935 function common_at_link($sender_id, $nickname) {
936 $sender = Profile::staticGet($sender_id);
937 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
939 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
945 function common_at_hash_link($sender_id, $tag) {
946 $user = User::staticGet($sender_id);
950 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
952 $url = common_local_url('subscriptions',
953 array('nickname' => $user->nickname,
955 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
961 function common_relative_profile($sender, $nickname, $dt=null) {
962 // Try to find profiles this profile is subscribed to that have this nickname
963 $recipient = new Profile();
964 // XXX: use a join instead of a subquery
965 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
966 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
967 if ($recipient->find(TRUE)) {
968 // XXX: should probably differentiate between profiles with
969 // the same name by date of most recent update
972 // Try to find profiles that listen to this profile and that have this nickname
973 $recipient = new Profile();
974 // XXX: use a join instead of a subquery
975 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
976 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
977 if ($recipient->find(TRUE)) {
978 // XXX: should probably differentiate between profiles with
979 // the same name by date of most recent update
982 // If this is a local user, try to find a local user with that nickname.
983 $sender = User::staticGet($sender->id);
985 $recipient_user = User::staticGet('nickname', $nickname);
986 if ($recipient_user) {
987 return $recipient_user->getProfile();
990 // Otherwise, no links. @messages from local users to remote users,
991 // or from remote users to other remote users, are just
992 // outside our ability to make intelligent guesses about
996 // where should the avatar go for this user?
998 function common_avatar_filename($id, $extension, $size=null, $extra=null) {
1002 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
1004 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
1008 function common_avatar_path($filename) {
1010 return INSTALLDIR . '/avatar/' . $filename;
1013 function common_avatar_url($filename) {
1014 return common_path('avatar/'.$filename);
1017 function common_avatar_display_url($avatar) {
1018 $server = common_config('avatar', 'server');
1020 return 'http://'.$server.'/'.$avatar->filename;
1022 return $avatar->url;
1026 function common_default_avatar($size) {
1027 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
1028 AVATAR_STREAM_SIZE => 'stream',
1029 AVATAR_MINI_SIZE => 'mini');
1030 return theme_path('default-avatar-'.$sizenames[$size].'.png');
1033 function common_local_url($action, $args=null, $fragment=null) {
1035 if (common_config('site','fancy')) {
1036 $url = common_fancy_url($action, $args);
1038 $url = common_simple_url($action, $args);
1040 if (!is_null($fragment)) {
1041 $url .= '#'.$fragment;
1046 function common_fancy_url($action, $args=null) {
1047 switch (strtolower($action)) {
1049 if ($args && isset($args['page'])) {
1050 return common_path('?page=' . $args['page']);
1052 return common_path('');
1055 if ($args && isset($args['page'])) {
1056 return common_path('featured?page=' . $args['page']);
1058 return common_path('featured');
1061 if ($args && isset($args['page'])) {
1062 return common_path('favorited?page=' . $args['page']);
1064 return common_path('favorited');
1067 return common_path('rss');
1069 return common_path("api/statuses/public_timeline.atom");
1071 return common_path('xrds');
1073 return common_path('featuredrss');
1074 case 'favoritedrss':
1075 return common_path('favoritedrss');
1077 if ($args && $args['type']) {
1078 return common_path('opensearch/'.$args['type']);
1080 return common_path('opensearch/people');
1083 return common_path('doc/'.$args['title']);
1090 return common_path('main/'.$action);
1092 return common_path('main/tagother?id='.$args['id']);
1094 if ($args && $args['code']) {
1095 return common_path('main/register/'.$args['code']);
1097 return common_path('main/register');
1099 case 'remotesubscribe':
1100 if ($args && $args['nickname']) {
1101 return common_path('main/remote?nickname=' . $args['nickname']);
1103 return common_path('main/remote');
1106 return common_path($args['nickname'].'/nudge');
1108 return common_path('main/openid');
1109 case 'profilesettings':
1110 return common_path('settings/profile');
1111 case 'emailsettings':
1112 return common_path('settings/email');
1113 case 'openidsettings':
1114 return common_path('settings/openid');
1116 return common_path('settings/sms');
1117 case 'twittersettings':
1118 return common_path('settings/twitter');
1119 case 'othersettings':
1120 return common_path('settings/other');
1121 case 'deleteprofile':
1122 return common_path('settings/delete');
1124 if ($args && $args['replyto']) {
1125 return common_path('notice/new?replyto='.$args['replyto']);
1127 return common_path('notice/new');
1130 return common_path('notice/'.$args['notice']);
1131 case 'deletenotice':
1132 if ($args && $args['notice']) {
1133 return common_path('notice/delete/'.$args['notice']);
1135 return common_path('notice/delete');
1137 case 'microsummary':
1140 return common_path($args['nickname'].'/'.$action);
1145 if ($args && isset($args['page'])) {
1146 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1148 return common_path($args['nickname'].'/'.$action);
1150 case 'subscriptions':
1152 $nickname = $args['nickname'];
1153 unset($args['nickname']);
1154 if (isset($args['tag'])) {
1155 $tag = $args['tag'];
1156 unset($args['tag']);
1158 $params = http_build_query($args);
1160 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1162 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1165 return common_path($args['nickname'].'/all/rss');
1167 return common_path($args['nickname'].'/replies/rss');
1169 if (isset($args['limit']))
1170 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1171 return common_path($args['nickname'].'/rss');
1173 if ($args && isset($args['page'])) {
1174 return common_path($args['nickname'].'?page=' . $args['page']);
1176 return common_path($args['nickname']);
1179 case 'usertimeline':
1180 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1181 case 'confirmaddress':
1182 return common_path('main/confirmaddress/'.$args['code']);
1184 return common_path('user/'.$args['id']);
1185 case 'recoverpassword':
1186 $path = 'main/recoverpassword';
1187 if ($args['code']) {
1188 $path .= '/' . $args['code'];
1190 return common_path($path);
1192 return common_path('settings/im');
1193 case 'peoplesearch':
1194 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1195 case 'noticesearch':
1196 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1197 case 'noticesearchrss':
1198 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1199 case 'avatarbynickname':
1200 return common_path($args['nickname'].'/avatar/'.$args['size']);
1202 if (isset($args['tag']) && $args['tag']) {
1203 $path = 'tag/' . $args['tag'];
1204 unset($args['tag']);
1208 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1210 $path = 'peopletag/' . $args['tag'];
1211 unset($args['tag']);
1212 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1214 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1216 return common_path('main/favor');
1218 return common_path('main/disfavor');
1219 case 'showfavorites':
1220 if ($args && isset($args['page'])) {
1221 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1223 return common_path($args['nickname'].'/favorites');
1225 case 'favoritesrss':
1226 return common_path($args['nickname'].'/favorites/rss');
1228 return common_path('message/' . $args['message']);
1230 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1232 // XXX: do fancy URLs for all the API methods
1233 switch (strtolower($args['apiaction'])) {
1235 switch (strtolower($args['method'])) {
1236 case 'user_timeline.rss':
1237 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1238 case 'user_timeline.atom':
1239 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1240 case 'user_timeline.json':
1241 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1242 case 'user_timeline.xml':
1243 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1244 default: return common_simple_url($action, $args);
1246 default: return common_simple_url($action, $args);
1249 if ($args && isset($args['seconds'])) {
1250 return common_path('main/sup?seconds='.$args['seconds']);
1252 return common_path('main/sup');
1255 return common_simple_url($action, $args);
1259 function common_simple_url($action, $args=null) {
1261 /* XXX: pretty URLs */
1264 foreach ($args as $key => $value) {
1265 $extra .= "&${key}=${value}";
1268 return common_path("index.php?action=${action}${extra}");
1271 function common_path($relative) {
1273 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1274 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1277 function common_date_string($dt) {
1278 // XXX: do some sexy date formatting
1279 // return date(DATE_RFC822, $dt);
1280 $t = strtotime($dt);
1284 if ($now < $t) { // that shouldn't happen!
1285 return common_exact_date($dt);
1286 } else if ($diff < 60) {
1287 return _('a few seconds ago');
1288 } else if ($diff < 92) {
1289 return _('about a minute ago');
1290 } else if ($diff < 3300) {
1291 return sprintf(_('about %d minutes ago'), round($diff/60));
1292 } else if ($diff < 5400) {
1293 return _('about an hour ago');
1294 } else if ($diff < 22 * 3600) {
1295 return sprintf(_('about %d hours ago'), round($diff/3600));
1296 } else if ($diff < 37 * 3600) {
1297 return _('about a day ago');
1298 } else if ($diff < 24 * 24 * 3600) {
1299 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1300 } else if ($diff < 46 * 24 * 3600) {
1301 return _('about a month ago');
1302 } else if ($diff < 330 * 24 * 3600) {
1303 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1304 } else if ($diff < 480 * 24 * 3600) {
1305 return _('about a year ago');
1307 return common_exact_date($dt);
1311 function common_exact_date($dt) {
1316 $_utc = new DateTimeZone('UTC');
1317 $_siteTz = new DateTimeZone(common_timezone());
1320 $dateStr = date('d F Y H:i:s', strtotime($dt));
1321 $d = new DateTime($dateStr, $_utc);
1322 $d->setTimezone($_siteTz);
1323 return $d->format(DATE_RFC850);
1326 function common_date_w3dtf($dt) {
1327 $dateStr = date('d F Y H:i:s', strtotime($dt));
1328 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1329 $d->setTimezone(new DateTimeZone(common_timezone()));
1330 return $d->format(DATE_W3C);
1333 function common_date_rfc2822($dt) {
1334 $dateStr = date('d F Y H:i:s', strtotime($dt));
1335 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1336 $d->setTimezone(new DateTimeZone(common_timezone()));
1337 return $d->format('r');
1340 function common_date_iso8601($dt) {
1341 $dateStr = date('d F Y H:i:s', strtotime($dt));
1342 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1343 $d->setTimezone(new DateTimeZone(common_timezone()));
1344 return $d->format('c');
1347 function common_sql_now() {
1348 return strftime('%Y-%m-%d %H:%M:%S', time());
1351 function common_redirect($url, $code=307) {
1352 static $status = array(301 => "Moved Permanently",
1355 307 => "Temporary Redirect");
1356 header("Status: ${code} $status[$code]");
1357 header("Location: $url");
1359 common_start_xml('a',
1360 '-//W3C//DTD XHTML 1.0 Strict//EN',
1361 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1362 common_element('a', array('href' => $url), $url);
1367 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) {
1452 // Check to see if notice should go to Twitter
1453 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1454 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1456 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1458 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1459 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1461 $result = common_twitter_broadcast($notice, $flink);
1464 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1469 if (common_config('queue', 'enabled')) {
1471 return common_enqueue_notice($notice);
1473 return common_real_broadcast($notice, $remote);
1477 function common_twitter_broadcast($notice, $flink) {
1480 $fuser = $flink->getForeignUser();
1481 $twitter_user = $fuser->nickname;
1482 $twitter_password = $flink->credentials;
1483 $uri = 'http://www.twitter.com/statuses/update.json';
1485 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1486 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1489 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1490 CURLOPT_POST => true,
1491 CURLOPT_POSTFIELDS => array(
1492 'status' => $statustxt,
1493 'source' => $config['integration']['source']
1495 CURLOPT_RETURNTRANSFER => true,
1496 CURLOPT_FAILONERROR => true,
1497 CURLOPT_HEADER => false,
1498 CURLOPT_FOLLOWLOCATION => true,
1499 CURLOPT_USERAGENT => "Laconica",
1500 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1501 CURLOPT_TIMEOUT => 120
1504 $ch = curl_init($uri);
1505 curl_setopt_array($ch, $options);
1506 $data = curl_exec($ch);
1507 $errmsg = curl_error($ch);
1510 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1518 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1523 // Twitter should return a status
1524 $status = json_decode($data);
1527 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1535 // Stick the notice on the queue
1537 function common_enqueue_notice($notice) {
1538 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1539 $qi = new Queue_item();
1540 $qi->notice_id = $notice->id;
1541 $qi->transport = $transport;
1542 $qi->created = $notice->created;
1543 $result = $qi->insert();
1545 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1546 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1549 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1554 function common_dequeue_notice($notice) {
1555 $qi = Queue_item::staticGet($notice->id);
1557 $result = $qi->delete();
1559 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1560 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1563 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1570 function common_real_broadcast($notice, $remote=false) {
1573 // Make sure we have the OMB stuff
1574 require_once(INSTALLDIR.'/lib/omb.php');
1575 $success = omb_broadcast_remote_subscribers($notice);
1577 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1581 require_once(INSTALLDIR.'/lib/jabber.php');
1582 $success = jabber_broadcast_notice($notice);
1584 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1588 require_once(INSTALLDIR.'/lib/mail.php');
1589 $success = mail_broadcast_notice_sms($notice);
1591 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1595 $success = jabber_public_notice($notice);
1597 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1600 // XXX: broadcast notices to other IM
1604 function common_broadcast_profile($profile) {
1605 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1606 require_once(INSTALLDIR.'/lib/omb.php');
1607 omb_broadcast_profile($profile);
1608 // XXX: Other broadcasts...?
1612 function common_profile_url($nickname) {
1613 return common_local_url('showstream', array('nickname' => $nickname));
1616 // Don't call if nobody's logged in
1618 function common_notice_form($action=null, $content=null) {
1619 $user = common_current_user();
1620 assert(!is_null($user));
1621 common_element_start('form', array('id' => 'status_form',
1623 'action' => common_local_url('newnotice')));
1624 common_element_start('p');
1625 common_element('label', array('for' => 'status_textarea',
1626 'id' => 'status_label'),
1627 sprintf(_('What\'s up, %s?'), $user->nickname));
1628 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1629 common_element('textarea', array('id' => 'status_textarea',
1632 'name' => 'status_textarea'),
1633 ($content) ? $content : '');
1634 common_hidden('token', common_session_token());
1636 common_hidden('returnto', $action);
1638 // set by JavaScript
1639 common_hidden('inreplyto', 'false');
1640 common_element('input', array('id' => 'status_submit',
1641 'name' => 'status_submit',
1643 'value' => _('Send')));
1644 common_element_end('p');
1645 common_element_end('form');
1648 // Should make up a reasonable root URL
1650 function common_root_url() {
1651 return common_path('');
1654 // returns $bytes bytes of random data as a hexadecimal string
1655 // "good" here is a goal and not a guarantee
1657 function common_good_rand($bytes) {
1658 // XXX: use random.org...?
1659 if (file_exists('/dev/urandom')) {
1660 return common_urandom($bytes);
1661 } else { // FIXME: this is probably not good enough
1662 return common_mtrand($bytes);
1666 function common_urandom($bytes) {
1667 $h = fopen('/dev/urandom', 'rb');
1669 $src = fread($h, $bytes);
1672 for ($i = 0; $i < $bytes; $i++) {
1673 $enc .= sprintf("%02x", (ord($src[$i])));
1678 function common_mtrand($bytes) {
1680 for ($i = 0; $i < $bytes; $i++) {
1681 $enc .= sprintf("%02x", mt_rand(0, 255));
1686 function common_set_returnto($url) {
1687 common_ensure_session();
1688 $_SESSION['returnto'] = $url;
1691 function common_get_returnto() {
1692 common_ensure_session();
1693 return $_SESSION['returnto'];
1696 function common_timestamp() {
1697 return date('YmdHis');
1700 function common_ensure_syslog() {
1701 static $initialized = false;
1702 if (!$initialized) {
1704 openlog($config['syslog']['appname'], 0, LOG_USER);
1705 $initialized = true;
1709 function common_log($priority, $msg, $filename=null) {
1710 $logfile = common_config('site', 'logfile');
1712 $log = fopen($logfile, "a");
1714 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1715 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1716 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1717 fwrite($log, $output);
1721 common_ensure_syslog();
1722 syslog($priority, $msg);
1726 function common_debug($msg, $filename=null) {
1728 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1730 common_log(LOG_DEBUG, $msg);
1734 function common_log_db_error(&$object, $verb, $filename=null) {
1735 $objstr = common_log_objstring($object);
1736 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1737 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1740 function common_log_objstring(&$object) {
1741 if (is_null($object)) {
1744 $arr = $object->toArray();
1746 foreach ($arr as $k => $v) {
1747 $fields[] = "$k='$v'";
1749 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1753 function common_valid_http_url($url) {
1754 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1757 function common_valid_tag($tag) {
1758 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1759 return (Validate::email($matches[1]) ||
1760 preg_match('/^([\w-\.]+)$/', $matches[1]));
1765 // Does a little before-after block for next/prev page
1767 function common_pagination($have_before, $have_after, $page, $action, $args=null) {
1769 if ($have_before || $have_after) {
1770 common_element_start('div', array('id' => 'pagination'));
1771 common_element_start('ul', array('id' => 'nav_pagination'));
1775 $pargs = array('page' => $page-1);
1776 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1778 common_element_start('li', 'before');
1779 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1781 common_element_end('li');
1785 $pargs = array('page' => $page+1);
1786 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1787 common_element_start('li', 'after');
1788 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1790 common_element_end('li');
1793 if ($have_before || $have_after) {
1794 common_element_end('ul');
1795 common_element_end('div');
1799 /* Following functions are copied from MediaWiki GlobalFunctions.php
1800 * and written by Evan Prodromou. */
1802 function common_accept_to_prefs($accept, $def = '*/*') {
1803 // No arg means accept anything (per HTTP spec)
1805 return array($def => 1);
1810 $parts = explode(',', $accept);
1812 foreach($parts as $part) {
1813 // FIXME: doesn't deal with params like 'text/html; level=1'
1814 @list($value, $qpart) = explode(';', $part);
1816 if(!isset($qpart)) {
1818 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1819 $prefs[$value] = $match[1];
1826 function common_mime_type_match($type, $avail) {
1827 if(array_key_exists($type, $avail)) {
1830 $parts = explode('/', $type);
1831 if(array_key_exists($parts[0] . '/*', $avail)) {
1832 return $parts[0] . '/*';
1833 } elseif(array_key_exists('*/*', $avail)) {
1841 function common_negotiate_type($cprefs, $sprefs) {
1844 foreach(array_keys($sprefs) as $type) {
1845 $parts = explode('/', $type);
1846 if($parts[1] != '*') {
1847 $ckey = common_mime_type_match($type, $cprefs);
1849 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1854 foreach(array_keys($cprefs) as $type) {
1855 $parts = explode('/', $type);
1856 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1857 $skey = common_mime_type_match($type, $sprefs);
1859 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1865 $besttype = "text/html";
1867 foreach(array_keys($combine) as $type) {
1868 if($combine[$type] > $bestq) {
1870 $bestq = $combine[$type];
1877 function common_config($main, $sub) {
1879 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1882 function common_copy_args($from) {
1884 $strip = get_magic_quotes_gpc();
1885 foreach ($from as $k => $v) {
1886 $to[$k] = ($strip) ? stripslashes($v) : $v;
1891 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1892 // This is used before handing a request off to OAuthRequest::from_request.
1893 function common_remove_magic_from_request() {
1894 if(get_magic_quotes_gpc()) {
1895 $_POST=array_map('stripslashes',$_POST);
1896 $_GET=array_map('stripslashes',$_GET);
1900 function common_user_uri(&$user) {
1901 return common_local_url('userbyid', array('id' => $user->id));
1904 function common_notice_uri(&$notice) {
1905 return common_local_url('shownotice',
1906 array('notice' => $notice->id));
1909 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1911 function common_confirmation_code($bits) {
1912 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1913 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1914 $chars = ceil($bits/5);
1916 for ($i = 0; $i < $chars; $i++) {
1917 // XXX: convert to string and back
1918 $num = hexdec(common_good_rand(1));
1919 // XXX: randomness is too precious to throw away almost
1920 // 40% of the bits we get!
1921 $code .= $codechars[$num%32];
1926 // convert markup to HTML
1928 function common_markup_to_html($c) {
1929 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1930 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1931 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1932 return Markdown($c);
1935 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1936 $avatar = $profile->getAvatar($size);
1938 return common_avatar_display_url($avatar);
1940 return common_default_avatar($size);
1944 function common_profile_uri($profile) {
1948 $user = User::staticGet($profile->id);
1953 $remote = Remote_profile::staticGet($profile->id);
1955 return $remote->uri;
1957 // XXX: this is a very bad profile!
1961 function common_canonical_sms($sms) {
1963 preg_replace('/\D/', '', $sms);
1967 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1970 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1974 case E_USER_WARNING:
1975 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1979 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1983 // FIXME: show error page if we're on the Web
1984 /* Don't execute PHP internal error handler */
1988 function common_session_token() {
1989 common_ensure_session();
1990 if (!array_key_exists('token', $_SESSION)) {
1991 $_SESSION['token'] = common_good_rand(64);
1993 return $_SESSION['token'];
1996 function common_disfavor_form($notice) {
1997 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1999 'class' => 'disfavor',
2000 'action' => common_local_url('disfavor')));
2002 common_element('input', array('type' => 'hidden',
2003 'name' => 'token-'. $notice->id,
2004 'id' => 'token-'. $notice->id,
2006 'value' => common_session_token()));
2008 common_element('input', array('type' => 'hidden',
2010 'id' => 'notice-n'. $notice->id,
2011 'class' => 'notice',
2012 'value' => $notice->id));
2014 common_element('input', array('type' => 'submit',
2015 'id' => 'disfavor-submit-' . $notice->id,
2016 'name' => 'disfavor-submit-' . $notice->id,
2017 'class' => 'disfavor',
2018 'value' => 'Disfavor favorite',
2019 'title' => 'Remove this message from favorites'));
2020 common_element_end('form');
2023 function common_favor_form($notice) {
2024 common_element_start('form', array('id' => 'favor-' . $notice->id,
2027 'action' => common_local_url('favor')));
2029 common_element('input', array('type' => 'hidden',
2030 'name' => 'token-'. $notice->id,
2031 'id' => 'token-'. $notice->id,
2033 'value' => common_session_token()));
2035 common_element('input', array('type' => 'hidden',
2037 'id' => 'notice-n'. $notice->id,
2038 'class' => 'notice',
2039 'value' => $notice->id));
2041 common_element('input', array('type' => 'submit',
2042 'id' => 'favor-submit-' . $notice->id,
2043 'name' => 'favor-submit-' . $notice->id,
2045 'value' => 'Add to favorites',
2046 'title' => 'Add this message to favorites'));
2047 common_element_end('form');
2050 function common_nudge_form($profile) {
2051 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2052 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2053 common_hidden('token', common_session_token());
2054 common_element('input', array('type' => 'submit',
2055 'class' => 'submit',
2056 'value' => _('Send a nudge')));
2057 common_element_end('form');
2059 function common_nudge_response() {
2060 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2063 function common_subscribe_form($profile) {
2064 common_element_start('form', array('id' => 'subscribe-' . $profile->id,
2066 'class' => 'subscribe',
2067 'action' => common_local_url('subscribe')));
2068 common_hidden('token', common_session_token());
2069 common_element('input', array('id' => 'subscribeto-' . $profile->id,
2070 'name' => 'subscribeto',
2072 'value' => $profile->id));
2073 common_element('input', array('type' => 'submit',
2074 'class' => 'submit',
2075 'value' => _('Subscribe')));
2076 common_element_end('form');
2079 function common_unsubscribe_form($profile) {
2080 common_element_start('form', array('id' => 'unsubscribe-' . $profile->id,
2082 'class' => 'unsubscribe',
2083 'action' => common_local_url('unsubscribe')));
2084 common_hidden('token', common_session_token());
2085 common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
2086 'name' => 'unsubscribeto',
2088 'value' => $profile->id));
2089 common_element('input', array('type' => 'submit',
2090 'class' => 'submit',
2091 'value' => _('Unsubscribe')));
2092 common_element_end('form');
2095 // XXX: Refactor this code
2096 function common_profile_new_message_nudge ($cur, $profile) {
2097 $user = User::staticGet('id', $profile->id);
2099 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2100 common_element_start('li', array('id' => 'profile_send_a_new_message'));
2101 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2102 _('Send a message'));
2103 common_element_end('li');
2105 if ($user->email && $user->emailnotifynudge) {
2106 common_element_start('li', array('id' => 'profile_nudge'));
2107 common_nudge_form($user);
2108 common_element_end('li');
2113 function common_cache_key($extra) {
2114 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2117 function common_keyize($str) {
2118 $str = strtolower($str);
2119 $str = preg_replace('/\s/', '_', $str);
2123 function common_message_form($content, $user, $to) {
2125 common_element_start('form', array('id' => 'message_form',
2127 'action' => common_local_url('newmessage')));
2129 $mutual_users = $user->mutuallySubscribedUsers();
2133 while ($mutual_users->fetch()) {
2134 if ($mutual_users->id != $user->id) {
2135 $mutual[$mutual_users->id] = $mutual_users->nickname;
2139 $mutual_users->free();
2140 unset($mutual_users);
2142 common_dropdown('to', _('To'), $mutual, null, FALSE, $to->id);
2144 common_element_start('p');
2146 common_element('textarea', array('id' => 'message_content',
2149 'name' => 'content'),
2150 ($content) ? $content : '');
2152 common_element('input', array('id' => 'message_send',
2153 'name' => 'message_send',
2155 'value' => _('Send')));
2157 common_hidden('token', common_session_token());
2159 common_element_end('p');
2160 common_element_end('form');
2163 function common_memcache() {
2164 static $cache = null;
2165 if (!common_config('memcached', 'enabled')) {
2169 $cache = new Memcache();
2170 $servers = common_config('memcached', 'server');
2171 if (is_array($servers)) {
2172 foreach($servers as $server) {
2173 $cache->addServer($server);
2176 $cache->addServer($servers);
2183 function common_compatible_license($from, $to) {
2184 // XXX: better compatibility check needed here!
2185 return ($from == $to);
2188 /* These are almost identical, so we use a helper function */
2190 function common_block_form($profile, $args=null) {
2191 common_blocking_form('block', _('Block'), $profile, $args);
2194 function common_unblock_form($profile, $args=null) {
2195 common_blocking_form('unblock', _('Unblock'), $profile, $args);
2198 function common_blocking_form($type, $label, $profile, $args=null) {
2199 common_element_start('form', array('id' => $type . '-' . $profile->id,
2202 'action' => common_local_url($type)));
2203 common_hidden('token', common_session_token());
2204 common_element('input', array('id' => $type . 'to-' . $profile->id,
2205 'name' => $type . 'to',
2207 'value' => $profile->id));
2208 common_element('input', array('type' => 'submit',
2209 'class' => 'submit',
2211 'value' => $label));
2213 foreach ($args as $k => $v) {
2214 common_hidden('returnto-' . $k, $v);
2217 common_element_end('form');