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, $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_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, $indent=true) {
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', $indent);
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_menu_item(common_local_url('doc', array('title' => 'help')),
336 common_element_end('ul');
339 function common_foot_menu() {
340 common_element_start('ul', array('id' => 'nav_sub'));
341 common_menu_item(common_local_url('doc', array('title' => 'help')),
343 common_menu_item(common_local_url('doc', array('title' => 'about')),
345 common_menu_item(common_local_url('doc', array('title' => 'faq')),
347 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
349 common_menu_item(common_local_url('doc', array('title' => 'source')),
351 common_menu_item(common_local_url('doc', array('title' => 'contact')),
353 common_element_end('ul');
356 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
359 $lattrs['class'] = 'current';
361 common_element_start('li', $lattrs);
362 $attrs['href'] = $url;
364 $attrs['title'] = $title;
366 common_element('a', $attrs, $text);
367 common_element_end('li');
370 function common_input($id, $label, $value=NULL,$instructions=NULL) {
371 common_element_start('p');
372 common_element('label', array('for' => $id), $label);
373 $attrs = array('name' => $id,
375 'class' => 'input_text',
378 $attrs['value'] = htmlspecialchars($value);
380 common_element('input', $attrs);
382 common_element('span', 'input_instructions', $instructions);
384 common_element_end('p');
387 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false)
389 common_element_start('p');
390 $attrs = array('name' => $id,
391 'type' => 'checkbox',
392 'class' => 'checkbox',
395 $attrs['value'] = htmlspecialchars($value);
398 $attrs['checked'] = 'checked';
401 $attrs['disabled'] = 'true';
403 common_element('input', $attrs);
405 common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label);
408 common_element('span', 'input_instructions', $instructions);
410 common_element_end('p');
413 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
414 common_element_start('p');
415 common_element('label', array('for' => $id), $label);
416 common_element_start('select', array('id' => $id, 'name' => $id));
418 common_element('option', array('value' => ''));
420 foreach ($content as $value => $option) {
421 if ($value == $selected) {
422 common_element('option', array('value' => $value, 'selected' => $value), $option);
424 common_element('option', array('value' => $value), $option);
427 common_element_end('select');
429 common_element('span', 'input_instructions', $instructions);
431 common_element_end('p');
433 function common_hidden($id, $value) {
434 common_element('input', array('name' => $id,
440 function common_password($id, $label, $instructions=NULL) {
441 common_element_start('p');
442 common_element('label', array('for' => $id), $label);
443 $attrs = array('name' => $id,
444 'type' => 'password',
445 'class' => 'password',
447 common_element('input', $attrs);
449 common_element('span', 'input_instructions', $instructions);
451 common_element_end('p');
454 function common_submit($id, $label, $cls='submit') {
456 common_element_start('p');
457 common_element('input', array('type' => 'submit',
462 common_element_end('p');
465 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
466 common_element_start('p');
467 common_element('label', array('for' => $id), $label);
468 common_element('textarea', array('rows' => 3,
472 ($content) ? $content : '');
474 common_element('span', 'input_instructions', $instructions);
476 common_element_end('p');
479 function common_timezone() {
480 if (common_logged_in()) {
481 $user = common_current_user();
482 if ($user->timezone) {
483 return $user->timezone;
488 return $config['site']['timezone'];
491 function common_language() {
493 // If there is a user logged in and they've set a language preference
494 // then return that one...
495 if (common_logged_in()) {
496 $user = common_current_user();
497 $user_language = $user->language;
499 return $user_language;
502 // Otherwise, find the best match for the languages requested by the
504 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
505 if (!empty($httplang)) {
506 $language = client_prefered_language($httplang);
511 // Finally, if none of the above worked, use the site's default...
512 return common_config('site', 'language');
514 # salted, hashed passwords are stored in the DB
516 function common_munge_password($password, $id) {
517 return md5($password . $id);
520 # check if a username exists and has matching password
521 function common_check_user($nickname, $password) {
522 # NEVER allow blank passwords, even if they match the DB
523 if (mb_strlen($password) == 0) {
526 $user = User::staticGet('nickname', $nickname);
527 if (is_null($user)) {
530 if (0 == strcmp(common_munge_password($password, $user->id),
539 # is the current user logged in?
540 function common_logged_in() {
541 return (!is_null(common_current_user()));
544 function common_have_session() {
545 return (0 != strcmp(session_id(), ''));
548 function common_ensure_session() {
549 if (!common_have_session()) {
554 # Three kinds of arguments:
559 # Initialize to false; set to NULL if none found
563 function common_set_user($user) {
567 if (is_null($user) && common_have_session()) {
569 unset($_SESSION['userid']);
571 } else if (is_string($user)) {
573 $user = User::staticGet('nickname', $nickname);
574 } else if (!($user instanceof User)) {
579 common_ensure_session();
580 $_SESSION['userid'] = $user->id;
587 function common_set_cookie($key, $value, $expiration=0) {
588 $path = common_config('site', 'path');
589 $server = common_config('site', 'server');
591 if ($path && ($path != '/')) {
592 $cookiepath = '/' . $path . '/';
596 return setcookie($key,
603 define('REMEMBERME', 'rememberme');
604 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); # 30 days
606 function common_rememberme($user=NULL) {
608 $user = common_current_user();
610 common_debug('No current user to remember', __FILE__);
615 $rm = new Remember_me();
617 $rm->code = common_good_rand(16);
618 $rm->user_id = $user->id;
620 # Wrap the insert in some good ol' fashioned transaction code
624 $result = $rm->insert();
627 common_log_db_error($rm, 'INSERT', __FILE__);
628 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
632 $rm->query('COMMIT');
634 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
636 $cookieval = $rm->user_id . ':' . $rm->code;
638 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
640 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
645 function common_remembered_user() {
649 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : NULL;
655 list($id, $code) = explode(':', $packed);
657 if (!$id || !$code) {
658 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
663 $rm = Remember_me::staticGet($code);
666 common_log(LOG_WARNING, 'No such remember code: ' . $code);
671 if ($rm->user_id != $id) {
672 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
677 $user = User::staticGet($rm->user_id);
680 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
686 $result = $rm->delete();
689 common_log_db_error($rm, 'DELETE', __FILE__);
690 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
695 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
697 common_set_user($user);
698 common_real_login(false);
700 # We issue a new cookie, so they can log in
701 # automatically again after this session
703 common_rememberme($user);
708 # must be called with a valid user!
710 function common_forgetme() {
711 common_set_cookie(REMEMBERME, '', 0);
714 # who is the current user?
715 function common_current_user() {
718 if ($_cur === false) {
720 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
721 common_ensure_session();
722 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
724 $_cur = User::staticGet($id);
729 # that didn't work; try to remember; will init $_cur to NULL on failure
730 $_cur = common_remembered_user();
733 common_debug("Got User " . $_cur->nickname);
734 common_debug("Faking session on remembered user");
735 # XXX: Is this necessary?
736 $_SESSION['userid'] = $_cur->id;
743 # Logins that are 'remembered' aren't 'real' -- they're subject to
744 # cookie-stealing. So, we don't let them do certain things. New reg,
745 # OpenID, and password logins _are_ real.
747 function common_real_login($real=true) {
748 common_ensure_session();
749 $_SESSION['real_login'] = $real;
752 function common_is_real_login() {
753 return common_logged_in() && $_SESSION['real_login'];
756 # get canonical version of nickname for comparison
757 function common_canonical_nickname($nickname) {
758 # XXX: UTF-8 canonicalization (like combining chars)
759 return strtolower($nickname);
762 # get canonical version of email for comparison
763 function common_canonical_email($email) {
764 # XXX: canonicalize UTF-8
765 # XXX: lcase the domain part
769 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$_+!*();/?:~-]))');
771 function common_render_content($text, $notice) {
772 $r = common_render_text($text);
773 $id = $notice->profile_id;
774 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
775 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
776 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
780 function common_render_text($text) {
781 $r = htmlspecialchars($text);
783 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
784 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
785 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
790 function common_render_uri_thingy($matches) {
794 # Some heuristics for extracting URIs from surrounding punctuation
795 # Strip from trailing text...
796 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
798 $trailer = $matches[2];
802 ']' => '[', # technically disallowed in URIs, but used in Java docs
803 ')' => '(', # far too frequent in Wikipedia and MSDN
805 $final = substr($uri, -1, 1);
806 if (isset($pairs[$final])) {
807 $openers = substr_count($uri, $pairs[$final]);
808 $closers = substr_count($uri, $final);
809 if ($closers > $openers) {
810 // Assume the paren was opened outside the URI
811 $uri = substr($uri, 0, -1);
812 $trailer = $final . $trailer;
815 if ($longurl = common_longurl($uri)) {
816 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
817 $title = " title='$longurl'";
821 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
824 function common_longurl($short_url) {
825 $long_url = common_shorten_link($short_url, true);
826 if ($long_url === $short_url) return false;
830 function common_longurl2($uri) {
831 $uri_e = urlencode($uri);
832 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
833 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
834 return stripslashes($longurl['long_url']);
837 function common_shorten_links($text) {
838 if (mb_strlen($text) <= 140) return $text;
839 static $cache = array();
840 if (isset($cache[$text])) return $cache[$text];
841 // \s = not a horizontal whitespace character (since PHP 5.2.4)
842 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
845 function common_shorten_link($url, $reverse = false) {
846 static $url_cache = array();
847 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
849 $user = common_current_user();
851 $curlh = curl_init();
852 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
853 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
854 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
856 switch($user->urlshorteningservice) {
858 $short_url_service = new LilUrl;
859 $short_url = $short_url_service->shorten($url);
863 $short_url_service = new TightUrl;
864 $short_url = $short_url_service->shorten($url);
868 $short_url_service = new PtitUrl;
869 $short_url = $short_url_service->shorten($url);
873 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
874 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
878 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
879 $short_url = curl_exec($curlh);
882 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
883 $short_url = curl_exec($curlh);
886 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
887 $short_url = curl_exec($curlh);
890 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
891 $short_url = curl_exec($curlh);
900 $url_cache[(string)$short_url] = $url;
901 return (string)$short_url;
906 function common_xml_safe_str($str) {
907 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
909 // Replace control, formatting, and surrogate characters with '*', ala Twitter
910 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
913 function common_tag_link($tag) {
914 $canonical = common_canonical_tag($tag);
915 $url = common_local_url('tag', array('tag' => $canonical));
916 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
919 function common_canonical_tag($tag) {
920 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
923 function common_valid_profile_tag($str) {
924 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
927 function common_at_link($sender_id, $nickname) {
928 $sender = Profile::staticGet($sender_id);
929 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
931 return '<span class="vcard"><a class="fn nickname url" rel="reply" href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a></span>';
933 return '<span class="vcard"> <span class="fn nickname">'.$nickname.'</span> </span>';
937 function common_at_hash_link($sender_id, $tag) {
938 $user = User::staticGet($sender_id);
942 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
944 $url = common_local_url('subscriptions',
945 array('nickname' => $user->nickname,
947 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
953 function common_relative_profile($sender, $nickname, $dt=NULL) {
954 # Try to find profiles this profile is subscribed to that have this nickname
955 $recipient = new Profile();
956 # XXX: use a join instead of a subquery
957 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
958 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
959 if ($recipient->find(TRUE)) {
960 # XXX: should probably differentiate between profiles with
961 # the same name by date of most recent update
964 # Try to find profiles that listen to this profile and that have this nickname
965 $recipient = new Profile();
966 # XXX: use a join instead of a subquery
967 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
968 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
969 if ($recipient->find(TRUE)) {
970 # XXX: should probably differentiate between profiles with
971 # the same name by date of most recent update
974 # If this is a local user, try to find a local user with that nickname.
975 $sender = User::staticGet($sender->id);
977 $recipient_user = User::staticGet('nickname', $nickname);
978 if ($recipient_user) {
979 return $recipient_user->getProfile();
982 # Otherwise, no links. @messages from local users to remote users,
983 # or from remote users to other remote users, are just
984 # outside our ability to make intelligent guesses about
988 // where should the avatar go for this user?
990 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
994 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
996 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
1000 function common_avatar_path($filename) {
1002 return INSTALLDIR . '/avatar/' . $filename;
1005 function common_avatar_url($filename) {
1006 return common_path('avatar/'.$filename);
1009 function common_avatar_display_url($avatar) {
1010 $server = common_config('avatar', 'server');
1012 return 'http://'.$server.'/'.$avatar->filename;
1014 return $avatar->url;
1018 function common_default_avatar($size) {
1019 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
1020 AVATAR_STREAM_SIZE => 'stream',
1021 AVATAR_MINI_SIZE => 'mini');
1022 return theme_path('default-avatar-'.$sizenames[$size].'.png');
1025 function common_local_url($action, $args=NULL, $fragment=NULL) {
1027 if (common_config('site','fancy')) {
1028 $url = common_fancy_url($action, $args);
1030 $url = common_simple_url($action, $args);
1032 if (!is_null($fragment)) {
1033 $url .= '#'.$fragment;
1038 function common_fancy_url($action, $args=NULL) {
1039 switch (strtolower($action)) {
1041 if ($args && isset($args['page'])) {
1042 return common_path('?page=' . $args['page']);
1044 return common_path('');
1047 if ($args && isset($args['page'])) {
1048 return common_path('featured?page=' . $args['page']);
1050 return common_path('featured');
1053 if ($args && isset($args['page'])) {
1054 return common_path('favorited?page=' . $args['page']);
1056 return common_path('favorited');
1059 return common_path('rss');
1061 return common_path('xrds');
1063 return common_path('featuredrss');
1064 case 'favoritedrss':
1065 return common_path('favoritedrss');
1067 if ($args && $args['type']) {
1068 return common_path('opensearch/'.$args['type']);
1070 return common_path('opensearch/people');
1073 return common_path('doc/'.$args['title']);
1079 return common_path('main/'.$action);
1081 return common_path('main/tagother?id='.$args['id']);
1083 if ($args && $args['code']) {
1084 return common_path('main/register/'.$args['code']);
1086 return common_path('main/register');
1088 case 'remotesubscribe':
1089 if ($args && $args['nickname']) {
1090 return common_path('main/remote?nickname=' . $args['nickname']);
1092 return common_path('main/remote');
1095 return common_path($args['nickname'].'/nudge');
1097 return common_path('main/openid');
1098 case 'profilesettings':
1099 return common_path('settings/profile');
1100 case 'emailsettings':
1101 return common_path('settings/email');
1102 case 'openidsettings':
1103 return common_path('settings/openid');
1105 return common_path('settings/sms');
1106 case 'twittersettings':
1107 return common_path('settings/twitter');
1108 case 'othersettings':
1109 return common_path('settings/other');
1110 case 'deleteprofile':
1111 return common_path('settings/delete');
1113 if ($args && $args['replyto']) {
1114 return common_path('notice/new?replyto='.$args['replyto']);
1116 return common_path('notice/new');
1119 return common_path('notice/'.$args['notice']);
1120 case 'deletenotice':
1121 if ($args && $args['notice']) {
1122 return common_path('notice/delete/'.$args['notice']);
1124 return common_path('notice/delete');
1126 case 'microsummary':
1129 return common_path($args['nickname'].'/'.$action);
1134 if ($args && isset($args['page'])) {
1135 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1137 return common_path($args['nickname'].'/'.$action);
1139 case 'subscriptions':
1141 $nickname = $args['nickname'];
1142 unset($args['nickname']);
1143 if (isset($args['tag'])) {
1144 $tag = $args['tag'];
1145 unset($args['tag']);
1147 $params = http_build_query($args);
1149 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1151 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1154 return common_path($args['nickname'].'/all/rss');
1156 return common_path($args['nickname'].'/replies/rss');
1158 if (isset($args['limit']))
1159 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1160 return common_path($args['nickname'].'/rss');
1162 if ($args && isset($args['page'])) {
1163 return common_path($args['nickname'].'?page=' . $args['page']);
1165 return common_path($args['nickname']);
1168 case 'usertimeline':
1169 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1170 case 'confirmaddress':
1171 return common_path('main/confirmaddress/'.$args['code']);
1173 return common_path('user/'.$args['id']);
1174 case 'recoverpassword':
1175 $path = 'main/recoverpassword';
1176 if ($args['code']) {
1177 $path .= '/' . $args['code'];
1179 return common_path($path);
1181 return common_path('settings/im');
1182 case 'peoplesearch':
1183 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1184 case 'noticesearch':
1185 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1186 case 'noticesearchrss':
1187 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1188 case 'avatarbynickname':
1189 return common_path($args['nickname'].'/avatar/'.$args['size']);
1191 if (isset($args['tag']) && $args['tag']) {
1192 $path = 'tag/' . $args['tag'];
1193 unset($args['tag']);
1197 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1199 $path = 'peopletag/' . $args['tag'];
1200 unset($args['tag']);
1201 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1203 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1205 return common_path('main/favor');
1207 return common_path('main/disfavor');
1208 case 'showfavorites':
1209 if ($args && isset($args['page'])) {
1210 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1212 return common_path($args['nickname'].'/favorites');
1214 case 'favoritesrss':
1215 return common_path($args['nickname'].'/favorites/rss');
1217 return common_path('message/' . $args['message']);
1219 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1221 # XXX: do fancy URLs for all the API methods
1222 switch (strtolower($args['apiaction'])) {
1224 switch (strtolower($args['method'])) {
1225 case 'user_timeline.rss':
1226 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1227 case 'user_timeline.atom':
1228 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1229 case 'user_timeline.json':
1230 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1231 case 'user_timeline.xml':
1232 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1233 default: return common_simple_url($action, $args);
1235 default: return common_simple_url($action, $args);
1238 if ($args && isset($args['seconds'])) {
1239 return common_path('main/sup?seconds='.$args['seconds']);
1241 return common_path('main/sup');
1244 return common_simple_url($action, $args);
1248 function common_simple_url($action, $args=NULL) {
1250 /* XXX: pretty URLs */
1253 foreach ($args as $key => $value) {
1254 $extra .= "&${key}=${value}";
1257 return common_path("index.php?action=${action}${extra}");
1260 function common_path($relative) {
1262 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1263 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1266 function common_date_string($dt) {
1267 // XXX: do some sexy date formatting
1268 // return date(DATE_RFC822, $dt);
1269 $t = strtotime($dt);
1273 if ($now < $t) { # that shouldn't happen!
1274 return common_exact_date($dt);
1275 } else if ($diff < 60) {
1276 return _('a few seconds ago');
1277 } else if ($diff < 92) {
1278 return _('about a minute ago');
1279 } else if ($diff < 3300) {
1280 return sprintf(_('about %d minutes ago'), round($diff/60));
1281 } else if ($diff < 5400) {
1282 return _('about an hour ago');
1283 } else if ($diff < 22 * 3600) {
1284 return sprintf(_('about %d hours ago'), round($diff/3600));
1285 } else if ($diff < 37 * 3600) {
1286 return _('about a day ago');
1287 } else if ($diff < 24 * 24 * 3600) {
1288 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1289 } else if ($diff < 46 * 24 * 3600) {
1290 return _('about a month ago');
1291 } else if ($diff < 330 * 24 * 3600) {
1292 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1293 } else if ($diff < 480 * 24 * 3600) {
1294 return _('about a year ago');
1296 return common_exact_date($dt);
1300 function common_exact_date($dt) {
1305 $_utc = new DateTimeZone('UTC');
1306 $_siteTz = new DateTimeZone(common_timezone());
1309 $dateStr = date('d F Y H:i:s', strtotime($dt));
1310 $d = new DateTime($dateStr, $_utc);
1311 $d->setTimezone($_siteTz);
1312 return $d->format(DATE_RFC850);
1315 function common_date_w3dtf($dt) {
1316 $dateStr = date('d F Y H:i:s', strtotime($dt));
1317 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1318 $d->setTimezone(new DateTimeZone(common_timezone()));
1319 return $d->format(DATE_W3C);
1322 function common_date_rfc2822($dt) {
1323 $dateStr = date('d F Y H:i:s', strtotime($dt));
1324 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1325 $d->setTimezone(new DateTimeZone(common_timezone()));
1326 return $d->format('r');
1329 function common_date_iso8601($dt) {
1330 $dateStr = date('d F Y H:i:s', strtotime($dt));
1331 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1332 $d->setTimezone(new DateTimeZone(common_timezone()));
1333 return $d->format('c');
1336 function common_sql_now() {
1337 return strftime('%Y-%m-%d %H:%M:%S', time());
1340 function common_redirect($url, $code=307) {
1341 static $status = array(301 => "Moved Permanently",
1344 307 => "Temporary Redirect");
1345 header("Status: ${code} $status[$code]");
1346 header("Location: $url");
1348 common_start_xml('a',
1349 '-//W3C//DTD XHTML 1.0 Strict//EN',
1350 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1351 common_element('a', array('href' => $url), $url);
1356 function common_save_replies($notice) {
1357 # Alternative reply format
1359 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1362 # extract all @messages
1363 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1367 if ($cnt || $tname) {
1368 # XXX: is there another way to make an array copy?
1369 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1372 $sender = Profile::staticGet($notice->profile_id);
1376 # store replied only for first @ (what user/notice what the reply directed,
1377 # we assume first @ is it)
1379 for ($i=0; $i<count($names); $i++) {
1380 $nickname = $names[$i];
1381 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1385 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1386 $reply_for = $recipient;
1387 $recipient_notice = $reply_for->getCurrentNotice();
1388 if ($recipient_notice) {
1389 $orig = clone($notice);
1390 $notice->reply_to = $recipient_notice->id;
1391 $notice->update($orig);
1394 $reply = new Reply();
1395 $reply->notice_id = $notice->id;
1396 $reply->profile_id = $recipient->id;
1397 $id = $reply->insert();
1399 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1400 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1401 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1404 $replied[$recipient->id] = 1;
1408 # Hash format replies, too
1409 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1411 foreach ($match[1] as $tag) {
1412 $tagged = Profile_tag::getTagged($sender->id, $tag);
1413 foreach ($tagged as $t) {
1414 if (!$replied[$t->id]) {
1415 $reply = new Reply();
1416 $reply->notice_id = $notice->id;
1417 $reply->profile_id = $t->id;
1418 $id = $reply->insert();
1420 common_log_db_error($reply, 'INSERT', __FILE__);
1429 function common_broadcast_notice($notice, $remote=false) {
1431 // Check to see if notice should go to Twitter
1432 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1433 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1435 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1437 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1438 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1440 $result = common_twitter_broadcast($notice, $flink);
1443 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1448 if (common_config('queue', 'enabled')) {
1450 return common_enqueue_notice($notice);
1452 return common_real_broadcast($notice, $remote);
1456 function common_twitter_broadcast($notice, $flink) {
1459 $fuser = $flink->getForeignUser();
1460 $twitter_user = $fuser->nickname;
1461 $twitter_password = $flink->credentials;
1462 $uri = 'http://www.twitter.com/statuses/update.json';
1464 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1465 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1468 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1469 CURLOPT_POST => true,
1470 CURLOPT_POSTFIELDS => array(
1471 'status' => $statustxt,
1472 'source' => $config['integration']['source']
1474 CURLOPT_RETURNTRANSFER => true,
1475 CURLOPT_FAILONERROR => true,
1476 CURLOPT_HEADER => false,
1477 CURLOPT_FOLLOWLOCATION => true,
1478 CURLOPT_USERAGENT => "Laconica",
1479 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1480 CURLOPT_TIMEOUT => 120
1483 $ch = curl_init($uri);
1484 curl_setopt_array($ch, $options);
1485 $data = curl_exec($ch);
1486 $errmsg = curl_error($ch);
1489 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1497 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1502 // Twitter should return a status
1503 $status = json_decode($data);
1506 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1514 # Stick the notice on the queue
1516 function common_enqueue_notice($notice) {
1517 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1518 $qi = new Queue_item();
1519 $qi->notice_id = $notice->id;
1520 $qi->transport = $transport;
1521 $qi->created = $notice->created;
1522 $result = $qi->insert();
1524 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1525 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1528 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1533 function common_dequeue_notice($notice) {
1534 $qi = Queue_item::staticGet($notice->id);
1536 $result = $qi->delete();
1538 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1539 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1542 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1549 function common_real_broadcast($notice, $remote=false) {
1552 # Make sure we have the OMB stuff
1553 require_once(INSTALLDIR.'/lib/omb.php');
1554 $success = omb_broadcast_remote_subscribers($notice);
1556 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1560 require_once(INSTALLDIR.'/lib/jabber.php');
1561 $success = jabber_broadcast_notice($notice);
1563 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1567 require_once(INSTALLDIR.'/lib/mail.php');
1568 $success = mail_broadcast_notice_sms($notice);
1570 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1574 $success = jabber_public_notice($notice);
1576 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1579 // XXX: broadcast notices to other IM
1583 function common_broadcast_profile($profile) {
1584 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1585 require_once(INSTALLDIR.'/lib/omb.php');
1586 omb_broadcast_profile($profile);
1587 // XXX: Other broadcasts...?
1591 function common_profile_url($nickname) {
1592 return common_local_url('showstream', array('nickname' => $nickname));
1595 # Don't call if nobody's logged in
1597 function common_notice_form($action=NULL, $content=NULL) {
1598 $user = common_current_user();
1599 assert(!is_null($user));
1600 common_element_start('form', array('id' => 'status_form',
1602 'action' => common_local_url('newnotice')));
1603 common_element_start('p');
1604 common_element('label', array('for' => 'status_textarea',
1605 'id' => 'status_label'),
1606 sprintf(_('What\'s up, %s?'), $user->nickname));
1607 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1608 common_element('textarea', array('id' => 'status_textarea',
1611 'name' => 'status_textarea'),
1612 ($content) ? $content : '');
1613 common_hidden('token', common_session_token());
1615 common_hidden('returnto', $action);
1618 common_hidden('inreplyto', 'false');
1619 common_element('input', array('id' => 'status_submit',
1620 'name' => 'status_submit',
1622 'value' => _('Send')));
1623 common_element_end('p');
1624 common_element_end('form');
1627 # Should make up a reasonable root URL
1629 function common_root_url() {
1630 return common_path('');
1633 # returns $bytes bytes of random data as a hexadecimal string
1634 # "good" here is a goal and not a guarantee
1636 function common_good_rand($bytes) {
1637 # XXX: use random.org...?
1638 if (file_exists('/dev/urandom')) {
1639 return common_urandom($bytes);
1640 } else { # FIXME: this is probably not good enough
1641 return common_mtrand($bytes);
1645 function common_urandom($bytes) {
1646 $h = fopen('/dev/urandom', 'rb');
1648 $src = fread($h, $bytes);
1651 for ($i = 0; $i < $bytes; $i++) {
1652 $enc .= sprintf("%02x", (ord($src[$i])));
1657 function common_mtrand($bytes) {
1659 for ($i = 0; $i < $bytes; $i++) {
1660 $enc .= sprintf("%02x", mt_rand(0, 255));
1665 function common_set_returnto($url) {
1666 common_ensure_session();
1667 $_SESSION['returnto'] = $url;
1670 function common_get_returnto() {
1671 common_ensure_session();
1672 return $_SESSION['returnto'];
1675 function common_timestamp() {
1676 return date('YmdHis');
1679 function common_ensure_syslog() {
1680 static $initialized = false;
1681 if (!$initialized) {
1683 openlog($config['syslog']['appname'], 0, LOG_USER);
1684 $initialized = true;
1688 function common_log($priority, $msg, $filename=NULL) {
1689 $logfile = common_config('site', 'logfile');
1691 $log = fopen($logfile, "a");
1693 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1694 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1695 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1696 fwrite($log, $output);
1700 common_ensure_syslog();
1701 syslog($priority, $msg);
1705 function common_debug($msg, $filename=NULL) {
1707 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1709 common_log(LOG_DEBUG, $msg);
1713 function common_log_db_error(&$object, $verb, $filename=NULL) {
1714 $objstr = common_log_objstring($object);
1715 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1716 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1719 function common_log_objstring(&$object) {
1720 if (is_null($object)) {
1723 $arr = $object->toArray();
1725 foreach ($arr as $k => $v) {
1726 $fields[] = "$k='$v'";
1728 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1732 function common_valid_http_url($url) {
1733 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1736 function common_valid_tag($tag) {
1737 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1738 return (Validate::email($matches[1]) ||
1739 preg_match('/^([\w-\.]+)$/', $matches[1]));
1744 # Does a little before-after block for next/prev page
1746 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1748 if ($have_before || $have_after) {
1749 common_element_start('div', array('id' => 'pagination'));
1750 common_element_start('ul', array('id' => 'nav_pagination'));
1754 $pargs = array('page' => $page-1);
1755 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1757 common_element_start('li', 'before');
1758 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1760 common_element_end('li');
1764 $pargs = array('page' => $page+1);
1765 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1766 common_element_start('li', 'after');
1767 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1769 common_element_end('li');
1772 if ($have_before || $have_after) {
1773 common_element_end('ul');
1774 common_element_end('div');
1778 /* Following functions are copied from MediaWiki GlobalFunctions.php
1779 * and written by Evan Prodromou. */
1781 function common_accept_to_prefs($accept, $def = '*/*') {
1782 # No arg means accept anything (per HTTP spec)
1784 return array($def => 1);
1789 $parts = explode(',', $accept);
1791 foreach($parts as $part) {
1792 # FIXME: doesn't deal with params like 'text/html; level=1'
1793 @list($value, $qpart) = explode(';', $part);
1795 if(!isset($qpart)) {
1797 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1798 $prefs[$value] = $match[1];
1805 function common_mime_type_match($type, $avail) {
1806 if(array_key_exists($type, $avail)) {
1809 $parts = explode('/', $type);
1810 if(array_key_exists($parts[0] . '/*', $avail)) {
1811 return $parts[0] . '/*';
1812 } elseif(array_key_exists('*/*', $avail)) {
1820 function common_negotiate_type($cprefs, $sprefs) {
1823 foreach(array_keys($sprefs) as $type) {
1824 $parts = explode('/', $type);
1825 if($parts[1] != '*') {
1826 $ckey = common_mime_type_match($type, $cprefs);
1828 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1833 foreach(array_keys($cprefs) as $type) {
1834 $parts = explode('/', $type);
1835 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1836 $skey = common_mime_type_match($type, $sprefs);
1838 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1844 $besttype = "text/html";
1846 foreach(array_keys($combine) as $type) {
1847 if($combine[$type] > $bestq) {
1849 $bestq = $combine[$type];
1856 function common_config($main, $sub) {
1858 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1861 function common_copy_args($from) {
1863 $strip = get_magic_quotes_gpc();
1864 foreach ($from as $k => $v) {
1865 $to[$k] = ($strip) ? stripslashes($v) : $v;
1870 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1871 // This is used before handing a request off to OAuthRequest::from_request.
1872 function common_remove_magic_from_request() {
1873 if(get_magic_quotes_gpc()) {
1874 $_POST=array_map('stripslashes',$_POST);
1875 $_GET=array_map('stripslashes',$_GET);
1879 function common_user_uri(&$user) {
1880 return common_local_url('userbyid', array('id' => $user->id));
1883 function common_notice_uri(&$notice) {
1884 return common_local_url('shownotice',
1885 array('notice' => $notice->id));
1888 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1890 function common_confirmation_code($bits) {
1891 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1892 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1893 $chars = ceil($bits/5);
1895 for ($i = 0; $i < $chars; $i++) {
1896 # XXX: convert to string and back
1897 $num = hexdec(common_good_rand(1));
1898 # XXX: randomness is too precious to throw away almost
1899 # 40% of the bits we get!
1900 $code .= $codechars[$num%32];
1905 # convert markup to HTML
1907 function common_markup_to_html($c) {
1908 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1909 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1910 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1911 return Markdown($c);
1914 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1915 $avatar = $profile->getAvatar($size);
1917 return common_avatar_display_url($avatar);
1919 return common_default_avatar($size);
1923 function common_profile_uri($profile) {
1927 $user = User::staticGet($profile->id);
1932 $remote = Remote_profile::staticGet($profile->id);
1934 return $remote->uri;
1936 # XXX: this is a very bad profile!
1940 function common_canonical_sms($sms) {
1942 preg_replace('/\D/', '', $sms);
1946 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1949 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1953 case E_USER_WARNING:
1954 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1958 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1962 # FIXME: show error page if we're on the Web
1963 /* Don't execute PHP internal error handler */
1967 function common_session_token() {
1968 common_ensure_session();
1969 if (!array_key_exists('token', $_SESSION)) {
1970 $_SESSION['token'] = common_good_rand(64);
1972 return $_SESSION['token'];
1975 function common_disfavor_form($notice) {
1976 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1978 'class' => 'disfavor',
1979 'action' => common_local_url('disfavor')));
1981 common_element('input', array('type' => 'hidden',
1982 'name' => 'token-'. $notice->id,
1983 'id' => 'token-'. $notice->id,
1985 'value' => common_session_token()));
1987 common_element('input', array('type' => 'hidden',
1989 'id' => 'notice-n'. $notice->id,
1990 'class' => 'notice',
1991 'value' => $notice->id));
1993 common_element('input', array('type' => 'submit',
1994 'id' => 'disfavor-submit-' . $notice->id,
1995 'name' => 'disfavor-submit-' . $notice->id,
1996 'class' => 'disfavor',
1997 'value' => 'Disfavor favorite',
1998 'title' => 'Remove this message from favorites'));
1999 common_element_end('form');
2002 function common_favor_form($notice) {
2003 common_element_start('form', array('id' => 'favor-' . $notice->id,
2006 'action' => common_local_url('favor')));
2008 common_element('input', array('type' => 'hidden',
2009 'name' => 'token-'. $notice->id,
2010 'id' => 'token-'. $notice->id,
2012 'value' => common_session_token()));
2014 common_element('input', array('type' => 'hidden',
2016 'id' => 'notice-n'. $notice->id,
2017 'class' => 'notice',
2018 'value' => $notice->id));
2020 common_element('input', array('type' => 'submit',
2021 'id' => 'favor-submit-' . $notice->id,
2022 'name' => 'favor-submit-' . $notice->id,
2024 'value' => 'Add to favorites',
2025 'title' => 'Add this message to favorites'));
2026 common_element_end('form');
2029 function common_nudge_form($profile) {
2030 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
2031 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
2032 common_hidden('token', common_session_token());
2033 common_element('input', array('type' => 'submit',
2034 'class' => 'submit',
2035 'value' => _('Send a nudge')));
2036 common_element_end('form');
2038 function common_nudge_response() {
2039 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
2042 function common_subscribe_form($profile) {
2043 common_element_start('form', array('id' => 'subscribe-' . $profile->nickname,
2045 'class' => 'subscribe',
2046 'action' => common_local_url('subscribe')));
2047 common_hidden('token', common_session_token());
2048 common_element('input', array('id' => 'subscribeto-' . $profile->nickname,
2049 'name' => 'subscribeto',
2051 'value' => $profile->nickname));
2052 common_element('input', array('type' => 'submit',
2053 'class' => 'submit',
2054 'value' => _('Subscribe')));
2055 common_element_end('form');
2058 function common_unsubscribe_form($profile) {
2059 common_element_start('form', array('id' => 'unsubscribe-' . $profile->nickname,
2061 'class' => 'unsubscribe',
2062 'action' => common_local_url('unsubscribe')));
2063 common_hidden('token', common_session_token());
2064 common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
2065 'name' => 'unsubscribeto',
2067 'value' => $profile->id));
2068 common_element('input', array('type' => 'submit',
2069 'class' => 'submit',
2070 'value' => _('Unsubscribe')));
2071 common_element_end('form');
2074 // XXX: Refactor this code
2075 function common_profile_new_message_nudge ($cur, $profile) {
2076 $user = User::staticGet('id', $profile->id);
2078 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
2079 common_element_start('li', array('id' => 'profile_send_a_new_message'));
2080 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2081 _('Send a message'));
2082 common_element_end('li');
2084 if ($user->email && $user->emailnotifynudge) {
2085 common_element_start('li', array('id' => 'profile_nudge'));
2086 common_nudge_form($user);
2087 common_element_end('li');
2092 function common_cache_key($extra) {
2093 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2096 function common_keyize($str) {
2097 $str = strtolower($str);
2098 $str = preg_replace('/\s/', '_', $str);
2102 function common_message_form($content, $user, $to) {
2104 common_element_start('form', array('id' => 'message_form',
2106 'action' => common_local_url('newmessage')));
2108 $mutual_users = $user->mutuallySubscribedUsers();
2112 while ($mutual_users->fetch()) {
2113 if ($mutual_users->id != $user->id) {
2114 $mutual[$mutual_users->id] = $mutual_users->nickname;
2118 $mutual_users->free();
2119 unset($mutual_users);
2121 common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
2123 common_element_start('p');
2125 common_element('textarea', array('id' => 'message_content',
2128 'name' => 'content'),
2129 ($content) ? $content : '');
2131 common_element('input', array('id' => 'message_send',
2132 'name' => 'message_send',
2134 'value' => _('Send')));
2136 common_hidden('token', common_session_token());
2138 common_element_end('p');
2139 common_element_end('form');
2142 function common_memcache() {
2143 static $cache = NULL;
2144 if (!common_config('memcached', 'enabled')) {
2148 $cache = new Memcache();
2149 $servers = common_config('memcached', 'server');
2150 if (is_array($servers)) {
2151 foreach($servers as $server) {
2152 $cache->addServer($server);
2155 $cache->addServer($servers);
2162 function common_compatible_license($from, $to) {
2163 # XXX: better compatibility check needed here!
2164 return ($from == $to);