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_timezone()
113 if (common_logged_in()) {
114 $user = common_current_user();
115 if ($user->timezone) {
116 return $user->timezone;
121 return $config['site']['timezone'];
124 function common_language()
127 // If there is a user logged in and they've set a language preference
128 // then return that one...
129 if (common_logged_in()) {
130 $user = common_current_user();
131 $user_language = $user->language;
133 return $user_language;
136 // Otherwise, find the best match for the languages requested by the
138 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
139 if (!empty($httplang)) {
140 $language = client_prefered_language($httplang);
145 // Finally, if none of the above worked, use the site's default...
146 return common_config('site', 'language');
148 // salted, hashed passwords are stored in the DB
150 function common_munge_password($password, $id)
152 return md5($password . $id);
155 // check if a username exists and has matching password
156 function common_check_user($nickname, $password)
158 // NEVER allow blank passwords, even if they match the DB
159 if (mb_strlen($password) == 0) {
162 $user = User::staticGet('nickname', $nickname);
163 if (is_null($user)) {
166 if (0 == strcmp(common_munge_password($password, $user->id),
175 // is the current user logged in?
176 function common_logged_in()
178 return (!is_null(common_current_user()));
181 function common_have_session()
183 return (0 != strcmp(session_id(), ''));
186 function common_ensure_session()
188 if (!common_have_session()) {
193 // Three kinds of arguments:
198 // Initialize to false; set to null if none found
202 function common_set_user($user)
207 if (is_null($user) && common_have_session()) {
209 unset($_SESSION['userid']);
211 } else if (is_string($user)) {
213 $user = User::staticGet('nickname', $nickname);
214 } else if (!($user instanceof User)) {
219 common_ensure_session();
220 $_SESSION['userid'] = $user->id;
227 function common_set_cookie($key, $value, $expiration=0)
229 $path = common_config('site', 'path');
230 $server = common_config('site', 'server');
232 if ($path && ($path != '/')) {
233 $cookiepath = '/' . $path . '/';
237 return setcookie($key,
244 define('REMEMBERME', 'rememberme');
245 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
247 function common_rememberme($user=null)
250 $user = common_current_user();
252 common_debug('No current user to remember', __FILE__);
257 $rm = new Remember_me();
259 $rm->code = common_good_rand(16);
260 $rm->user_id = $user->id;
262 // Wrap the insert in some good ol' fashioned transaction code
266 $result = $rm->insert();
269 common_log_db_error($rm, 'INSERT', __FILE__);
270 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
274 $rm->query('COMMIT');
276 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
278 $cookieval = $rm->user_id . ':' . $rm->code;
280 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
282 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
287 function common_remembered_user()
292 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
298 list($id, $code) = explode(':', $packed);
300 if (!$id || !$code) {
301 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
306 $rm = Remember_me::staticGet($code);
309 common_log(LOG_WARNING, 'No such remember code: ' . $code);
314 if ($rm->user_id != $id) {
315 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
320 $user = User::staticGet($rm->user_id);
323 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
329 $result = $rm->delete();
332 common_log_db_error($rm, 'DELETE', __FILE__);
333 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
338 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
340 common_set_user($user);
341 common_real_login(false);
343 // We issue a new cookie, so they can log in
344 // automatically again after this session
346 common_rememberme($user);
351 // must be called with a valid user!
353 function common_forgetme()
355 common_set_cookie(REMEMBERME, '', 0);
358 // who is the current user?
359 function common_current_user()
363 if ($_cur === false) {
365 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
366 common_ensure_session();
367 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
369 $_cur = User::staticGet($id);
374 // that didn't work; try to remember; will init $_cur to null on failure
375 $_cur = common_remembered_user();
378 common_debug("Got User " . $_cur->nickname);
379 common_debug("Faking session on remembered user");
380 // XXX: Is this necessary?
381 $_SESSION['userid'] = $_cur->id;
388 // Logins that are 'remembered' aren't 'real' -- they're subject to
389 // cookie-stealing. So, we don't let them do certain things. New reg,
390 // OpenID, and password logins _are_ real.
392 function common_real_login($real=true)
394 common_ensure_session();
395 $_SESSION['real_login'] = $real;
398 function common_is_real_login()
400 return common_logged_in() && $_SESSION['real_login'];
403 // get canonical version of nickname for comparison
404 function common_canonical_nickname($nickname)
406 // XXX: UTF-8 canonicalization (like combining chars)
407 return strtolower($nickname);
410 // get canonical version of email for comparison
411 function common_canonical_email($email)
413 // XXX: canonicalize UTF-8
414 // XXX: lcase the domain part
418 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$_+!*();/?:~-]))');
420 function common_render_content($text, $notice)
422 $r = common_render_text($text);
423 $id = $notice->profile_id;
424 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
425 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
426 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
427 $r = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
431 function common_render_text($text)
433 $r = htmlspecialchars($text);
435 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
436 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
437 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
442 function common_render_uri_thingy($matches)
447 // Some heuristics for extracting URIs from surrounding punctuation
448 // Strip from trailing text...
449 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
451 $trailer = $matches[2];
455 ']' => '[', // technically disallowed in URIs, but used in Java docs
456 ')' => '(', // far too frequent in Wikipedia and MSDN
458 $final = substr($uri, -1, 1);
459 if (isset($pairs[$final])) {
460 $openers = substr_count($uri, $pairs[$final]);
461 $closers = substr_count($uri, $final);
462 if ($closers > $openers) {
463 // Assume the paren was opened outside the URI
464 $uri = substr($uri, 0, -1);
465 $trailer = $final . $trailer;
468 if ($longurl = common_longurl($uri)) {
469 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
470 $title = " title='$longurl'";
474 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
477 function common_longurl($short_url)
479 $long_url = common_shorten_link($short_url, true);
480 if ($long_url === $short_url) return false;
484 function common_longurl2($uri)
486 $uri_e = urlencode($uri);
487 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
488 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
489 return stripslashes($longurl['long_url']);
492 function common_shorten_links($text)
494 if (mb_strlen($text) <= 140) return $text;
495 static $cache = array();
496 if (isset($cache[$text])) return $cache[$text];
497 // \s = not a horizontal whitespace character (since PHP 5.2.4)
498 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
501 function common_shorten_link($url, $reverse = false)
503 static $url_cache = array();
504 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
506 $user = common_current_user();
508 $curlh = curl_init();
509 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
510 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
511 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
513 switch($user->urlshorteningservice) {
515 $short_url_service = new LilUrl;
516 $short_url = $short_url_service->shorten($url);
520 $short_url_service = new TightUrl;
521 $short_url = $short_url_service->shorten($url);
525 $short_url_service = new PtitUrl;
526 $short_url = $short_url_service->shorten($url);
530 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
531 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
535 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
536 $short_url = curl_exec($curlh);
539 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
540 $short_url = curl_exec($curlh);
543 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
544 $short_url = curl_exec($curlh);
547 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
548 $short_url = curl_exec($curlh);
557 $url_cache[(string)$short_url] = $url;
558 return (string)$short_url;
563 function common_xml_safe_str($str)
565 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
567 // Replace control, formatting, and surrogate characters with '*', ala Twitter
568 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
571 function common_tag_link($tag)
573 $canonical = common_canonical_tag($tag);
574 $url = common_local_url('tag', array('tag' => $canonical));
575 return '<span class="tag"><a href="' . htmlspecialchars($url) . '" rel="tag">' . htmlspecialchars($tag) . '</a></span>';
578 function common_canonical_tag($tag)
580 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
583 function common_valid_profile_tag($str)
585 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
588 function common_at_link($sender_id, $nickname)
590 $sender = Profile::staticGet($sender_id);
591 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
593 return '<span class="vcard"><a href="'.htmlspecialchars($recipient->profileurl).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
599 function common_group_link($sender_id, $nickname)
601 $sender = Profile::staticGet($sender_id);
602 $group = User_group::staticGet('nickname', common_canonical_nickname($nickname));
603 if ($group && $sender->isMember($group)) {
604 return '<span class="vcard"><a href="'.htmlspecialchars($group->permalink()).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
610 function common_at_hash_link($sender_id, $tag)
612 $user = User::staticGet($sender_id);
616 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
618 $url = common_local_url('subscriptions',
619 array('nickname' => $user->nickname,
621 return '<span class="tag"><a href="'.htmlspecialchars($url).'" rel="tag">'.$tag.'</a></span>';
627 function common_relative_profile($sender, $nickname, $dt=null)
629 // Try to find profiles this profile is subscribed to that have this nickname
630 $recipient = new Profile();
631 // XXX: use a join instead of a subquery
632 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
633 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
634 if ($recipient->find(true)) {
635 // XXX: should probably differentiate between profiles with
636 // the same name by date of most recent update
639 // Try to find profiles that listen to this profile and that have this nickname
640 $recipient = new Profile();
641 // XXX: use a join instead of a subquery
642 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
643 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
644 if ($recipient->find(true)) {
645 // XXX: should probably differentiate between profiles with
646 // the same name by date of most recent update
649 // If this is a local user, try to find a local user with that nickname.
650 $sender = User::staticGet($sender->id);
652 $recipient_user = User::staticGet('nickname', $nickname);
653 if ($recipient_user) {
654 return $recipient_user->getProfile();
657 // Otherwise, no links. @messages from local users to remote users,
658 // or from remote users to other remote users, are just
659 // outside our ability to make intelligent guesses about
663 // where should the avatar go for this user?
665 function common_avatar_filename($id, $extension, $size=null, $extra=null)
670 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
672 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
676 function common_avatar_path($filename)
679 return INSTALLDIR . '/avatar/' . $filename;
682 function common_avatar_url($filename)
684 return common_path('avatar/'.$filename);
687 function common_avatar_display_url($avatar)
689 $server = common_config('avatar', 'server');
691 return 'http://'.$server.'/'.$avatar->filename;
697 function common_default_avatar($size)
699 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
700 AVATAR_STREAM_SIZE => 'stream',
701 AVATAR_MINI_SIZE => 'mini');
702 return theme_path('default-avatar-'.$sizenames[$size].'.png');
705 function common_local_url($action, $args=null, $fragment=null)
708 if (common_config('site','fancy')) {
709 $url = common_fancy_url($action, $args);
711 $url = common_simple_url($action, $args);
713 if (!is_null($fragment)) {
714 $url .= '#'.$fragment;
719 function common_fancy_url($action, $args=null)
721 switch (strtolower($action)) {
723 if ($args && isset($args['page'])) {
724 return common_path('?page=' . $args['page']);
726 return common_path('');
729 if ($args && isset($args['page'])) {
730 return common_path('featured?page=' . $args['page']);
732 return common_path('featured');
735 if ($args && isset($args['page'])) {
736 return common_path('favorited?page=' . $args['page']);
738 return common_path('favorited');
741 return common_path('rss');
743 return common_path("api/statuses/public_timeline.atom");
745 return common_path('xrds');
747 return common_path('featuredrss');
749 return common_path('favoritedrss');
751 if ($args && $args['type']) {
752 return common_path('opensearch/'.$args['type']);
754 return common_path('opensearch/people');
757 return common_path('doc/'.$args['title']);
764 return common_path('main/'.$action);
766 return common_path('main/tagother?id='.$args['id']);
768 if ($args && $args['code']) {
769 return common_path('main/register/'.$args['code']);
771 return common_path('main/register');
773 case 'remotesubscribe':
774 if ($args && $args['nickname']) {
775 return common_path('main/remote?nickname=' . $args['nickname']);
777 return common_path('main/remote');
780 return common_path($args['nickname'].'/nudge');
782 return common_path('main/openid');
783 case 'profilesettings':
784 return common_path('settings/profile');
785 case 'passwordsettings':
786 return common_path('settings/password');
787 case 'emailsettings':
788 return common_path('settings/email');
789 case 'openidsettings':
790 return common_path('settings/openid');
792 return common_path('settings/sms');
793 case 'twittersettings':
794 return common_path('settings/twitter');
795 case 'othersettings':
796 return common_path('settings/other');
797 case 'deleteprofile':
798 return common_path('settings/delete');
800 if ($args && $args['replyto']) {
801 return common_path('notice/new?replyto='.$args['replyto']);
803 return common_path('notice/new');
806 return common_path('notice/'.$args['notice']);
808 if ($args && $args['notice']) {
809 return common_path('notice/delete/'.$args['notice']);
811 return common_path('notice/delete');
816 return common_path($args['nickname'].'/'.$action);
821 if ($args && isset($args['page'])) {
822 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
824 return common_path($args['nickname'].'/'.$action);
826 case 'subscriptions':
828 $nickname = $args['nickname'];
829 unset($args['nickname']);
830 if (isset($args['tag'])) {
834 $params = http_build_query($args);
836 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
838 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
841 return common_path($args['nickname'].'/all/rss');
843 return common_path($args['nickname'].'/replies/rss');
845 if (isset($args['limit']))
846 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
847 return common_path($args['nickname'].'/rss');
849 if ($args && isset($args['page'])) {
850 return common_path($args['nickname'].'?page=' . $args['page']);
852 return common_path($args['nickname']);
856 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
857 case 'confirmaddress':
858 return common_path('main/confirmaddress/'.$args['code']);
860 return common_path('user/'.$args['id']);
861 case 'recoverpassword':
862 $path = 'main/recoverpassword';
864 $path .= '/' . $args['code'];
866 return common_path($path);
868 return common_path('settings/im');
869 case 'avatarsettings':
870 return common_path('settings/avatar');
872 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
874 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
875 case 'noticesearchrss':
876 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
877 case 'avatarbynickname':
878 return common_path($args['nickname'].'/avatar/'.$args['size']);
880 $path = 'tag/' . $args['tag'];
882 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
883 case 'publictagcloud':
884 return common_path('tags');
886 $path = 'peopletag/' . $args['tag'];
888 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
890 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
892 return common_path('main/favor');
894 return common_path('main/disfavor');
895 case 'showfavorites':
896 if ($args && isset($args['page'])) {
897 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
899 return common_path($args['nickname'].'/favorites');
902 return common_path($args['nickname'].'/favorites/rss');
904 return common_path('message/' . $args['message']);
906 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
908 // XXX: do fancy URLs for all the API methods
909 switch (strtolower($args['apiaction'])) {
911 switch (strtolower($args['method'])) {
912 case 'user_timeline.rss':
913 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
914 case 'user_timeline.atom':
915 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
916 case 'user_timeline.json':
917 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
918 case 'user_timeline.xml':
919 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
920 default: return common_simple_url($action, $args);
922 default: return common_simple_url($action, $args);
925 if ($args && isset($args['seconds'])) {
926 return common_path('main/sup?seconds='.$args['seconds']);
928 return common_path('main/sup');
931 return common_path('group/new');
933 return common_path('group/'.$args['nickname']);
935 return common_path('group/'.$args['nickname'].'/edit');
937 return common_path('group/'.$args['nickname'].'/join');
939 return common_path('group/'.$args['nickname'].'/leave');
941 return common_path('group/'.$args['id'].'/id');
943 return common_path('group/'.$args['nickname'].'/rss');
945 return common_path('group/'.$args['nickname'].'/members');
947 return common_path($args['nickname'].'/groups');
949 return common_path('group');
951 return common_simple_url($action, $args);
955 function common_simple_url($action, $args=null)
958 /* XXX: pretty URLs */
961 foreach ($args as $key => $value) {
962 $extra .= "&${key}=${value}";
965 return common_path("index.php?action=${action}${extra}");
968 function common_path($relative)
971 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
972 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
975 function common_date_string($dt)
977 // XXX: do some sexy date formatting
978 // return date(DATE_RFC822, $dt);
983 if ($now < $t) { // that shouldn't happen!
984 return common_exact_date($dt);
985 } else if ($diff < 60) {
986 return _('a few seconds ago');
987 } else if ($diff < 92) {
988 return _('about a minute ago');
989 } else if ($diff < 3300) {
990 return sprintf(_('about %d minutes ago'), round($diff/60));
991 } else if ($diff < 5400) {
992 return _('about an hour ago');
993 } else if ($diff < 22 * 3600) {
994 return sprintf(_('about %d hours ago'), round($diff/3600));
995 } else if ($diff < 37 * 3600) {
996 return _('about a day ago');
997 } else if ($diff < 24 * 24 * 3600) {
998 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
999 } else if ($diff < 46 * 24 * 3600) {
1000 return _('about a month ago');
1001 } else if ($diff < 330 * 24 * 3600) {
1002 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1003 } else if ($diff < 480 * 24 * 3600) {
1004 return _('about a year ago');
1006 return common_exact_date($dt);
1010 function common_exact_date($dt)
1016 $_utc = new DateTimeZone('UTC');
1017 $_siteTz = new DateTimeZone(common_timezone());
1020 $dateStr = date('d F Y H:i:s', strtotime($dt));
1021 $d = new DateTime($dateStr, $_utc);
1022 $d->setTimezone($_siteTz);
1023 return $d->format(DATE_RFC850);
1026 function common_date_w3dtf($dt)
1028 $dateStr = date('d F Y H:i:s', strtotime($dt));
1029 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1030 $d->setTimezone(new DateTimeZone(common_timezone()));
1031 return $d->format(DATE_W3C);
1034 function common_date_rfc2822($dt)
1036 $dateStr = date('d F Y H:i:s', strtotime($dt));
1037 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1038 $d->setTimezone(new DateTimeZone(common_timezone()));
1039 return $d->format('r');
1042 function common_date_iso8601($dt)
1044 $dateStr = date('d F Y H:i:s', strtotime($dt));
1045 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1046 $d->setTimezone(new DateTimeZone(common_timezone()));
1047 return $d->format('c');
1050 function common_sql_now()
1052 return strftime('%Y-%m-%d %H:%M:%S', time());
1055 function common_redirect($url, $code=307)
1057 static $status = array(301 => "Moved Permanently",
1060 307 => "Temporary Redirect");
1062 header("Status: ${code} $status[$code]");
1063 header("Location: $url");
1065 $xo = new XMLOutputter();
1067 '-//W3C//DTD XHTML 1.0 Strict//EN',
1068 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1069 $xo->element('a', array('href' => $url), $url);
1074 function common_broadcast_notice($notice, $remote=false)
1077 // Check to see if notice should go to Twitter
1078 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1079 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1081 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1083 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1084 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1086 $result = common_twitter_broadcast($notice, $flink);
1089 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1094 if (common_config('queue', 'enabled')) {
1096 return common_enqueue_notice($notice);
1098 return common_real_broadcast($notice, $remote);
1102 function common_twitter_broadcast($notice, $flink)
1106 $fuser = $flink->getForeignUser();
1107 $twitter_user = $fuser->nickname;
1108 $twitter_password = $flink->credentials;
1109 $uri = 'http://www.twitter.com/statuses/update.json';
1111 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1112 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1115 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1116 CURLOPT_POST => true,
1117 CURLOPT_POSTFIELDS => array(
1118 'status' => $statustxt,
1119 'source' => $config['integration']['source']
1121 CURLOPT_RETURNTRANSFER => true,
1122 CURLOPT_FAILONERROR => true,
1123 CURLOPT_HEADER => false,
1124 CURLOPT_FOLLOWLOCATION => true,
1125 CURLOPT_USERAGENT => "Laconica",
1126 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1127 CURLOPT_TIMEOUT => 120,
1129 # Twitter is strict about accepting invalid "Expect" headers
1130 CURLOPT_HTTPHEADER => array('Expect:')
1133 $ch = curl_init($uri);
1134 curl_setopt_array($ch, $options);
1135 $data = curl_exec($ch);
1136 $errmsg = curl_error($ch);
1139 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1147 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1152 // Twitter should return a status
1153 $status = json_decode($data);
1156 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1164 // Stick the notice on the queue
1166 function common_enqueue_notice($notice)
1168 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1169 $qi = new Queue_item();
1170 $qi->notice_id = $notice->id;
1171 $qi->transport = $transport;
1172 $qi->created = $notice->created;
1173 $result = $qi->insert();
1175 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1176 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1179 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1184 function common_dequeue_notice($notice)
1186 $qi = Queue_item::staticGet($notice->id);
1188 $result = $qi->delete();
1190 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1191 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1194 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1201 function common_real_broadcast($notice, $remote=false)
1205 // Make sure we have the OMB stuff
1206 require_once(INSTALLDIR.'/lib/omb.php');
1207 $success = omb_broadcast_remote_subscribers($notice);
1209 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1213 require_once(INSTALLDIR.'/lib/jabber.php');
1214 $success = jabber_broadcast_notice($notice);
1216 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1220 require_once(INSTALLDIR.'/lib/mail.php');
1221 $success = mail_broadcast_notice_sms($notice);
1223 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1227 $success = jabber_public_notice($notice);
1229 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1232 // XXX: broadcast notices to other IM
1236 function common_broadcast_profile($profile)
1238 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1239 require_once(INSTALLDIR.'/lib/omb.php');
1240 omb_broadcast_profile($profile);
1241 // XXX: Other broadcasts...?
1245 function common_profile_url($nickname)
1247 return common_local_url('showstream', array('nickname' => $nickname));
1250 // Should make up a reasonable root URL
1252 function common_root_url()
1254 return common_path('');
1257 // returns $bytes bytes of random data as a hexadecimal string
1258 // "good" here is a goal and not a guarantee
1260 function common_good_rand($bytes)
1262 // XXX: use random.org...?
1263 if (file_exists('/dev/urandom')) {
1264 return common_urandom($bytes);
1265 } else { // FIXME: this is probably not good enough
1266 return common_mtrand($bytes);
1270 function common_urandom($bytes)
1272 $h = fopen('/dev/urandom', 'rb');
1274 $src = fread($h, $bytes);
1277 for ($i = 0; $i < $bytes; $i++) {
1278 $enc .= sprintf("%02x", (ord($src[$i])));
1283 function common_mtrand($bytes)
1286 for ($i = 0; $i < $bytes; $i++) {
1287 $enc .= sprintf("%02x", mt_rand(0, 255));
1292 function common_set_returnto($url)
1294 common_ensure_session();
1295 $_SESSION['returnto'] = $url;
1298 function common_get_returnto()
1300 common_ensure_session();
1301 return $_SESSION['returnto'];
1304 function common_timestamp()
1306 return date('YmdHis');
1309 function common_ensure_syslog()
1311 static $initialized = false;
1312 if (!$initialized) {
1314 openlog($config['syslog']['appname'], 0, LOG_USER);
1315 $initialized = true;
1319 function common_log($priority, $msg, $filename=null)
1321 $logfile = common_config('site', 'logfile');
1323 $log = fopen($logfile, "a");
1325 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1326 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1327 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1328 fwrite($log, $output);
1332 common_ensure_syslog();
1333 syslog($priority, $msg);
1337 function common_debug($msg, $filename=null)
1340 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1342 common_log(LOG_DEBUG, $msg);
1346 function common_log_db_error(&$object, $verb, $filename=null)
1348 $objstr = common_log_objstring($object);
1349 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1350 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1353 function common_log_objstring(&$object)
1355 if (is_null($object)) {
1358 $arr = $object->toArray();
1360 foreach ($arr as $k => $v) {
1361 $fields[] = "$k='$v'";
1363 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1367 function common_valid_http_url($url)
1369 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1372 function common_valid_tag($tag)
1374 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1375 return (Validate::email($matches[1]) ||
1376 preg_match('/^([\w-\.]+)$/', $matches[1]));
1381 /* Following functions are copied from MediaWiki GlobalFunctions.php
1382 * and written by Evan Prodromou. */
1384 function common_accept_to_prefs($accept, $def = '*/*')
1386 // No arg means accept anything (per HTTP spec)
1388 return array($def => 1);
1393 $parts = explode(',', $accept);
1395 foreach($parts as $part) {
1396 // FIXME: doesn't deal with params like 'text/html; level=1'
1397 @list($value, $qpart) = explode(';', $part);
1399 if(!isset($qpart)) {
1401 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1402 $prefs[$value] = $match[1];
1409 function common_mime_type_match($type, $avail)
1411 if(array_key_exists($type, $avail)) {
1414 $parts = explode('/', $type);
1415 if(array_key_exists($parts[0] . '/*', $avail)) {
1416 return $parts[0] . '/*';
1417 } elseif(array_key_exists('*/*', $avail)) {
1425 function common_negotiate_type($cprefs, $sprefs)
1429 foreach(array_keys($sprefs) as $type) {
1430 $parts = explode('/', $type);
1431 if($parts[1] != '*') {
1432 $ckey = common_mime_type_match($type, $cprefs);
1434 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1439 foreach(array_keys($cprefs) as $type) {
1440 $parts = explode('/', $type);
1441 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1442 $skey = common_mime_type_match($type, $sprefs);
1444 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1450 $besttype = "text/html";
1452 foreach(array_keys($combine) as $type) {
1453 if($combine[$type] > $bestq) {
1455 $bestq = $combine[$type];
1462 function common_config($main, $sub)
1465 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1468 function common_copy_args($from)
1471 $strip = get_magic_quotes_gpc();
1472 foreach ($from as $k => $v) {
1473 $to[$k] = ($strip) ? stripslashes($v) : $v;
1478 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1479 // This is used before handing a request off to OAuthRequest::from_request.
1480 function common_remove_magic_from_request()
1482 if(get_magic_quotes_gpc()) {
1483 $_POST=array_map('stripslashes',$_POST);
1484 $_GET=array_map('stripslashes',$_GET);
1488 function common_user_uri(&$user)
1490 return common_local_url('userbyid', array('id' => $user->id));
1493 function common_notice_uri(&$notice)
1495 return common_local_url('shownotice',
1496 array('notice' => $notice->id));
1499 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1501 function common_confirmation_code($bits)
1503 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1504 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1505 $chars = ceil($bits/5);
1507 for ($i = 0; $i < $chars; $i++) {
1508 // XXX: convert to string and back
1509 $num = hexdec(common_good_rand(1));
1510 // XXX: randomness is too precious to throw away almost
1511 // 40% of the bits we get!
1512 $code .= $codechars[$num%32];
1517 // convert markup to HTML
1519 function common_markup_to_html($c)
1521 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1522 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1523 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1524 return Markdown($c);
1527 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
1529 $avatar = $profile->getAvatar($size);
1531 return common_avatar_display_url($avatar);
1533 return common_default_avatar($size);
1537 function common_profile_uri($profile)
1542 $user = User::staticGet($profile->id);
1547 $remote = Remote_profile::staticGet($profile->id);
1549 return $remote->uri;
1551 // XXX: this is a very bad profile!
1555 function common_canonical_sms($sms)
1558 preg_replace('/\D/', '', $sms);
1562 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1566 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1570 case E_USER_WARNING:
1571 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1575 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1579 // FIXME: show error page if we're on the Web
1580 /* Don't execute PHP internal error handler */
1584 function common_session_token()
1586 common_ensure_session();
1587 if (!array_key_exists('token', $_SESSION)) {
1588 $_SESSION['token'] = common_good_rand(64);
1590 return $_SESSION['token'];
1593 function common_cache_key($extra)
1595 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1598 function common_keyize($str)
1600 $str = strtolower($str);
1601 $str = preg_replace('/\s/', '_', $str);
1605 function common_memcache()
1607 static $cache = null;
1608 if (!common_config('memcached', 'enabled')) {
1612 $cache = new Memcache();
1613 $servers = common_config('memcached', 'server');
1614 if (is_array($servers)) {
1615 foreach($servers as $server) {
1616 $cache->addServer($server);
1619 $cache->addServer($servers);
1626 function common_compatible_license($from, $to)
1628 // XXX: better compatibility check needed here!
1629 return ($from == $to);