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, user, files) */
22 // Show a server error
24 function common_server_error($msg, $code=500)
26 static $status = array(500 => 'Internal Server Error',
27 501 => 'Not Implemented',
29 503 => 'Service Unavailable',
30 504 => 'Gateway Timeout',
31 505 => 'HTTP Version Not Supported');
33 if (!array_key_exists($code, $status)) {
37 $status_string = $status[$code];
39 header('HTTP/1.1 '.$code.' '.$status_string);
40 header('Content-type: text/plain');
48 function common_user_error($msg, $code=400)
50 static $status = array(400 => 'Bad Request',
51 401 => 'Unauthorized',
52 402 => 'Payment Required',
55 405 => 'Method Not Allowed',
56 406 => 'Not Acceptable',
57 407 => 'Proxy Authentication Required',
58 408 => 'Request Timeout',
61 411 => 'Length Required',
62 412 => 'Precondition Failed',
63 413 => 'Request Entity Too Large',
64 414 => 'Request-URI Too Long',
65 415 => 'Unsupported Media Type',
66 416 => 'Requested Range Not Satisfiable',
67 417 => 'Expectation Failed');
69 if (!array_key_exists($code, $status)) {
73 $status_string = $status[$code];
75 header('HTTP/1.1 '.$code.' '.$status_string);
77 common_show_header('Error');
78 common_element('div', array('class' => 'error'), $msg);
82 function common_init_locale($language=null)
85 $language = common_language();
87 putenv('LANGUAGE='.$language);
88 putenv('LANG='.$language);
89 return setlocale(LC_ALL, $language . ".utf8",
96 function common_init_language()
98 mb_internal_encoding('UTF-8');
99 $language = common_language();
100 // So we don't have to make people install the gettext locales
101 $locale_set = common_init_locale($language);
102 bindtextdomain("laconica", common_config('site','locale_path'));
103 bind_textdomain_codeset("laconica", "UTF-8");
104 textdomain("laconica");
105 setlocale(LC_CTYPE, 'C');
107 common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
111 function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null)
115 global $action; /* XXX: kind of cheating here. */
119 common_element_start('head');
120 common_element('title', null,
121 $pagetitle . " - " . $config['site']['name']);
122 common_element('link', array('rel' => 'stylesheet',
123 'type' => 'text/css',
124 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
125 'media' => 'screen, projection, tv'));
126 foreach (array(6,7) as $ver) {
127 if (file_exists(theme_file('ie'.$ver.'.css'))) {
128 // Yes, IE people should be put in jail.
129 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
130 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
134 common_element('script', array('type' => 'text/javascript',
135 'src' => common_path('js/jquery.min.js')),
137 common_element('script', array('type' => 'text/javascript',
138 'src' => common_path('js/jquery.form.js')),
140 common_element('script', array('type' => 'text/javascript',
141 'src' => common_path('js/xbImportNode.js')),
143 common_element('script', array('type' => 'text/javascript',
144 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
146 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
147 'href' => common_local_url('opensearch', array('type' => 'people')),
148 'title' => common_config('site', 'name').' People Search'));
150 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
151 'href' => common_local_url('opensearch', array('type' => 'notice')),
152 'title' => common_config('site', 'name').' Notice Search'));
156 call_user_func($callable, $data);
158 call_user_func($callable);
161 common_element_end('head');
162 common_element_start('body', $action);
163 common_element_start('div', array('id' => 'wrap'));
164 common_element_start('div', array('id' => 'header'));
166 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
167 || file_exists(theme_file('logo.png')))
169 common_element_start('a', array('href' => common_local_url('public')));
170 common_element('img', array('src' => isset($config['site']['logo']) ?
171 ($config['site']['logo']) : theme_path('logo.png'),
172 'alt' => $config['site']['name'],
174 common_element_end('a');
176 common_element_start('p', array('id' => 'branding'));
177 common_element('a', array('href' => common_local_url('public')),
178 $config['site']['name']);
179 common_element_end('p');
182 common_element('h1', 'pagetitle', $pagetitle);
186 call_user_func($headercall, $data);
188 call_user_func($headercall);
191 common_element_end('div');
192 common_element_start('div', array('id' => 'content'));
195 function common_show_footer()
198 common_element_end('div'); // content div
200 common_element_start('div', array('id' => 'footer'));
201 common_element_start('div', 'laconica');
202 if (common_config('site', 'broughtby')) {
203 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
205 $instr = _('**%%site.name%%** is a microblogging service. ');
207 $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);
208 $output = common_markup_to_html($instr);
210 common_element_end('div');
211 common_element('img', array('id' => 'cc',
212 'src' => $config['license']['image'],
213 'alt' => $config['license']['title']));
214 common_element_start('p');
215 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
216 common_element('a', array('class' => 'license',
218 'href' => $config['license']['url']),
219 $config['license']['title']);
220 common_text(_('. Contributors should be attributed by full name or nickname.'));
221 common_element_end('p');
222 common_element_end('div');
223 common_element_end('div');
224 common_element_end('body');
225 common_element_end('html');
229 function common_nav_menu()
231 $user = common_current_user();
232 common_element_start('ul', array('id' => 'nav'));
234 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
237 common_menu_item(common_local_url('peoplesearch'), _('Search'));
239 common_menu_item(common_local_url('profilesettings'),
241 common_menu_item(common_local_url('invite'),
243 common_menu_item(common_local_url('logout'),
246 common_menu_item(common_local_url('login'), _('Login'));
247 if (!common_config('site', 'closed')) {
248 common_menu_item(common_local_url('register'), _('Register'));
250 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
252 common_menu_item(common_local_url('doc', array('title' => 'help')),
254 common_element_end('ul');
257 function common_foot_menu()
259 common_element_start('ul', array('id' => 'nav_sub'));
260 common_menu_item(common_local_url('doc', array('title' => 'help')),
262 common_menu_item(common_local_url('doc', array('title' => 'about')),
264 common_menu_item(common_local_url('doc', array('title' => 'faq')),
266 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
268 common_menu_item(common_local_url('doc', array('title' => 'source')),
270 common_menu_item(common_local_url('doc', array('title' => 'contact')),
272 common_element_end('ul');
275 function common_menu_item($url, $text, $title=null, $is_selected=false)
279 $lattrs['class'] = 'current';
281 common_element_start('li', $lattrs);
282 $attrs['href'] = $url;
284 $attrs['title'] = $title;
286 common_element('a', $attrs, $text);
287 common_element_end('li');
290 function common_timezone()
292 if (common_logged_in()) {
293 $user = common_current_user();
294 if ($user->timezone) {
295 return $user->timezone;
300 return $config['site']['timezone'];
303 function common_language()
306 // If there is a user logged in and they've set a language preference
307 // then return that one...
308 if (common_logged_in()) {
309 $user = common_current_user();
310 $user_language = $user->language;
312 return $user_language;
315 // Otherwise, find the best match for the languages requested by the
317 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
318 if (!empty($httplang)) {
319 $language = client_prefered_language($httplang);
324 // Finally, if none of the above worked, use the site's default...
325 return common_config('site', 'language');
327 // salted, hashed passwords are stored in the DB
329 function common_munge_password($password, $id)
331 return md5($password . $id);
334 // check if a username exists and has matching password
335 function common_check_user($nickname, $password)
337 // NEVER allow blank passwords, even if they match the DB
338 if (mb_strlen($password) == 0) {
341 $user = User::staticGet('nickname', $nickname);
342 if (is_null($user)) {
345 if (0 == strcmp(common_munge_password($password, $user->id),
354 // is the current user logged in?
355 function common_logged_in()
357 return (!is_null(common_current_user()));
360 function common_have_session()
362 return (0 != strcmp(session_id(), ''));
365 function common_ensure_session()
367 if (!common_have_session()) {
372 // Three kinds of arguments:
377 // Initialize to false; set to null if none found
381 function common_set_user($user)
386 if (is_null($user) && common_have_session()) {
388 unset($_SESSION['userid']);
390 } else if (is_string($user)) {
392 $user = User::staticGet('nickname', $nickname);
393 } else if (!($user instanceof User)) {
398 common_ensure_session();
399 $_SESSION['userid'] = $user->id;
406 function common_set_cookie($key, $value, $expiration=0)
408 $path = common_config('site', 'path');
409 $server = common_config('site', 'server');
411 if ($path && ($path != '/')) {
412 $cookiepath = '/' . $path . '/';
416 return setcookie($key,
423 define('REMEMBERME', 'rememberme');
424 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
426 function common_rememberme($user=null)
429 $user = common_current_user();
431 common_debug('No current user to remember', __FILE__);
436 $rm = new Remember_me();
438 $rm->code = common_good_rand(16);
439 $rm->user_id = $user->id;
441 // Wrap the insert in some good ol' fashioned transaction code
445 $result = $rm->insert();
448 common_log_db_error($rm, 'INSERT', __FILE__);
449 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
453 $rm->query('COMMIT');
455 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
457 $cookieval = $rm->user_id . ':' . $rm->code;
459 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
461 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
466 function common_remembered_user()
471 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
477 list($id, $code) = explode(':', $packed);
479 if (!$id || !$code) {
480 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
485 $rm = Remember_me::staticGet($code);
488 common_log(LOG_WARNING, 'No such remember code: ' . $code);
493 if ($rm->user_id != $id) {
494 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
499 $user = User::staticGet($rm->user_id);
502 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
508 $result = $rm->delete();
511 common_log_db_error($rm, 'DELETE', __FILE__);
512 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
517 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
519 common_set_user($user);
520 common_real_login(false);
522 // We issue a new cookie, so they can log in
523 // automatically again after this session
525 common_rememberme($user);
530 // must be called with a valid user!
532 function common_forgetme()
534 common_set_cookie(REMEMBERME, '', 0);
537 // who is the current user?
538 function common_current_user()
542 if ($_cur === false) {
544 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
545 common_ensure_session();
546 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
548 $_cur = User::staticGet($id);
553 // that didn't work; try to remember; will init $_cur to null on failure
554 $_cur = common_remembered_user();
557 common_debug("Got User " . $_cur->nickname);
558 common_debug("Faking session on remembered user");
559 // XXX: Is this necessary?
560 $_SESSION['userid'] = $_cur->id;
567 // Logins that are 'remembered' aren't 'real' -- they're subject to
568 // cookie-stealing. So, we don't let them do certain things. New reg,
569 // OpenID, and password logins _are_ real.
571 function common_real_login($real=true)
573 common_ensure_session();
574 $_SESSION['real_login'] = $real;
577 function common_is_real_login()
579 return common_logged_in() && $_SESSION['real_login'];
582 // get canonical version of nickname for comparison
583 function common_canonical_nickname($nickname)
585 // XXX: UTF-8 canonicalization (like combining chars)
586 return strtolower($nickname);
589 // get canonical version of email for comparison
590 function common_canonical_email($email)
592 // XXX: canonicalize UTF-8
593 // XXX: lcase the domain part
597 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$_+!*();/?:~-]))');
599 function common_render_content($text, $notice)
601 $r = common_render_text($text);
602 $id = $notice->profile_id;
603 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
604 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
605 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
609 function common_render_text($text)
611 $r = htmlspecialchars($text);
613 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
614 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
615 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
620 function common_render_uri_thingy($matches)
625 // Some heuristics for extracting URIs from surrounding punctuation
626 // Strip from trailing text...
627 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
629 $trailer = $matches[2];
633 ']' => '[', // technically disallowed in URIs, but used in Java docs
634 ')' => '(', // far too frequent in Wikipedia and MSDN
636 $final = substr($uri, -1, 1);
637 if (isset($pairs[$final])) {
638 $openers = substr_count($uri, $pairs[$final]);
639 $closers = substr_count($uri, $final);
640 if ($closers > $openers) {
641 // Assume the paren was opened outside the URI
642 $uri = substr($uri, 0, -1);
643 $trailer = $final . $trailer;
646 if ($longurl = common_longurl($uri)) {
647 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
648 $title = " title='$longurl'";
652 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
655 function common_longurl($short_url)
657 $long_url = common_shorten_link($short_url, true);
658 if ($long_url === $short_url) return false;
662 function common_longurl2($uri)
664 $uri_e = urlencode($uri);
665 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
666 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
667 return stripslashes($longurl['long_url']);
670 function common_shorten_links($text)
672 if (mb_strlen($text) <= 140) return $text;
673 static $cache = array();
674 if (isset($cache[$text])) return $cache[$text];
675 // \s = not a horizontal whitespace character (since PHP 5.2.4)
676 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
679 function common_shorten_link($url, $reverse = false)
681 static $url_cache = array();
682 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
684 $user = common_current_user();
686 $curlh = curl_init();
687 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
688 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
689 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
691 switch($user->urlshorteningservice) {
693 $short_url_service = new LilUrl;
694 $short_url = $short_url_service->shorten($url);
698 $short_url_service = new TightUrl;
699 $short_url = $short_url_service->shorten($url);
703 $short_url_service = new PtitUrl;
704 $short_url = $short_url_service->shorten($url);
708 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
709 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
713 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
714 $short_url = curl_exec($curlh);
717 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
718 $short_url = curl_exec($curlh);
721 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
722 $short_url = curl_exec($curlh);
725 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
726 $short_url = curl_exec($curlh);
735 $url_cache[(string)$short_url] = $url;
736 return (string)$short_url;
741 function common_xml_safe_str($str)
743 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
745 // Replace control, formatting, and surrogate characters with '*', ala Twitter
746 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
749 function common_tag_link($tag)
751 $canonical = common_canonical_tag($tag);
752 $url = common_local_url('tag', array('tag' => $canonical));
753 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
756 function common_canonical_tag($tag)
758 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
761 function common_valid_profile_tag($str)
763 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
766 function common_at_link($sender_id, $nickname)
768 $sender = Profile::staticGet($sender_id);
769 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
771 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
777 function common_at_hash_link($sender_id, $tag)
779 $user = User::staticGet($sender_id);
783 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
785 $url = common_local_url('subscriptions',
786 array('nickname' => $user->nickname,
788 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
794 function common_relative_profile($sender, $nickname, $dt=null)
796 // Try to find profiles this profile is subscribed to that have this nickname
797 $recipient = new Profile();
798 // XXX: use a join instead of a subquery
799 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
800 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
801 if ($recipient->find(true)) {
802 // XXX: should probably differentiate between profiles with
803 // the same name by date of most recent update
806 // Try to find profiles that listen to this profile and that have this nickname
807 $recipient = new Profile();
808 // XXX: use a join instead of a subquery
809 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
810 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
811 if ($recipient->find(true)) {
812 // XXX: should probably differentiate between profiles with
813 // the same name by date of most recent update
816 // If this is a local user, try to find a local user with that nickname.
817 $sender = User::staticGet($sender->id);
819 $recipient_user = User::staticGet('nickname', $nickname);
820 if ($recipient_user) {
821 return $recipient_user->getProfile();
824 // Otherwise, no links. @messages from local users to remote users,
825 // or from remote users to other remote users, are just
826 // outside our ability to make intelligent guesses about
830 // where should the avatar go for this user?
832 function common_avatar_filename($id, $extension, $size=null, $extra=null)
837 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
839 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
843 function common_avatar_path($filename)
846 return INSTALLDIR . '/avatar/' . $filename;
849 function common_avatar_url($filename)
851 return common_path('avatar/'.$filename);
854 function common_avatar_display_url($avatar)
856 $server = common_config('avatar', 'server');
858 return 'http://'.$server.'/'.$avatar->filename;
864 function common_default_avatar($size)
866 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
867 AVATAR_STREAM_SIZE => 'stream',
868 AVATAR_MINI_SIZE => 'mini');
869 return theme_path('default-avatar-'.$sizenames[$size].'.png');
872 function common_local_url($action, $args=null, $fragment=null)
875 if (common_config('site','fancy')) {
876 $url = common_fancy_url($action, $args);
878 $url = common_simple_url($action, $args);
880 if (!is_null($fragment)) {
881 $url .= '#'.$fragment;
886 function common_fancy_url($action, $args=null)
888 switch (strtolower($action)) {
890 if ($args && isset($args['page'])) {
891 return common_path('?page=' . $args['page']);
893 return common_path('');
896 if ($args && isset($args['page'])) {
897 return common_path('featured?page=' . $args['page']);
899 return common_path('featured');
902 if ($args && isset($args['page'])) {
903 return common_path('favorited?page=' . $args['page']);
905 return common_path('favorited');
908 return common_path('rss');
910 return common_path("api/statuses/public_timeline.atom");
912 return common_path('xrds');
914 return common_path('featuredrss');
916 return common_path('favoritedrss');
918 if ($args && $args['type']) {
919 return common_path('opensearch/'.$args['type']);
921 return common_path('opensearch/people');
924 return common_path('doc/'.$args['title']);
931 return common_path('main/'.$action);
933 return common_path('main/tagother?id='.$args['id']);
935 if ($args && $args['code']) {
936 return common_path('main/register/'.$args['code']);
938 return common_path('main/register');
940 case 'remotesubscribe':
941 if ($args && $args['nickname']) {
942 return common_path('main/remote?nickname=' . $args['nickname']);
944 return common_path('main/remote');
947 return common_path($args['nickname'].'/nudge');
949 return common_path('main/openid');
950 case 'profilesettings':
951 return common_path('settings/profile');
952 case 'emailsettings':
953 return common_path('settings/email');
954 case 'openidsettings':
955 return common_path('settings/openid');
957 return common_path('settings/sms');
958 case 'twittersettings':
959 return common_path('settings/twitter');
960 case 'othersettings':
961 return common_path('settings/other');
962 case 'deleteprofile':
963 return common_path('settings/delete');
965 if ($args && $args['replyto']) {
966 return common_path('notice/new?replyto='.$args['replyto']);
968 return common_path('notice/new');
971 return common_path('notice/'.$args['notice']);
973 if ($args && $args['notice']) {
974 return common_path('notice/delete/'.$args['notice']);
976 return common_path('notice/delete');
981 return common_path($args['nickname'].'/'.$action);
986 if ($args && isset($args['page'])) {
987 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
989 return common_path($args['nickname'].'/'.$action);
991 case 'subscriptions':
993 $nickname = $args['nickname'];
994 unset($args['nickname']);
995 if (isset($args['tag'])) {
999 $params = http_build_query($args);
1001 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
1003 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
1006 return common_path($args['nickname'].'/all/rss');
1008 return common_path($args['nickname'].'/replies/rss');
1010 if (isset($args['limit']))
1011 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
1012 return common_path($args['nickname'].'/rss');
1014 if ($args && isset($args['page'])) {
1015 return common_path($args['nickname'].'?page=' . $args['page']);
1017 return common_path($args['nickname']);
1020 case 'usertimeline':
1021 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1022 case 'confirmaddress':
1023 return common_path('main/confirmaddress/'.$args['code']);
1025 return common_path('user/'.$args['id']);
1026 case 'recoverpassword':
1027 $path = 'main/recoverpassword';
1028 if ($args['code']) {
1029 $path .= '/' . $args['code'];
1031 return common_path($path);
1033 return common_path('settings/im');
1034 case 'peoplesearch':
1035 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1036 case 'noticesearch':
1037 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1038 case 'noticesearchrss':
1039 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1040 case 'avatarbynickname':
1041 return common_path($args['nickname'].'/avatar/'.$args['size']);
1043 if (isset($args['tag']) && $args['tag']) {
1044 $path = 'tag/' . $args['tag'];
1045 unset($args['tag']);
1049 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1051 $path = 'peopletag/' . $args['tag'];
1052 unset($args['tag']);
1053 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1055 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1057 return common_path('main/favor');
1059 return common_path('main/disfavor');
1060 case 'showfavorites':
1061 if ($args && isset($args['page'])) {
1062 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1064 return common_path($args['nickname'].'/favorites');
1066 case 'favoritesrss':
1067 return common_path($args['nickname'].'/favorites/rss');
1069 return common_path('message/' . $args['message']);
1071 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1073 // XXX: do fancy URLs for all the API methods
1074 switch (strtolower($args['apiaction'])) {
1076 switch (strtolower($args['method'])) {
1077 case 'user_timeline.rss':
1078 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1079 case 'user_timeline.atom':
1080 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
1081 case 'user_timeline.json':
1082 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
1083 case 'user_timeline.xml':
1084 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
1085 default: return common_simple_url($action, $args);
1087 default: return common_simple_url($action, $args);
1090 if ($args && isset($args['seconds'])) {
1091 return common_path('main/sup?seconds='.$args['seconds']);
1093 return common_path('main/sup');
1096 return common_simple_url($action, $args);
1100 function common_simple_url($action, $args=null)
1103 /* XXX: pretty URLs */
1106 foreach ($args as $key => $value) {
1107 $extra .= "&${key}=${value}";
1110 return common_path("index.php?action=${action}${extra}");
1113 function common_path($relative)
1116 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1117 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1120 function common_date_string($dt)
1122 // XXX: do some sexy date formatting
1123 // return date(DATE_RFC822, $dt);
1124 $t = strtotime($dt);
1128 if ($now < $t) { // that shouldn't happen!
1129 return common_exact_date($dt);
1130 } else if ($diff < 60) {
1131 return _('a few seconds ago');
1132 } else if ($diff < 92) {
1133 return _('about a minute ago');
1134 } else if ($diff < 3300) {
1135 return sprintf(_('about %d minutes ago'), round($diff/60));
1136 } else if ($diff < 5400) {
1137 return _('about an hour ago');
1138 } else if ($diff < 22 * 3600) {
1139 return sprintf(_('about %d hours ago'), round($diff/3600));
1140 } else if ($diff < 37 * 3600) {
1141 return _('about a day ago');
1142 } else if ($diff < 24 * 24 * 3600) {
1143 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1144 } else if ($diff < 46 * 24 * 3600) {
1145 return _('about a month ago');
1146 } else if ($diff < 330 * 24 * 3600) {
1147 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1148 } else if ($diff < 480 * 24 * 3600) {
1149 return _('about a year ago');
1151 return common_exact_date($dt);
1155 function common_exact_date($dt)
1161 $_utc = new DateTimeZone('UTC');
1162 $_siteTz = new DateTimeZone(common_timezone());
1165 $dateStr = date('d F Y H:i:s', strtotime($dt));
1166 $d = new DateTime($dateStr, $_utc);
1167 $d->setTimezone($_siteTz);
1168 return $d->format(DATE_RFC850);
1171 function common_date_w3dtf($dt)
1173 $dateStr = date('d F Y H:i:s', strtotime($dt));
1174 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1175 $d->setTimezone(new DateTimeZone(common_timezone()));
1176 return $d->format(DATE_W3C);
1179 function common_date_rfc2822($dt)
1181 $dateStr = date('d F Y H:i:s', strtotime($dt));
1182 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1183 $d->setTimezone(new DateTimeZone(common_timezone()));
1184 return $d->format('r');
1187 function common_date_iso8601($dt)
1189 $dateStr = date('d F Y H:i:s', strtotime($dt));
1190 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1191 $d->setTimezone(new DateTimeZone(common_timezone()));
1192 return $d->format('c');
1195 function common_sql_now()
1197 return strftime('%Y-%m-%d %H:%M:%S', time());
1200 function common_redirect($url, $code=307)
1202 static $status = array(301 => "Moved Permanently",
1205 307 => "Temporary Redirect");
1206 header("Status: ${code} $status[$code]");
1207 header("Location: $url");
1209 common_start_xml('a',
1210 '-//W3C//DTD XHTML 1.0 Strict//EN',
1211 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1212 common_element('a', array('href' => $url), $url);
1217 function common_save_replies($notice)
1219 // Alternative reply format
1221 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1224 // extract all @messages
1225 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1229 if ($cnt || $tname) {
1230 // XXX: is there another way to make an array copy?
1231 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1234 $sender = Profile::staticGet($notice->profile_id);
1238 // store replied only for first @ (what user/notice what the reply directed,
1239 // we assume first @ is it)
1241 for ($i=0; $i<count($names); $i++) {
1242 $nickname = $names[$i];
1243 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1247 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self
1248 $reply_for = $recipient;
1249 $recipient_notice = $reply_for->getCurrentNotice();
1250 if ($recipient_notice) {
1251 $orig = clone($notice);
1252 $notice->reply_to = $recipient_notice->id;
1253 $notice->update($orig);
1256 // Don't save replies from blocked profile to local user
1257 $recipient_user = User::staticGet('id', $recipient->id);
1258 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1261 $reply = new Reply();
1262 $reply->notice_id = $notice->id;
1263 $reply->profile_id = $recipient->id;
1264 $id = $reply->insert();
1266 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1267 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1268 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1271 $replied[$recipient->id] = 1;
1275 // Hash format replies, too
1276 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1278 foreach ($match[1] as $tag) {
1279 $tagged = Profile_tag::getTagged($sender->id, $tag);
1280 foreach ($tagged as $t) {
1281 if (!$replied[$t->id]) {
1282 // Don't save replies from blocked profile to local user
1283 $t_user = User::staticGet('id', $t->id);
1284 if ($t_user && $t_user->hasBlocked($sender)) {
1287 $reply = new Reply();
1288 $reply->notice_id = $notice->id;
1289 $reply->profile_id = $t->id;
1290 $id = $reply->insert();
1292 common_log_db_error($reply, 'INSERT', __FILE__);
1301 function common_broadcast_notice($notice, $remote=false)
1304 // Check to see if notice should go to Twitter
1305 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1306 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1308 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1310 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1311 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1313 $result = common_twitter_broadcast($notice, $flink);
1316 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1321 if (common_config('queue', 'enabled')) {
1323 return common_enqueue_notice($notice);
1325 return common_real_broadcast($notice, $remote);
1329 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,
1356 # Twitter is strict about accepting invalid "Expect" headers
1357 CURLOPT_HTTPHEADER => array('Expect:')
1360 $ch = curl_init($uri);
1361 curl_setopt_array($ch, $options);
1362 $data = curl_exec($ch);
1363 $errmsg = curl_error($ch);
1366 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1374 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1379 // Twitter should return a status
1380 $status = json_decode($data);
1383 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1391 // Stick the notice on the queue
1393 function common_enqueue_notice($notice)
1395 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1396 $qi = new Queue_item();
1397 $qi->notice_id = $notice->id;
1398 $qi->transport = $transport;
1399 $qi->created = $notice->created;
1400 $result = $qi->insert();
1402 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1403 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1406 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1411 function common_dequeue_notice($notice)
1413 $qi = Queue_item::staticGet($notice->id);
1415 $result = $qi->delete();
1417 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1418 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1421 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1428 function common_real_broadcast($notice, $remote=false)
1432 // Make sure we have the OMB stuff
1433 require_once(INSTALLDIR.'/lib/omb.php');
1434 $success = omb_broadcast_remote_subscribers($notice);
1436 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1440 require_once(INSTALLDIR.'/lib/jabber.php');
1441 $success = jabber_broadcast_notice($notice);
1443 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1447 require_once(INSTALLDIR.'/lib/mail.php');
1448 $success = mail_broadcast_notice_sms($notice);
1450 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1454 $success = jabber_public_notice($notice);
1456 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1459 // XXX: broadcast notices to other IM
1463 function common_broadcast_profile($profile)
1465 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1466 require_once(INSTALLDIR.'/lib/omb.php');
1467 omb_broadcast_profile($profile);
1468 // XXX: Other broadcasts...?
1472 function common_profile_url($nickname)
1474 return common_local_url('showstream', array('nickname' => $nickname));
1477 // Don't call if nobody's logged in
1479 function common_notice_form($action=null, $content=null)
1481 $user = common_current_user();
1482 assert(!is_null($user));
1483 common_element_start('form', array('id' => 'status_form',
1485 'action' => common_local_url('newnotice')));
1486 common_element_start('p');
1487 common_element('label', array('for' => 'status_textarea',
1488 'id' => 'status_label'),
1489 sprintf(_('What\'s up, %s?'), $user->nickname));
1490 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1491 common_element('textarea', array('id' => 'status_textarea',
1494 'name' => 'status_textarea'),
1495 ($content) ? $content : '');
1496 common_hidden('token', common_session_token());
1498 common_hidden('returnto', $action);
1500 // set by JavaScript
1501 common_hidden('inreplyto', 'false');
1502 common_element('input', array('id' => 'status_submit',
1503 'name' => 'status_submit',
1505 'value' => _('Send')));
1506 common_element_end('p');
1507 common_element_end('form');
1510 // Should make up a reasonable root URL
1512 function common_root_url()
1514 return common_path('');
1517 // returns $bytes bytes of random data as a hexadecimal string
1518 // "good" here is a goal and not a guarantee
1520 function common_good_rand($bytes)
1522 // XXX: use random.org...?
1523 if (file_exists('/dev/urandom')) {
1524 return common_urandom($bytes);
1525 } else { // FIXME: this is probably not good enough
1526 return common_mtrand($bytes);
1530 function common_urandom($bytes)
1532 $h = fopen('/dev/urandom', 'rb');
1534 $src = fread($h, $bytes);
1537 for ($i = 0; $i < $bytes; $i++) {
1538 $enc .= sprintf("%02x", (ord($src[$i])));
1543 function common_mtrand($bytes)
1546 for ($i = 0; $i < $bytes; $i++) {
1547 $enc .= sprintf("%02x", mt_rand(0, 255));
1552 function common_set_returnto($url)
1554 common_ensure_session();
1555 $_SESSION['returnto'] = $url;
1558 function common_get_returnto()
1560 common_ensure_session();
1561 return $_SESSION['returnto'];
1564 function common_timestamp()
1566 return date('YmdHis');
1569 function common_ensure_syslog()
1571 static $initialized = false;
1572 if (!$initialized) {
1574 openlog($config['syslog']['appname'], 0, LOG_USER);
1575 $initialized = true;
1579 function common_log($priority, $msg, $filename=null)
1581 $logfile = common_config('site', 'logfile');
1583 $log = fopen($logfile, "a");
1585 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1586 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1587 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1588 fwrite($log, $output);
1592 common_ensure_syslog();
1593 syslog($priority, $msg);
1597 function common_debug($msg, $filename=null)
1600 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1602 common_log(LOG_DEBUG, $msg);
1606 function common_log_db_error(&$object, $verb, $filename=null)
1608 $objstr = common_log_objstring($object);
1609 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1610 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1613 function common_log_objstring(&$object)
1615 if (is_null($object)) {
1618 $arr = $object->toArray();
1620 foreach ($arr as $k => $v) {
1621 $fields[] = "$k='$v'";
1623 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1627 function common_valid_http_url($url)
1629 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1632 function common_valid_tag($tag)
1634 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1635 return (Validate::email($matches[1]) ||
1636 preg_match('/^([\w-\.]+)$/', $matches[1]));
1641 // Does a little before-after block for next/prev page
1643 function common_pagination($have_before, $have_after, $page, $action, $args=null)
1646 if ($have_before || $have_after) {
1647 common_element_start('div', array('id' => 'pagination'));
1648 common_element_start('ul', array('id' => 'nav_pagination'));
1652 $pargs = array('page' => $page-1);
1653 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1655 common_element_start('li', 'before');
1656 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1658 common_element_end('li');
1662 $pargs = array('page' => $page+1);
1663 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1664 common_element_start('li', 'after');
1665 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1667 common_element_end('li');
1670 if ($have_before || $have_after) {
1671 common_element_end('ul');
1672 common_element_end('div');
1676 /* Following functions are copied from MediaWiki GlobalFunctions.php
1677 * and written by Evan Prodromou. */
1679 function common_accept_to_prefs($accept, $def = '*/*')
1681 // No arg means accept anything (per HTTP spec)
1683 return array($def => 1);
1688 $parts = explode(',', $accept);
1690 foreach($parts as $part) {
1691 // FIXME: doesn't deal with params like 'text/html; level=1'
1692 @list($value, $qpart) = explode(';', $part);
1694 if(!isset($qpart)) {
1696 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1697 $prefs[$value] = $match[1];
1704 function common_mime_type_match($type, $avail)
1706 if(array_key_exists($type, $avail)) {
1709 $parts = explode('/', $type);
1710 if(array_key_exists($parts[0] . '/*', $avail)) {
1711 return $parts[0] . '/*';
1712 } elseif(array_key_exists('*/*', $avail)) {
1720 function common_negotiate_type($cprefs, $sprefs)
1724 foreach(array_keys($sprefs) as $type) {
1725 $parts = explode('/', $type);
1726 if($parts[1] != '*') {
1727 $ckey = common_mime_type_match($type, $cprefs);
1729 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1734 foreach(array_keys($cprefs) as $type) {
1735 $parts = explode('/', $type);
1736 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1737 $skey = common_mime_type_match($type, $sprefs);
1739 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1745 $besttype = "text/html";
1747 foreach(array_keys($combine) as $type) {
1748 if($combine[$type] > $bestq) {
1750 $bestq = $combine[$type];
1757 function common_config($main, $sub)
1760 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1763 function common_copy_args($from)
1766 $strip = get_magic_quotes_gpc();
1767 foreach ($from as $k => $v) {
1768 $to[$k] = ($strip) ? stripslashes($v) : $v;
1773 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1774 // This is used before handing a request off to OAuthRequest::from_request.
1775 function common_remove_magic_from_request()
1777 if(get_magic_quotes_gpc()) {
1778 $_POST=array_map('stripslashes',$_POST);
1779 $_GET=array_map('stripslashes',$_GET);
1783 function common_user_uri(&$user)
1785 return common_local_url('userbyid', array('id' => $user->id));
1788 function common_notice_uri(&$notice)
1790 return common_local_url('shownotice',
1791 array('notice' => $notice->id));
1794 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1796 function common_confirmation_code($bits)
1798 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1799 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1800 $chars = ceil($bits/5);
1802 for ($i = 0; $i < $chars; $i++) {
1803 // XXX: convert to string and back
1804 $num = hexdec(common_good_rand(1));
1805 // XXX: randomness is too precious to throw away almost
1806 // 40% of the bits we get!
1807 $code .= $codechars[$num%32];
1812 // convert markup to HTML
1814 function common_markup_to_html($c)
1816 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1817 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1818 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1819 return Markdown($c);
1822 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
1824 $avatar = $profile->getAvatar($size);
1826 return common_avatar_display_url($avatar);
1828 return common_default_avatar($size);
1832 function common_profile_uri($profile)
1837 $user = User::staticGet($profile->id);
1842 $remote = Remote_profile::staticGet($profile->id);
1844 return $remote->uri;
1846 // XXX: this is a very bad profile!
1850 function common_canonical_sms($sms)
1853 preg_replace('/\D/', '', $sms);
1857 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1861 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1865 case E_USER_WARNING:
1866 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1870 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1874 // FIXME: show error page if we're on the Web
1875 /* Don't execute PHP internal error handler */
1879 function common_session_token()
1881 common_ensure_session();
1882 if (!array_key_exists('token', $_SESSION)) {
1883 $_SESSION['token'] = common_good_rand(64);
1885 return $_SESSION['token'];
1888 function common_disfavor_form($notice)
1890 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1892 'class' => 'disfavor',
1893 'action' => common_local_url('disfavor')));
1895 common_element('input', array('type' => 'hidden',
1896 'name' => 'token-'. $notice->id,
1897 'id' => 'token-'. $notice->id,
1899 'value' => common_session_token()));
1901 common_element('input', array('type' => 'hidden',
1903 'id' => 'notice-n'. $notice->id,
1904 'class' => 'notice',
1905 'value' => $notice->id));
1907 common_element('input', array('type' => 'submit',
1908 'id' => 'disfavor-submit-' . $notice->id,
1909 'name' => 'disfavor-submit-' . $notice->id,
1910 'class' => 'disfavor',
1911 'value' => 'Disfavor favorite',
1912 'title' => 'Remove this message from favorites'));
1913 common_element_end('form');
1916 function common_favor_form($notice)
1918 common_element_start('form', array('id' => 'favor-' . $notice->id,
1921 'action' => common_local_url('favor')));
1923 common_element('input', array('type' => 'hidden',
1924 'name' => 'token-'. $notice->id,
1925 'id' => 'token-'. $notice->id,
1927 'value' => common_session_token()));
1929 common_element('input', array('type' => 'hidden',
1931 'id' => 'notice-n'. $notice->id,
1932 'class' => 'notice',
1933 'value' => $notice->id));
1935 common_element('input', array('type' => 'submit',
1936 'id' => 'favor-submit-' . $notice->id,
1937 'name' => 'favor-submit-' . $notice->id,
1939 'value' => 'Add to favorites',
1940 'title' => 'Add this message to favorites'));
1941 common_element_end('form');
1944 function common_nudge_form($profile)
1946 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
1947 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
1948 common_hidden('token', common_session_token());
1949 common_element('input', array('type' => 'submit',
1950 'class' => 'submit',
1951 'value' => _('Send a nudge')));
1952 common_element_end('form');
1954 function common_nudge_response()
1956 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
1959 function common_subscribe_form($profile)
1961 common_element_start('form', array('id' => 'subscribe-' . $profile->id,
1963 'class' => 'subscribe',
1964 'action' => common_local_url('subscribe')));
1965 common_hidden('token', common_session_token());
1966 common_element('input', array('id' => 'subscribeto-' . $profile->id,
1967 'name' => 'subscribeto',
1969 'value' => $profile->id));
1970 common_element('input', array('type' => 'submit',
1971 'class' => 'submit',
1972 'value' => _('Subscribe')));
1973 common_element_end('form');
1976 function common_unsubscribe_form($profile)
1978 common_element_start('form', array('id' => 'unsubscribe-' . $profile->id,
1980 'class' => 'unsubscribe',
1981 'action' => common_local_url('unsubscribe')));
1982 common_hidden('token', common_session_token());
1983 common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
1984 'name' => 'unsubscribeto',
1986 'value' => $profile->id));
1987 common_element('input', array('type' => 'submit',
1988 'class' => 'submit',
1989 'value' => _('Unsubscribe')));
1990 common_element_end('form');
1993 // XXX: Refactor this code
1994 function common_profile_new_message_nudge ($cur, $profile)
1996 $user = User::staticGet('id', $profile->id);
1998 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
1999 common_element_start('li', array('id' => 'profile_send_a_new_message'));
2000 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
2001 _('Send a message'));
2002 common_element_end('li');
2004 if ($user->email && $user->emailnotifynudge) {
2005 common_element_start('li', array('id' => 'profile_nudge'));
2006 common_nudge_form($user);
2007 common_element_end('li');
2012 function common_cache_key($extra)
2014 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
2017 function common_keyize($str)
2019 $str = strtolower($str);
2020 $str = preg_replace('/\s/', '_', $str);
2024 function common_message_form($content, $user, $to)
2027 common_element_start('form', array('id' => 'message_form',
2029 'action' => common_local_url('newmessage')));
2031 $mutual_users = $user->mutuallySubscribedUsers();
2035 while ($mutual_users->fetch()) {
2036 if ($mutual_users->id != $user->id) {
2037 $mutual[$mutual_users->id] = $mutual_users->nickname;
2041 $mutual_users->free();
2042 unset($mutual_users);
2044 common_dropdown('to', _('To'), $mutual, null, false, $to->id);
2046 common_element_start('p');
2048 common_element('textarea', array('id' => 'message_content',
2051 'name' => 'content'),
2052 ($content) ? $content : '');
2054 common_element('input', array('id' => 'message_send',
2055 'name' => 'message_send',
2057 'value' => _('Send')));
2059 common_hidden('token', common_session_token());
2061 common_element_end('p');
2062 common_element_end('form');
2065 function common_memcache()
2067 static $cache = null;
2068 if (!common_config('memcached', 'enabled')) {
2072 $cache = new Memcache();
2073 $servers = common_config('memcached', 'server');
2074 if (is_array($servers)) {
2075 foreach($servers as $server) {
2076 $cache->addServer($server);
2079 $cache->addServer($servers);
2086 function common_compatible_license($from, $to)
2088 // XXX: better compatibility check needed here!
2089 return ($from == $to);
2092 /* These are almost identical, so we use a helper function */
2094 function common_block_form($profile, $args=null)
2096 common_blocking_form('block', _('Block'), $profile, $args);
2099 function common_unblock_form($profile, $args=null)
2101 common_blocking_form('unblock', _('Unblock'), $profile, $args);
2104 function common_blocking_form($type, $label, $profile, $args=null)
2106 common_element_start('form', array('id' => $type . '-' . $profile->id,
2109 'action' => common_local_url($type)));
2110 common_hidden('token', common_session_token());
2111 common_element('input', array('id' => $type . 'to-' . $profile->id,
2112 'name' => $type . 'to',
2114 'value' => $profile->id));
2115 common_element('input', array('type' => 'submit',
2116 'class' => 'submit',
2118 'value' => $label));
2120 foreach ($args as $k => $v) {
2121 common_hidden('returnto-' . $k, $v);
2124 common_element_end('form');