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) */
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) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 function common_init_language() {
135 mb_internal_encoding('UTF-8');
136 $language = common_language();
137 # So we don't have to make people install the gettext locales
138 putenv('LANGUAGE='.$language);
139 putenv('LANG='.$language);
140 $locale_set = setlocale(LC_ALL, $language . ".utf8",
142 $language . ".utf-8",
143 $language . ".UTF-8",
145 bindtextdomain("laconica", common_config('site','locale_path'));
146 bind_textdomain_codeset("laconica", "UTF-8");
147 textdomain("laconica");
148 setlocale(LC_CTYPE, 'C');
150 common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
154 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
156 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
162 common_element_start('head');
163 common_element('title', NULL,
164 $pagetitle . " - " . $config['site']['name']);
165 common_element('link', array('rel' => 'stylesheet',
166 'type' => 'text/css',
167 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
168 'media' => 'screen, projection, tv'));
169 foreach (array(6,7) as $ver) {
170 if (file_exists(theme_file('ie'.$ver.'.css'))) {
171 # Yes, IE people should be put in jail.
172 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
173 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
177 common_element('script', array('type' => 'text/javascript',
178 'src' => common_path('js/jquery.min.js')),
180 common_element('script', array('type' => 'text/javascript',
181 'src' => common_path('js/jquery.form.js')),
183 common_element('script', array('type' => 'text/javascript',
184 'src' => common_path('js/xbImportNode.js')),
186 common_element('script', array('type' => 'text/javascript',
187 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
189 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
190 'href' => common_local_url('opensearch', array('type' => 'people')),
191 'title' => common_config('site', 'name').' People Search'));
193 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
194 'href' => common_local_url('opensearch', array('type' => 'notice')),
195 'title' => common_config('site', 'name').' Notice Search'));
199 call_user_func($callable, $data);
201 call_user_func($callable);
204 common_element_end('head');
205 common_element_start('body');
206 common_element_start('div', array('id' => 'wrap'));
207 common_element_start('div', array('id' => 'header'));
209 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
210 || file_exists(theme_file('logo.png')))
212 common_element_start('a', array('href' => common_local_url('public')));
213 common_element('img', array('src' => isset($config['site']['logo']) ?
214 ($config['site']['logo']) : theme_path('logo.png'),
215 'alt' => $config['site']['name'],
217 common_element_end('a');
219 common_element_start('p', array('id' => 'branding'));
220 common_element('a', array('href' => common_local_url('public')),
221 $config['site']['name']);
222 common_element_end('p');
225 common_element('h1', 'pagetitle', $pagetitle);
229 call_user_func($headercall, $data);
231 call_user_func($headercall);
234 common_element_end('div');
235 common_element_start('div', array('id' => 'content'));
238 function common_start_html($type=NULL) {
241 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
243 # XXX: allow content negotiation for RDF, RSS, or XRDS
245 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
246 common_accept_to_prefs(PAGE_TYPE_PREFS));
249 common_user_error(_('This page is not available in a media type you accept'), 406);
254 header('Content-Type: '.$type);
256 common_start_xml('html',
257 '-//W3C//DTD XHTML 1.0 Strict//EN',
258 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
260 # FIXME: correct language for interface
262 $language = common_language();
264 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
265 'xml:lang' => $language,
266 'lang' => $language));
269 function common_show_footer() {
271 common_element_end('div'); # content div
273 common_element_start('div', array('id' => 'footer'));
274 common_element_start('div', 'laconica');
275 if (common_config('site', 'broughtby')) {
276 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
278 $instr = _('**%%site.name%%** is a microblogging service. ');
280 $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);
281 $output = common_markup_to_html($instr);
283 common_element_end('div');
284 common_element('img', array('id' => 'cc',
285 'src' => $config['license']['image'],
286 'alt' => $config['license']['title']));
287 common_element_start('p');
288 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
289 common_element('a', array('class' => 'license',
291 'href' => $config['license']['url']),
292 $config['license']['title']);
293 common_text(_('. Contributors should be attributed by full name or nickname.'));
294 common_element_end('p');
295 common_element_end('div');
296 common_element_end('div');
297 common_element_end('body');
298 common_element_end('html');
302 function common_text($txt) {
307 function common_raw($xml) {
312 function common_nav_menu() {
313 $user = common_current_user();
314 common_element_start('ul', array('id' => 'nav'));
316 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
319 common_menu_item(common_local_url('peoplesearch'), _('Search'));
321 common_menu_item(common_local_url('profilesettings'),
323 common_menu_item(common_local_url('invite'),
325 common_menu_item(common_local_url('logout'),
328 common_menu_item(common_local_url('login'), _('Login'));
329 if (!common_config('site', 'closed')) {
330 common_menu_item(common_local_url('register'), _('Register'));
332 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
334 common_element_end('ul');
337 function common_foot_menu() {
338 common_element_start('ul', array('id' => 'nav_sub'));
339 common_menu_item(common_local_url('doc', array('title' => 'help')),
341 common_menu_item(common_local_url('doc', array('title' => 'about')),
343 common_menu_item(common_local_url('doc', array('title' => 'faq')),
345 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
347 common_menu_item(common_local_url('doc', array('title' => 'source')),
349 common_menu_item(common_local_url('doc', array('title' => 'contact')),
351 common_element_end('ul');
354 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
357 $lattrs['class'] = 'current';
359 common_element_start('li', $lattrs);
360 $attrs['href'] = $url;
362 $attrs['title'] = $title;
364 common_element('a', $attrs, $text);
365 common_element_end('li');
368 function common_input($id, $label, $value=NULL,$instructions=NULL) {
369 common_element_start('p');
370 common_element('label', array('for' => $id), $label);
371 $attrs = array('name' => $id,
373 'class' => 'input_text',
376 $attrs['value'] = htmlspecialchars($value);
378 common_element('input', $attrs);
380 common_element('span', 'input_instructions', $instructions);
382 common_element_end('p');
385 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false)
387 common_element_start('p');
388 $attrs = array('name' => $id,
389 'type' => 'checkbox',
390 'class' => 'checkbox',
393 $attrs['value'] = htmlspecialchars($value);
396 $attrs['checked'] = 'checked';
399 $attrs['disabled'] = 'true';
401 common_element('input', $attrs);
404 common_element('span', 'checkbox_label', $label);
407 common_element('span', 'input_instructions', $instructions);
409 common_element_end('p');
412 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
413 common_element_start('p');
414 common_element('label', array('for' => $id), $label);
415 common_element_start('select', array('id' => $id, 'name' => $id));
417 common_element('option', array('value' => ''));
419 foreach ($content as $value => $option) {
420 if ($value == $selected) {
421 common_element('option', array('value' => $value, 'selected' => $value), $option);
423 common_element('option', array('value' => $value), $option);
426 common_element_end('select');
428 common_element('span', 'input_instructions', $instructions);
430 common_element_end('p');
432 function common_hidden($id, $value) {
433 common_element('input', array('name' => $id,
439 function common_password($id, $label, $instructions=NULL) {
440 common_element_start('p');
441 common_element('label', array('for' => $id), $label);
442 $attrs = array('name' => $id,
443 'type' => 'password',
444 'class' => 'password',
446 common_element('input', $attrs);
448 common_element('span', 'input_instructions', $instructions);
450 common_element_end('p');
453 function common_submit($id, $label, $cls='submit') {
455 common_element_start('p');
456 common_element('input', array('type' => 'submit',
461 common_element_end('p');
464 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
465 common_element_start('p');
466 common_element('label', array('for' => $id), $label);
467 common_element('textarea', array('rows' => 3,
471 ($content) ? $content : '');
473 common_element('span', 'input_instructions', $instructions);
475 common_element_end('p');
478 function common_timezone() {
479 if (common_logged_in()) {
480 $user = common_current_user();
481 if ($user->timezone) {
482 return $user->timezone;
487 return $config['site']['timezone'];
490 function common_language() {
492 // If there is a user logged in and they've set a language preference
493 // then return that one...
494 if (common_logged_in()) {
495 $user = common_current_user();
496 $user_language = $user->language;
498 return $user_language;
501 // Otherwise, find the best match for the languages requested by the
503 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
504 if (!empty($httplang)) {
505 $language = client_prefered_language($httplang);
510 // Finally, if none of the above worked, use the site's default...
511 return common_config('site', 'language');
513 # salted, hashed passwords are stored in the DB
515 function common_munge_password($password, $id) {
516 return md5($password . $id);
519 # check if a username exists and has matching password
520 function common_check_user($nickname, $password) {
521 # NEVER allow blank passwords, even if they match the DB
522 if (mb_strlen($password) == 0) {
525 $user = User::staticGet('nickname', $nickname);
526 if (is_null($user)) {
529 if (0 == strcmp(common_munge_password($password, $user->id),
538 # is the current user logged in?
539 function common_logged_in() {
540 return (!is_null(common_current_user()));
543 function common_have_session() {
544 return (0 != strcmp(session_id(), ''));
547 function common_ensure_session() {
548 if (!common_have_session()) {
553 # Three kinds of arguments:
558 function common_set_user($user) {
559 if (is_null($user) && common_have_session()) {
560 unset($_SESSION['userid']);
562 } else if (is_string($user)) {
564 $user = User::staticGet('nickname', $nickname);
565 } else if (!($user instanceof User)) {
570 common_ensure_session();
571 $_SESSION['userid'] = $user->id;
577 function common_set_cookie($key, $value, $expiration=0) {
578 $path = common_config('site', 'path');
579 $server = common_config('site', 'server');
581 if ($path && ($path != '/')) {
582 $cookiepath = '/' . $path . '/';
586 return setcookie($key,
593 define('REMEMBERME', 'rememberme');
594 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
596 function common_rememberme($user=NULL) {
598 $user = common_current_user();
600 common_debug('No current user to remember', __FILE__);
604 $rm = new Remember_me();
605 $rm->code = common_good_rand(16);
606 $rm->user_id = $user->id;
607 $result = $rm->insert();
609 common_log_db_error($rm, 'INSERT', __FILE__);
610 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
613 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
614 common_set_cookie(REMEMBERME,
615 implode(':', array($rm->user_id, $rm->code)),
616 time() + REMEMBERME_EXPIRY);
620 function common_remembered_user() {
623 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
625 list($id, $code) = explode(':', $packed);
627 $rm = Remember_me::staticGet($code);
628 if ($rm && ($rm->user_id == $id)) {
629 $user = User::staticGet($rm->user_id);
632 $result = $rm->delete();
634 common_log_db_error($rm, 'DELETE', __FILE__);
637 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
638 common_set_user($user->nickname);
639 common_real_login(false);
640 # We issue a new cookie, so they can log in
641 # automatically again after this session
642 common_rememberme($user);
651 # must be called with a valid user!
653 function common_forgetme() {
654 common_set_cookie(REMEMBERME, '', 0);
657 # who is the current user?
658 function common_current_user() {
659 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
660 common_ensure_session();
661 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
663 # note: this should cache
664 $user = User::staticGet($id);
668 # that didn't work; try to remember
669 $user = common_remembered_user();
671 common_debug("Got User " . $user->nickname);
672 common_debug("Faking session on remembered user");
673 $_SESSION['userid'] = $user->id;
678 # Logins that are 'remembered' aren't 'real' -- they're subject to
679 # cookie-stealing. So, we don't let them do certain things. New reg,
680 # OpenID, and password logins _are_ real.
682 function common_real_login($real=true) {
683 common_ensure_session();
684 $_SESSION['real_login'] = $real;
687 function common_is_real_login() {
688 return common_logged_in() && $_SESSION['real_login'];
691 # get canonical version of nickname for comparison
692 function common_canonical_nickname($nickname) {
693 # XXX: UTF-8 canonicalization (like combining chars)
694 return strtolower($nickname);
697 # get canonical version of email for comparison
698 function common_canonical_email($email) {
699 # XXX: canonicalize UTF-8
700 # XXX: lcase the domain part
704 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$_+!*();/?:~-]))');
706 function common_render_content($text, $notice) {
707 $r = common_render_text($text);
708 $id = $notice->profile_id;
709 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
710 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
714 function common_render_text($text) {
715 $r = htmlspecialchars($text);
717 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
718 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
719 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
724 function common_render_uri_thingy($matches) {
728 # Some heuristics for extracting URIs from surrounding punctuation
729 # Strip from trailing text...
730 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
732 $trailer = $matches[2];
736 ']' => '[', # technically disallowed in URIs, but used in Java docs
737 ')' => '(', # far too frequent in Wikipedia and MSDN
739 $final = substr($uri, -1, 1);
740 if (isset($pairs[$final])) {
741 $openers = substr_count($uri, $pairs[$final]);
742 $closers = substr_count($uri, $final);
743 if ($closers > $openers) {
744 // Assume the paren was opened outside the URI
745 $uri = substr($uri, 0, -1);
746 $trailer = $final . $trailer;
749 if ($longurl = common_longurl($uri)) {
750 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
751 $title = " title='$longurl'";
755 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
758 function common_longurl($uri) {
759 $uri_e = urlencode($uri);
760 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
761 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
762 return stripslashes($longurl['long_url']);
765 function common_shorten_links($text) {
766 // \s = not a horizontal whitespace character (since PHP 5.2.4)
767 // RYM this should prevent * preceded URLs from being processed but it its a char
768 // $r = preg_replace('@[^*](https?://[^)\]>\s]+)@e', "common_shorten_link('\\1')", $r);
769 return preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
772 function common_shorten_link($long_url) {
774 $user = common_current_user();
776 $curlh = curl_init();
777 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
778 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
779 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
781 switch($user->urlshorteningservice) {
783 $short_url_service = new LilUrl;
784 $short_url = $short_url_service->shorten($long_url);
788 $short_url_service = new TightUrl;
789 $short_url = $short_url_service->shorten($long_url);
793 $short_url_service = new PtitUrl;
794 $short_url = $short_url_service->shorten($long_url);
798 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($long_url));
799 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
803 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($long_url));
804 $short_url = curl_exec($curlh);
807 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($long_url));
808 $short_url = curl_exec($curlh);
811 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($long_url));
812 $short_url = curl_exec($curlh);
815 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($long_url));
816 $short_url = curl_exec($curlh);
830 function common_xml_safe_str($str) {
831 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
833 // Replace control, formatting, and surrogate characters with '*', ala Twitter
834 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
837 function common_tag_link($tag) {
838 $canonical = common_canonical_tag($tag);
839 $url = common_local_url('tag', array('tag' => $canonical));
840 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
843 function common_canonical_tag($tag) {
844 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
847 function common_valid_profile_tag($str) {
848 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
851 function common_at_link($sender_id, $nickname) {
852 $sender = Profile::staticGet($sender_id);
853 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
855 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
861 function common_relative_profile($sender, $nickname, $dt=NULL) {
862 # Try to find profiles this profile is subscribed to that have this nickname
863 $recipient = new Profile();
864 # XXX: use a join instead of a subquery
865 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
866 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
867 if ($recipient->find(TRUE)) {
868 # XXX: should probably differentiate between profiles with
869 # the same name by date of most recent update
872 # Try to find profiles that listen to this profile and that have this nickname
873 $recipient = new Profile();
874 # XXX: use a join instead of a subquery
875 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
876 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
877 if ($recipient->find(TRUE)) {
878 # XXX: should probably differentiate between profiles with
879 # the same name by date of most recent update
882 # If this is a local user, try to find a local user with that nickname.
883 $sender = User::staticGet($sender->id);
885 $recipient_user = User::staticGet('nickname', $nickname);
886 if ($recipient_user) {
887 return $recipient_user->getProfile();
890 # Otherwise, no links. @messages from local users to remote users,
891 # or from remote users to other remote users, are just
892 # outside our ability to make intelligent guesses about
896 // where should the avatar go for this user?
898 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
902 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
904 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
908 function common_avatar_path($filename) {
910 return INSTALLDIR . '/avatar/' . $filename;
913 function common_avatar_url($filename) {
914 return common_path('avatar/'.$filename);
917 function common_avatar_display_url($avatar) {
918 $server = common_config('avatar', 'server');
920 return 'http://'.$server.'/'.$avatar->filename;
926 function common_default_avatar($size) {
927 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
928 AVATAR_STREAM_SIZE => 'stream',
929 AVATAR_MINI_SIZE => 'mini');
930 return theme_path('default-avatar-'.$sizenames[$size].'.png');
933 function common_local_url($action, $args=NULL, $fragment=NULL) {
935 if (common_config('site','fancy')) {
936 $url = common_fancy_url($action, $args);
938 $url = common_simple_url($action, $args);
940 if (!is_null($fragment)) {
941 $url .= '#'.$fragment;
946 function common_fancy_url($action, $args=NULL) {
947 switch (strtolower($action)) {
949 if ($args && isset($args['page'])) {
950 return common_path('?page=' . $args['page']);
952 return common_path('');
955 if ($args && isset($args['page'])) {
956 return common_path('featured?page=' . $args['page']);
958 return common_path('featured');
961 if ($args && isset($args['page'])) {
962 return common_path('favorited?page=' . $args['page']);
964 return common_path('favorited');
967 return common_path('rss');
969 return common_path('xrds');
971 return common_path('featuredrss');
973 return common_path('favoritedrss');
975 if ($args && $args['type']) {
976 return common_path('opensearch/'.$args['type']);
978 return common_path('opensearch/people');
981 return common_path('doc/'.$args['title']);
987 return common_path('main/'.$action);
989 return common_path('main/tagother?id='.$args['id']);
991 if ($args && $args['code']) {
992 return common_path('main/register/'.$args['code']);
994 return common_path('main/register');
996 case 'remotesubscribe':
997 if ($args && $args['nickname']) {
998 return common_path('main/remote?nickname=' . $args['nickname']);
1000 return common_path('main/remote');
1003 return common_path($args['nickname'].'/nudge');
1005 return common_path('main/openid');
1006 case 'profilesettings':
1007 return common_path('settings/profile');
1008 case 'emailsettings':
1009 return common_path('settings/email');
1010 case 'openidsettings':
1011 return common_path('settings/openid');
1013 return common_path('settings/sms');
1014 case 'twittersettings':
1015 return common_path('settings/twitter');
1016 case 'othersettings':
1017 return common_path('settings/other');
1019 if ($args && $args['replyto']) {
1020 return common_path('notice/new?replyto='.$args['replyto']);
1022 return common_path('notice/new');
1025 return common_path('notice/'.$args['notice']);
1026 case 'deletenotice':
1027 if ($args && $args['notice']) {
1028 return common_path('notice/delete/'.$args['notice']);
1030 return common_path('notice/delete');
1034 return common_path($args['nickname'].'/'.$action);
1039 if ($args && isset($args['page'])) {
1040 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1042 return common_path($args['nickname'].'/'.$action);
1044 case 'subscriptions':
1046 $nickname = $args['nickname'];
1047 unset($args['nickname']);
1048 if (isset($args['tag'])) {
1049 $tag = $args['tag'];
1050 unset($args['tag']);
1052 $params = http_build_query($args);
1054 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1056 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1059 return common_path($args['nickname'].'/all/rss');
1061 return common_path($args['nickname'].'/replies/rss');
1063 return common_path($args['nickname'].'/rss');
1065 if ($args && isset($args['page'])) {
1066 return common_path($args['nickname'].'?page=' . $args['page']);
1068 return common_path($args['nickname']);
1071 case 'usertimeline':
1072 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1073 case 'confirmaddress':
1074 return common_path('main/confirmaddress/'.$args['code']);
1076 return common_path('user/'.$args['id']);
1077 case 'recoverpassword':
1078 $path = 'main/recoverpassword';
1079 if ($args['code']) {
1080 $path .= '/' . $args['code'];
1082 return common_path($path);
1084 return common_path('settings/im');
1085 case 'peoplesearch':
1086 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1087 case 'noticesearch':
1088 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1089 case 'noticesearchrss':
1090 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1091 case 'avatarbynickname':
1092 return common_path($args['nickname'].'/avatar/'.$args['size']);
1094 if (isset($args['tag']) && $args['tag']) {
1095 $path = 'tag/' . $args['tag'];
1096 unset($args['tag']);
1100 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1102 $path = 'peopletag/' . $args['tag'];
1103 unset($args['tag']);
1104 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1106 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1108 return common_path('main/favor');
1110 return common_path('main/disfavor');
1111 case 'showfavorites':
1112 if ($args && isset($args['page'])) {
1113 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1115 return common_path($args['nickname'].'/favorites');
1117 case 'favoritesrss':
1118 return common_path($args['nickname'].'/favorites/rss');
1120 return common_path('message/' . $args['message']);
1122 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1124 # XXX: do fancy URLs for all the API methods
1125 switch (strtolower($args['apiaction'])) {
1127 switch (strtolower($args['method'])) {
1128 case 'user_timeline.rss':
1129 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1130 case 'user_timeline.atom':
1131 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1132 case 'user_timeline.rss':
1133 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1134 case 'user_timeline.atom':
1135 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1136 default: return common_simple_url($action, $args);
1138 default: return common_simple_url($action, $args);
1141 if ($args && isset($args['seconds'])) {
1142 return common_path('main/sup?seconds='.$args['seconds']);
1144 return common_path('main/sup');
1147 return common_simple_url($action, $args);
1151 function common_simple_url($action, $args=NULL) {
1153 /* XXX: pretty URLs */
1156 foreach ($args as $key => $value) {
1157 $extra .= "&${key}=${value}";
1160 return common_path("index.php?action=${action}${extra}");
1163 function common_path($relative) {
1165 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1166 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1169 function common_date_string($dt) {
1170 // XXX: do some sexy date formatting
1171 // return date(DATE_RFC822, $dt);
1172 $t = strtotime($dt);
1176 if ($now < $t) { # that shouldn't happen!
1177 return common_exact_date($dt);
1178 } else if ($diff < 60) {
1179 return _('a few seconds ago');
1180 } else if ($diff < 92) {
1181 return _('about a minute ago');
1182 } else if ($diff < 3300) {
1183 return sprintf(_('about %d minutes ago'), round($diff/60));
1184 } else if ($diff < 5400) {
1185 return _('about an hour ago');
1186 } else if ($diff < 22 * 3600) {
1187 return sprintf(_('about %d hours ago'), round($diff/3600));
1188 } else if ($diff < 37 * 3600) {
1189 return _('about a day ago');
1190 } else if ($diff < 24 * 24 * 3600) {
1191 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1192 } else if ($diff < 46 * 24 * 3600) {
1193 return _('about a month ago');
1194 } else if ($diff < 330 * 24 * 3600) {
1195 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1196 } else if ($diff < 480 * 24 * 3600) {
1197 return _('about a year ago');
1199 return common_exact_date($dt);
1203 function common_exact_date($dt) {
1208 $_utc = new DateTimeZone('UTC');
1209 $_siteTz = new DateTimeZone(common_timezone());
1212 $dateStr = date('d F Y H:i:s', strtotime($dt));
1213 $d = new DateTime($dateStr, $_utc);
1214 $d->setTimezone($_siteTz);
1215 return $d->format(DATE_RFC850);
1218 function common_date_w3dtf($dt) {
1219 $dateStr = date('d F Y H:i:s', strtotime($dt));
1220 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1221 $d->setTimezone(new DateTimeZone(common_timezone()));
1222 return $d->format(DATE_W3C);
1225 function common_date_rfc2822($dt) {
1226 $dateStr = date('d F Y H:i:s', strtotime($dt));
1227 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1228 $d->setTimezone(new DateTimeZone(common_timezone()));
1229 return $d->format('r');
1232 function common_date_iso8601($dt) {
1233 $dateStr = date('d F Y H:i:s', strtotime($dt));
1234 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1235 $d->setTimezone(new DateTimeZone(common_timezone()));
1236 return $d->format('c');
1239 function common_sql_now() {
1240 return strftime('%Y-%m-%d %H:%M:%S', time());
1243 function common_redirect($url, $code=307) {
1244 static $status = array(301 => "Moved Permanently",
1247 307 => "Temporary Redirect");
1248 header("Status: ${code} $status[$code]");
1249 header("Location: $url");
1251 common_start_xml('a',
1252 '-//W3C//DTD XHTML 1.0 Strict//EN',
1253 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1254 common_element('a', array('href' => $url), $url);
1259 function common_save_replies($notice) {
1260 # Alternative reply format
1262 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1265 # extract all @messages
1266 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1267 if (!$cnt && !$tname) {
1270 # XXX: is there another way to make an array copy?
1271 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1272 $sender = Profile::staticGet($notice->profile_id);
1273 # store replied only for first @ (what user/notice what the reply directed,
1274 # we assume first @ is it)
1275 for ($i=0; $i<count($names); $i++) {
1276 $nickname = $names[$i];
1277 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1281 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1282 $reply_for = $recipient;
1283 $recipient_notice = $reply_for->getCurrentNotice();
1284 if ($recipient_notice) {
1285 $orig = clone($notice);
1286 $notice->reply_to = $recipient_notice->id;
1287 $notice->update($orig);
1290 $reply = new Reply();
1291 $reply->notice_id = $notice->id;
1292 $reply->profile_id = $recipient->id;
1293 $id = $reply->insert();
1295 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1296 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1297 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1303 function common_broadcast_notice($notice, $remote=false) {
1305 // Check to see if notice should go to Twitter
1306 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1307 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1309 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1311 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1312 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1314 $result = common_twitter_broadcast($notice, $flink);
1317 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1322 if (common_config('queue', 'enabled')) {
1324 return common_enqueue_notice($notice);
1326 return common_real_broadcast($notice, $remote);
1330 function common_twitter_broadcast($notice, $flink) {
1333 $fuser = $flink->getForeignUser();
1334 $twitter_user = $fuser->nickname;
1335 $twitter_password = $flink->credentials;
1336 $uri = 'http://www.twitter.com/statuses/update.json';
1338 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1339 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1342 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1343 CURLOPT_POST => true,
1344 CURLOPT_POSTFIELDS => array(
1345 'status' => $statustxt,
1346 'source' => $config['integration']['source']
1348 CURLOPT_RETURNTRANSFER => true,
1349 CURLOPT_FAILONERROR => true,
1350 CURLOPT_HEADER => false,
1351 CURLOPT_FOLLOWLOCATION => true,
1352 CURLOPT_USERAGENT => "Laconica",
1353 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1354 CURLOPT_TIMEOUT => 120
1357 $ch = curl_init($uri);
1358 curl_setopt_array($ch, $options);
1359 $data = curl_exec($ch);
1360 $errmsg = curl_error($ch);
1363 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1371 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1376 // Twitter should return a status
1377 $status = json_decode($data);
1380 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1388 # Stick the notice on the queue
1390 function common_enqueue_notice($notice) {
1391 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1392 $qi = new Queue_item();
1393 $qi->notice_id = $notice->id;
1394 $qi->transport = $transport;
1395 $qi->created = $notice->created;
1396 $result = $qi->insert();
1398 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1399 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1402 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1407 function common_dequeue_notice($notice) {
1408 $qi = Queue_item::staticGet($notice->id);
1410 $result = $qi->delete();
1412 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1413 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1416 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1423 function common_real_broadcast($notice, $remote=false) {
1426 # Make sure we have the OMB stuff
1427 require_once(INSTALLDIR.'/lib/omb.php');
1428 $success = omb_broadcast_remote_subscribers($notice);
1430 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1434 require_once(INSTALLDIR.'/lib/jabber.php');
1435 $success = jabber_broadcast_notice($notice);
1437 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1441 require_once(INSTALLDIR.'/lib/mail.php');
1442 $success = mail_broadcast_notice_sms($notice);
1444 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1448 $success = jabber_public_notice($notice);
1450 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1453 // XXX: broadcast notices to other IM
1457 function common_broadcast_profile($profile) {
1458 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1459 require_once(INSTALLDIR.'/lib/omb.php');
1460 omb_broadcast_profile($profile);
1461 // XXX: Other broadcasts...?
1465 function common_profile_url($nickname) {
1466 return common_local_url('showstream', array('nickname' => $nickname));
1469 # Don't call if nobody's logged in
1471 function common_notice_form($action=NULL, $content=NULL) {
1472 $user = common_current_user();
1473 assert(!is_null($user));
1474 common_element_start('form', array('id' => 'status_form',
1476 'action' => common_local_url('newnotice')));
1477 common_element_start('p');
1478 common_element('label', array('for' => 'status_textarea',
1479 'id' => 'status_label'),
1480 sprintf(_('What\'s up, %s?'), $user->nickname));
1481 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1482 common_element('textarea', array('id' => 'status_textarea',
1485 'name' => 'status_textarea'),
1486 ($content) ? $content : '');
1487 common_hidden('token', common_session_token());
1489 common_hidden('returnto', $action);
1492 common_hidden('inreplyto', 'false');
1493 common_element('input', array('id' => 'status_submit',
1494 'name' => 'status_submit',
1496 'value' => _('Send')));
1497 common_element_end('p');
1498 common_element_end('form');
1501 # Should make up a reasonable root URL
1503 function common_root_url() {
1504 return common_path('');
1507 # returns $bytes bytes of random data as a hexadecimal string
1508 # "good" here is a goal and not a guarantee
1510 function common_good_rand($bytes) {
1511 # XXX: use random.org...?
1512 if (file_exists('/dev/urandom')) {
1513 return common_urandom($bytes);
1514 } else { # FIXME: this is probably not good enough
1515 return common_mtrand($bytes);
1519 function common_urandom($bytes) {
1520 $h = fopen('/dev/urandom', 'rb');
1522 $src = fread($h, $bytes);
1525 for ($i = 0; $i < $bytes; $i++) {
1526 $enc .= sprintf("%02x", (ord($src[$i])));
1531 function common_mtrand($bytes) {
1533 for ($i = 0; $i < $bytes; $i++) {
1534 $enc .= sprintf("%02x", mt_rand(0, 255));
1539 function common_set_returnto($url) {
1540 common_ensure_session();
1541 $_SESSION['returnto'] = $url;
1544 function common_get_returnto() {
1545 common_ensure_session();
1546 return $_SESSION['returnto'];
1549 function common_timestamp() {
1550 return date('YmdHis');
1553 function common_ensure_syslog() {
1554 static $initialized = false;
1555 if (!$initialized) {
1557 openlog($config['syslog']['appname'], 0, LOG_USER);
1558 $initialized = true;
1562 function common_log($priority, $msg, $filename=NULL) {
1563 $logfile = common_config('site', 'logfile');
1565 $log = fopen($logfile, "a");
1567 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1568 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1569 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1570 fwrite($log, $output);
1574 common_ensure_syslog();
1575 syslog($priority, $msg);
1579 function common_debug($msg, $filename=NULL) {
1581 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1583 common_log(LOG_DEBUG, $msg);
1587 function common_log_db_error(&$object, $verb, $filename=NULL) {
1588 $objstr = common_log_objstring($object);
1589 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1590 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1593 function common_log_objstring(&$object) {
1594 if (is_null($object)) {
1597 $arr = $object->toArray();
1599 foreach ($arr as $k => $v) {
1600 $fields[] = "$k='$v'";
1602 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1606 function common_valid_http_url($url) {
1607 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1610 function common_valid_tag($tag) {
1611 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1612 return (Validate::email($matches[1]) ||
1613 preg_match('/^([\w-\.]+)$/', $matches[1]));
1618 # Does a little before-after block for next/prev page
1620 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1622 if ($have_before || $have_after) {
1623 common_element_start('div', array('id' => 'pagination'));
1624 common_element_start('ul', array('id' => 'nav_pagination'));
1628 $pargs = array('page' => $page-1);
1629 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1631 common_element_start('li', 'before');
1632 common_element('a', array('href' => common_local_url($action, $newargs)),
1634 common_element_end('li');
1638 $pargs = array('page' => $page+1);
1639 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1640 common_element_start('li', 'after');
1641 common_element('a', array('href' => common_local_url($action, $newargs)),
1643 common_element_end('li');
1646 if ($have_before || $have_after) {
1647 common_element_end('ul');
1648 common_element_end('div');
1652 /* Following functions are copied from MediaWiki GlobalFunctions.php
1653 * and written by Evan Prodromou. */
1655 function common_accept_to_prefs($accept, $def = '*/*') {
1656 # No arg means accept anything (per HTTP spec)
1658 return array($def => 1);
1663 $parts = explode(',', $accept);
1665 foreach($parts as $part) {
1666 # FIXME: doesn't deal with params like 'text/html; level=1'
1667 @list($value, $qpart) = explode(';', $part);
1669 if(!isset($qpart)) {
1671 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1672 $prefs[$value] = $match[1];
1679 function common_mime_type_match($type, $avail) {
1680 if(array_key_exists($type, $avail)) {
1683 $parts = explode('/', $type);
1684 if(array_key_exists($parts[0] . '/*', $avail)) {
1685 return $parts[0] . '/*';
1686 } elseif(array_key_exists('*/*', $avail)) {
1694 function common_negotiate_type($cprefs, $sprefs) {
1697 foreach(array_keys($sprefs) as $type) {
1698 $parts = explode('/', $type);
1699 if($parts[1] != '*') {
1700 $ckey = common_mime_type_match($type, $cprefs);
1702 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1707 foreach(array_keys($cprefs) as $type) {
1708 $parts = explode('/', $type);
1709 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1710 $skey = common_mime_type_match($type, $sprefs);
1712 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1718 $besttype = "text/html";
1720 foreach(array_keys($combine) as $type) {
1721 if($combine[$type] > $bestq) {
1723 $bestq = $combine[$type];
1730 function common_config($main, $sub) {
1732 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1735 function common_copy_args($from) {
1737 $strip = get_magic_quotes_gpc();
1738 foreach ($from as $k => $v) {
1739 $to[$k] = ($strip) ? stripslashes($v) : $v;
1744 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1745 // This is used before handing a request off to OAuthRequest::from_request.
1746 function common_remove_magic_from_request() {
1747 if(get_magic_quotes_gpc()) {
1748 $_POST=array_map('stripslashes',$_POST);
1749 $_GET=array_map('stripslashes',$_GET);
1753 function common_user_uri(&$user) {
1754 return common_local_url('userbyid', array('id' => $user->id));
1757 function common_notice_uri(&$notice) {
1758 return common_local_url('shownotice',
1759 array('notice' => $notice->id));
1762 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1764 function common_confirmation_code($bits) {
1765 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1766 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1767 $chars = ceil($bits/5);
1769 for ($i = 0; $i < $chars; $i++) {
1770 # XXX: convert to string and back
1771 $num = hexdec(common_good_rand(1));
1772 # XXX: randomness is too precious to throw away almost
1773 # 40% of the bits we get!
1774 $code .= $codechars[$num%32];
1779 # convert markup to HTML
1781 function common_markup_to_html($c) {
1782 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1783 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1784 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1785 return Markdown($c);
1788 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1789 $avatar = $profile->getAvatar($size);
1791 return common_avatar_display_url($avatar);
1793 return common_default_avatar($size);
1797 function common_profile_uri($profile) {
1801 $user = User::staticGet($profile->id);
1806 $remote = Remote_profile::staticGet($profile->id);
1808 return $remote->uri;
1810 # XXX: this is a very bad profile!
1814 function common_canonical_sms($sms) {
1816 preg_replace('/\D/', '', $sms);
1820 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1823 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1827 case E_USER_WARNING:
1828 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1832 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1836 # FIXME: show error page if we're on the Web
1837 /* Don't execute PHP internal error handler */
1841 function common_session_token() {
1842 common_ensure_session();
1843 if (!array_key_exists('token', $_SESSION)) {
1844 $_SESSION['token'] = common_good_rand(64);
1846 return $_SESSION['token'];
1849 function common_disfavor_form($notice) {
1850 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1852 'class' => 'disfavor',
1853 'action' => common_local_url('disfavor')));
1855 common_element('input', array('type' => 'hidden',
1856 'name' => 'token-'. $notice->id,
1857 'id' => 'token-'. $notice->id,
1859 'value' => common_session_token()));
1861 common_element('input', array('type' => 'hidden',
1863 'id' => 'notice-n'. $notice->id,
1864 'class' => 'notice',
1865 'value' => $notice->id));
1867 common_element('input', array('type' => 'submit',
1868 'id' => 'disfavor-submit-' . $notice->id,
1869 'name' => 'disfavor-submit-' . $notice->id,
1870 'class' => 'disfavor',
1871 'value' => 'Disfavor favorite',
1872 'title' => 'Remove this message from favorites'));
1873 common_element_end('form');
1876 function common_favor_form($notice) {
1877 common_element_start('form', array('id' => 'favor-' . $notice->id,
1880 'action' => common_local_url('favor')));
1882 common_element('input', array('type' => 'hidden',
1883 'name' => 'token-'. $notice->id,
1884 'id' => 'token-'. $notice->id,
1886 'value' => common_session_token()));
1888 common_element('input', array('type' => 'hidden',
1890 'id' => 'notice-n'. $notice->id,
1891 'class' => 'notice',
1892 'value' => $notice->id));
1894 common_element('input', array('type' => 'submit',
1895 'id' => 'favor-submit-' . $notice->id,
1896 'name' => 'favor-submit-' . $notice->id,
1898 'value' => 'Add to favorites',
1899 'title' => 'Add this message to favorites'));
1900 common_element_end('form');
1903 function common_nudge_form($profile) {
1904 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
1905 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
1906 common_hidden('token', common_session_token());
1907 common_element('input', array('type' => 'submit',
1908 'class' => 'submit',
1909 'value' => _('Send a nudge')));
1910 common_element_end('form');
1912 function common_nudge_response() {
1913 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
1916 function common_subscribe_form($profile) {
1917 common_element_start('form', array('id' => 'subscribe-' . $profile->nickname,
1919 'class' => 'subscribe',
1920 'action' => common_local_url('subscribe')));
1921 common_hidden('token', common_session_token());
1922 common_element('input', array('id' => 'subscribeto-' . $profile->nickname,
1923 'name' => 'subscribeto',
1925 'value' => $profile->nickname));
1926 common_element('input', array('type' => 'submit',
1927 'class' => 'submit',
1928 'value' => _('Subscribe')));
1929 common_element_end('form');
1932 function common_unsubscribe_form($profile) {
1933 common_element_start('form', array('id' => 'unsubscribe-' . $profile->nickname,
1935 'class' => 'unsubscribe',
1936 'action' => common_local_url('unsubscribe')));
1937 common_hidden('token', common_session_token());
1938 common_element('input', array('id' => 'unsubscribeto-' . $profile->nickname,
1939 'name' => 'unsubscribeto',
1941 'value' => $profile->nickname));
1942 common_element('input', array('type' => 'submit',
1943 'class' => 'submit',
1944 'value' => _('Unsubscribe')));
1945 common_element_end('form');
1948 // XXX: Refactor this code
1949 function common_profile_new_message_nudge ($cur, $profile) {
1950 $user = User::staticGet('id', $profile->id);
1952 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
1953 common_element_start('li', array('id' => 'profile_send_a_new_message'));
1954 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
1955 _('Send a message'));
1956 common_element_end('li');
1958 if ($user->email && $user->emailnotifynudge) {
1959 common_element_start('li', array('id' => 'profile_nudge'));
1960 common_nudge_form($user);
1961 common_element_end('li');
1966 function common_cache_key($extra) {
1967 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1970 function common_keyize($str) {
1971 $str = strtolower($str);
1972 $str = preg_replace('/\s/', '_', $str);
1976 function common_message_form($content, $user, $to) {
1978 common_element_start('form', array('id' => 'message_form',
1980 'action' => common_local_url('newmessage')));
1982 $mutual_users = $user->mutuallySubscribedUsers();
1986 while ($mutual_users->fetch()) {
1987 if ($mutual_users->id != $user->id) {
1988 $mutual[$mutual_users->id] = $mutual_users->nickname;
1992 $mutual_users->free();
1993 unset($mutual_users);
1995 common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
1997 common_element_start('p');
1999 common_element('textarea', array('id' => 'message_content',
2002 'name' => 'content'),
2003 ($content) ? $content : '');
2005 common_element('input', array('id' => 'message_send',
2006 'name' => 'message_send',
2008 'value' => _('Send')));
2010 common_hidden('token', common_session_token());
2012 common_element_end('p');
2013 common_element_end('form');
2016 function common_memcache() {
2017 static $cache = NULL;
2018 if (!common_config('memcached', 'enabled')) {
2022 $cache = new Memcache();
2023 $servers = common_config('memcached', 'server');
2024 if (is_array($servers)) {
2025 foreach($servers as $server) {
2026 $cache->addServer($server);
2029 $cache->addServer($servers);