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);
430 function common_render_text($text)
432 $r = htmlspecialchars($text);
434 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
435 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
436 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
441 function common_render_uri_thingy($matches)
446 // Some heuristics for extracting URIs from surrounding punctuation
447 // Strip from trailing text...
448 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
450 $trailer = $matches[2];
454 ']' => '[', // technically disallowed in URIs, but used in Java docs
455 ')' => '(', // far too frequent in Wikipedia and MSDN
457 $final = substr($uri, -1, 1);
458 if (isset($pairs[$final])) {
459 $openers = substr_count($uri, $pairs[$final]);
460 $closers = substr_count($uri, $final);
461 if ($closers > $openers) {
462 // Assume the paren was opened outside the URI
463 $uri = substr($uri, 0, -1);
464 $trailer = $final . $trailer;
467 if ($longurl = common_longurl($uri)) {
468 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
469 $title = " title='$longurl'";
473 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
476 function common_longurl($short_url)
478 $long_url = common_shorten_link($short_url, true);
479 if ($long_url === $short_url) return false;
483 function common_longurl2($uri)
485 $uri_e = urlencode($uri);
486 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
487 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
488 return stripslashes($longurl['long_url']);
491 function common_shorten_links($text)
493 if (mb_strlen($text) <= 140) return $text;
494 static $cache = array();
495 if (isset($cache[$text])) return $cache[$text];
496 // \s = not a horizontal whitespace character (since PHP 5.2.4)
497 return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
500 function common_shorten_link($url, $reverse = false)
502 static $url_cache = array();
503 if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
505 $user = common_current_user();
507 $curlh = curl_init();
508 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
509 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
510 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
512 switch($user->urlshorteningservice) {
514 $short_url_service = new LilUrl;
515 $short_url = $short_url_service->shorten($url);
519 $short_url_service = new TightUrl;
520 $short_url = $short_url_service->shorten($url);
524 $short_url_service = new PtitUrl;
525 $short_url = $short_url_service->shorten($url);
529 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
530 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
534 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
535 $short_url = curl_exec($curlh);
538 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
539 $short_url = curl_exec($curlh);
542 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
543 $short_url = curl_exec($curlh);
546 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
547 $short_url = curl_exec($curlh);
556 $url_cache[(string)$short_url] = $url;
557 return (string)$short_url;
562 function common_xml_safe_str($str)
564 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
566 // Replace control, formatting, and surrogate characters with '*', ala Twitter
567 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
570 function common_tag_link($tag)
572 $canonical = common_canonical_tag($tag);
573 $url = common_local_url('tag', array('tag' => $canonical));
574 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
577 function common_canonical_tag($tag)
579 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
582 function common_valid_profile_tag($str)
584 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
587 function common_at_link($sender_id, $nickname)
589 $sender = Profile::staticGet($sender_id);
590 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
592 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
598 function common_at_hash_link($sender_id, $tag)
600 $user = User::staticGet($sender_id);
604 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
606 $url = common_local_url('subscriptions',
607 array('nickname' => $user->nickname,
609 return '<a href="'.htmlspecialchars($url).'" class="atlink">'.$tag.'</a>';
615 function common_relative_profile($sender, $nickname, $dt=null)
617 // Try to find profiles this profile is subscribed to that have this nickname
618 $recipient = new Profile();
619 // XXX: use a join instead of a subquery
620 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
621 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
622 if ($recipient->find(true)) {
623 // XXX: should probably differentiate between profiles with
624 // the same name by date of most recent update
627 // Try to find profiles that listen to this profile and that have this nickname
628 $recipient = new Profile();
629 // XXX: use a join instead of a subquery
630 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
631 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
632 if ($recipient->find(true)) {
633 // XXX: should probably differentiate between profiles with
634 // the same name by date of most recent update
637 // If this is a local user, try to find a local user with that nickname.
638 $sender = User::staticGet($sender->id);
640 $recipient_user = User::staticGet('nickname', $nickname);
641 if ($recipient_user) {
642 return $recipient_user->getProfile();
645 // Otherwise, no links. @messages from local users to remote users,
646 // or from remote users to other remote users, are just
647 // outside our ability to make intelligent guesses about
651 // where should the avatar go for this user?
653 function common_avatar_filename($id, $extension, $size=null, $extra=null)
658 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
660 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
664 function common_avatar_path($filename)
667 return INSTALLDIR . '/avatar/' . $filename;
670 function common_avatar_url($filename)
672 return common_path('avatar/'.$filename);
675 function common_avatar_display_url($avatar)
677 $server = common_config('avatar', 'server');
679 return 'http://'.$server.'/'.$avatar->filename;
685 function common_default_avatar($size)
687 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
688 AVATAR_STREAM_SIZE => 'stream',
689 AVATAR_MINI_SIZE => 'mini');
690 return theme_path('default-avatar-'.$sizenames[$size].'.png');
693 function common_local_url($action, $args=null, $fragment=null)
696 if (common_config('site','fancy')) {
697 $url = common_fancy_url($action, $args);
699 $url = common_simple_url($action, $args);
701 if (!is_null($fragment)) {
702 $url .= '#'.$fragment;
707 function common_fancy_url($action, $args=null)
709 switch (strtolower($action)) {
711 if ($args && isset($args['page'])) {
712 return common_path('?page=' . $args['page']);
714 return common_path('');
717 if ($args && isset($args['page'])) {
718 return common_path('featured?page=' . $args['page']);
720 return common_path('featured');
723 if ($args && isset($args['page'])) {
724 return common_path('favorited?page=' . $args['page']);
726 return common_path('favorited');
729 return common_path('rss');
731 return common_path("api/statuses/public_timeline.atom");
733 return common_path('xrds');
735 return common_path('featuredrss');
737 return common_path('favoritedrss');
739 if ($args && $args['type']) {
740 return common_path('opensearch/'.$args['type']);
742 return common_path('opensearch/people');
745 return common_path('doc/'.$args['title']);
752 return common_path('main/'.$action);
754 return common_path('main/tagother?id='.$args['id']);
756 if ($args && $args['code']) {
757 return common_path('main/register/'.$args['code']);
759 return common_path('main/register');
761 case 'remotesubscribe':
762 if ($args && $args['nickname']) {
763 return common_path('main/remote?nickname=' . $args['nickname']);
765 return common_path('main/remote');
768 return common_path($args['nickname'].'/nudge');
770 return common_path('main/openid');
771 case 'profilesettings':
772 return common_path('settings/profile');
773 case 'emailsettings':
774 return common_path('settings/email');
775 case 'openidsettings':
776 return common_path('settings/openid');
778 return common_path('settings/sms');
779 case 'twittersettings':
780 return common_path('settings/twitter');
781 case 'othersettings':
782 return common_path('settings/other');
783 case 'deleteprofile':
784 return common_path('settings/delete');
786 if ($args && $args['replyto']) {
787 return common_path('notice/new?replyto='.$args['replyto']);
789 return common_path('notice/new');
792 return common_path('notice/'.$args['notice']);
794 if ($args && $args['notice']) {
795 return common_path('notice/delete/'.$args['notice']);
797 return common_path('notice/delete');
802 return common_path($args['nickname'].'/'.$action);
807 if ($args && isset($args['page'])) {
808 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
810 return common_path($args['nickname'].'/'.$action);
812 case 'subscriptions':
814 $nickname = $args['nickname'];
815 unset($args['nickname']);
816 if (isset($args['tag'])) {
820 $params = http_build_query($args);
822 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
824 return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
827 return common_path($args['nickname'].'/all/rss');
829 return common_path($args['nickname'].'/replies/rss');
831 if (isset($args['limit']))
832 return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
833 return common_path($args['nickname'].'/rss');
835 if ($args && isset($args['page'])) {
836 return common_path($args['nickname'].'?page=' . $args['page']);
838 return common_path($args['nickname']);
842 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
843 case 'confirmaddress':
844 return common_path('main/confirmaddress/'.$args['code']);
846 return common_path('user/'.$args['id']);
847 case 'recoverpassword':
848 $path = 'main/recoverpassword';
850 $path .= '/' . $args['code'];
852 return common_path($path);
854 return common_path('settings/im');
856 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
858 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
859 case 'noticesearchrss':
860 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
861 case 'avatarbynickname':
862 return common_path($args['nickname'].'/avatar/'.$args['size']);
864 if (isset($args['tag']) && $args['tag']) {
865 $path = 'tag/' . $args['tag'];
870 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
872 $path = 'peopletag/' . $args['tag'];
874 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
876 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
878 return common_path('main/favor');
880 return common_path('main/disfavor');
881 case 'showfavorites':
882 if ($args && isset($args['page'])) {
883 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
885 return common_path($args['nickname'].'/favorites');
888 return common_path($args['nickname'].'/favorites/rss');
890 return common_path('message/' . $args['message']);
892 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
894 // XXX: do fancy URLs for all the API methods
895 switch (strtolower($args['apiaction'])) {
897 switch (strtolower($args['method'])) {
898 case 'user_timeline.rss':
899 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
900 case 'user_timeline.atom':
901 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
902 case 'user_timeline.json':
903 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
904 case 'user_timeline.xml':
905 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
906 default: return common_simple_url($action, $args);
908 default: return common_simple_url($action, $args);
911 if ($args && isset($args['seconds'])) {
912 return common_path('main/sup?seconds='.$args['seconds']);
914 return common_path('main/sup');
917 return common_simple_url($action, $args);
921 function common_simple_url($action, $args=null)
924 /* XXX: pretty URLs */
927 foreach ($args as $key => $value) {
928 $extra .= "&${key}=${value}";
931 return common_path("index.php?action=${action}${extra}");
934 function common_path($relative)
937 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
938 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
941 function common_date_string($dt)
943 // XXX: do some sexy date formatting
944 // return date(DATE_RFC822, $dt);
949 if ($now < $t) { // that shouldn't happen!
950 return common_exact_date($dt);
951 } else if ($diff < 60) {
952 return _('a few seconds ago');
953 } else if ($diff < 92) {
954 return _('about a minute ago');
955 } else if ($diff < 3300) {
956 return sprintf(_('about %d minutes ago'), round($diff/60));
957 } else if ($diff < 5400) {
958 return _('about an hour ago');
959 } else if ($diff < 22 * 3600) {
960 return sprintf(_('about %d hours ago'), round($diff/3600));
961 } else if ($diff < 37 * 3600) {
962 return _('about a day ago');
963 } else if ($diff < 24 * 24 * 3600) {
964 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
965 } else if ($diff < 46 * 24 * 3600) {
966 return _('about a month ago');
967 } else if ($diff < 330 * 24 * 3600) {
968 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
969 } else if ($diff < 480 * 24 * 3600) {
970 return _('about a year ago');
972 return common_exact_date($dt);
976 function common_exact_date($dt)
982 $_utc = new DateTimeZone('UTC');
983 $_siteTz = new DateTimeZone(common_timezone());
986 $dateStr = date('d F Y H:i:s', strtotime($dt));
987 $d = new DateTime($dateStr, $_utc);
988 $d->setTimezone($_siteTz);
989 return $d->format(DATE_RFC850);
992 function common_date_w3dtf($dt)
994 $dateStr = date('d F Y H:i:s', strtotime($dt));
995 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
996 $d->setTimezone(new DateTimeZone(common_timezone()));
997 return $d->format(DATE_W3C);
1000 function common_date_rfc2822($dt)
1002 $dateStr = date('d F Y H:i:s', strtotime($dt));
1003 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1004 $d->setTimezone(new DateTimeZone(common_timezone()));
1005 return $d->format('r');
1008 function common_date_iso8601($dt)
1010 $dateStr = date('d F Y H:i:s', strtotime($dt));
1011 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1012 $d->setTimezone(new DateTimeZone(common_timezone()));
1013 return $d->format('c');
1016 function common_sql_now()
1018 return strftime('%Y-%m-%d %H:%M:%S', time());
1021 function common_redirect($url, $code=307)
1023 static $status = array(301 => "Moved Permanently",
1026 307 => "Temporary Redirect");
1027 header("Status: ${code} $status[$code]");
1028 header("Location: $url");
1030 common_start_xml('a',
1031 '-//W3C//DTD XHTML 1.0 Strict//EN',
1032 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1033 common_element('a', array('href' => $url), $url);
1038 function common_save_replies($notice)
1040 // Alternative reply format
1042 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1045 // extract all @messages
1046 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1050 if ($cnt || $tname) {
1051 // XXX: is there another way to make an array copy?
1052 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1055 $sender = Profile::staticGet($notice->profile_id);
1059 // store replied only for first @ (what user/notice what the reply directed,
1060 // we assume first @ is it)
1062 for ($i=0; $i<count($names); $i++) {
1063 $nickname = $names[$i];
1064 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1068 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self
1069 $reply_for = $recipient;
1070 $recipient_notice = $reply_for->getCurrentNotice();
1071 if ($recipient_notice) {
1072 $orig = clone($notice);
1073 $notice->reply_to = $recipient_notice->id;
1074 $notice->update($orig);
1077 // Don't save replies from blocked profile to local user
1078 $recipient_user = User::staticGet('id', $recipient->id);
1079 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1082 $reply = new Reply();
1083 $reply->notice_id = $notice->id;
1084 $reply->profile_id = $recipient->id;
1085 $id = $reply->insert();
1087 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1088 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1089 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1092 $replied[$recipient->id] = 1;
1096 // Hash format replies, too
1097 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1099 foreach ($match[1] as $tag) {
1100 $tagged = Profile_tag::getTagged($sender->id, $tag);
1101 foreach ($tagged as $t) {
1102 if (!$replied[$t->id]) {
1103 // Don't save replies from blocked profile to local user
1104 $t_user = User::staticGet('id', $t->id);
1105 if ($t_user && $t_user->hasBlocked($sender)) {
1108 $reply = new Reply();
1109 $reply->notice_id = $notice->id;
1110 $reply->profile_id = $t->id;
1111 $id = $reply->insert();
1113 common_log_db_error($reply, 'INSERT', __FILE__);
1122 function common_broadcast_notice($notice, $remote=false)
1125 // Check to see if notice should go to Twitter
1126 $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1127 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1129 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1131 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1132 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1134 $result = common_twitter_broadcast($notice, $flink);
1137 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1142 if (common_config('queue', 'enabled')) {
1144 return common_enqueue_notice($notice);
1146 return common_real_broadcast($notice, $remote);
1150 function common_twitter_broadcast($notice, $flink)
1154 $fuser = $flink->getForeignUser();
1155 $twitter_user = $fuser->nickname;
1156 $twitter_password = $flink->credentials;
1157 $uri = 'http://www.twitter.com/statuses/update.json';
1159 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1160 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1163 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1164 CURLOPT_POST => true,
1165 CURLOPT_POSTFIELDS => array(
1166 'status' => $statustxt,
1167 'source' => $config['integration']['source']
1169 CURLOPT_RETURNTRANSFER => true,
1170 CURLOPT_FAILONERROR => true,
1171 CURLOPT_HEADER => false,
1172 CURLOPT_FOLLOWLOCATION => true,
1173 CURLOPT_USERAGENT => "Laconica",
1174 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1175 CURLOPT_TIMEOUT => 120,
1177 # Twitter is strict about accepting invalid "Expect" headers
1178 CURLOPT_HTTPHEADER => array('Expect:')
1181 $ch = curl_init($uri);
1182 curl_setopt_array($ch, $options);
1183 $data = curl_exec($ch);
1184 $errmsg = curl_error($ch);
1187 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1195 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1200 // Twitter should return a status
1201 $status = json_decode($data);
1204 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1212 // Stick the notice on the queue
1214 function common_enqueue_notice($notice)
1216 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1217 $qi = new Queue_item();
1218 $qi->notice_id = $notice->id;
1219 $qi->transport = $transport;
1220 $qi->created = $notice->created;
1221 $result = $qi->insert();
1223 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1224 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1227 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1232 function common_dequeue_notice($notice)
1234 $qi = Queue_item::staticGet($notice->id);
1236 $result = $qi->delete();
1238 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1239 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1242 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1249 function common_real_broadcast($notice, $remote=false)
1253 // Make sure we have the OMB stuff
1254 require_once(INSTALLDIR.'/lib/omb.php');
1255 $success = omb_broadcast_remote_subscribers($notice);
1257 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1261 require_once(INSTALLDIR.'/lib/jabber.php');
1262 $success = jabber_broadcast_notice($notice);
1264 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1268 require_once(INSTALLDIR.'/lib/mail.php');
1269 $success = mail_broadcast_notice_sms($notice);
1271 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1275 $success = jabber_public_notice($notice);
1277 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1280 // XXX: broadcast notices to other IM
1284 function common_broadcast_profile($profile)
1286 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1287 require_once(INSTALLDIR.'/lib/omb.php');
1288 omb_broadcast_profile($profile);
1289 // XXX: Other broadcasts...?
1293 function common_profile_url($nickname)
1295 return common_local_url('showstream', array('nickname' => $nickname));
1298 // Don't call if nobody's logged in
1300 function common_notice_form($action=null, $content=null)
1302 $user = common_current_user();
1303 assert(!is_null($user));
1304 common_element_start('form', array('id' => 'status_form',
1306 'action' => common_local_url('newnotice')));
1307 common_element_start('p');
1308 common_element('label', array('for' => 'status_textarea',
1309 'id' => 'status_label'),
1310 sprintf(_('What\'s up, %s?'), $user->nickname));
1311 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1312 common_element('textarea', array('id' => 'status_textarea',
1315 'name' => 'status_textarea'),
1316 ($content) ? $content : '');
1317 common_hidden('token', common_session_token());
1319 common_hidden('returnto', $action);
1321 // set by JavaScript
1322 common_hidden('inreplyto', 'false');
1323 common_element('input', array('id' => 'status_submit',
1324 'name' => 'status_submit',
1326 'value' => _('Send')));
1327 common_element_end('p');
1328 common_element_end('form');
1331 // Should make up a reasonable root URL
1333 function common_root_url()
1335 return common_path('');
1338 // returns $bytes bytes of random data as a hexadecimal string
1339 // "good" here is a goal and not a guarantee
1341 function common_good_rand($bytes)
1343 // XXX: use random.org...?
1344 if (file_exists('/dev/urandom')) {
1345 return common_urandom($bytes);
1346 } else { // FIXME: this is probably not good enough
1347 return common_mtrand($bytes);
1351 function common_urandom($bytes)
1353 $h = fopen('/dev/urandom', 'rb');
1355 $src = fread($h, $bytes);
1358 for ($i = 0; $i < $bytes; $i++) {
1359 $enc .= sprintf("%02x", (ord($src[$i])));
1364 function common_mtrand($bytes)
1367 for ($i = 0; $i < $bytes; $i++) {
1368 $enc .= sprintf("%02x", mt_rand(0, 255));
1373 function common_set_returnto($url)
1375 common_ensure_session();
1376 $_SESSION['returnto'] = $url;
1379 function common_get_returnto()
1381 common_ensure_session();
1382 return $_SESSION['returnto'];
1385 function common_timestamp()
1387 return date('YmdHis');
1390 function common_ensure_syslog()
1392 static $initialized = false;
1393 if (!$initialized) {
1395 openlog($config['syslog']['appname'], 0, LOG_USER);
1396 $initialized = true;
1400 function common_log($priority, $msg, $filename=null)
1402 $logfile = common_config('site', 'logfile');
1404 $log = fopen($logfile, "a");
1406 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1407 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1408 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1409 fwrite($log, $output);
1413 common_ensure_syslog();
1414 syslog($priority, $msg);
1418 function common_debug($msg, $filename=null)
1421 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1423 common_log(LOG_DEBUG, $msg);
1427 function common_log_db_error(&$object, $verb, $filename=null)
1429 $objstr = common_log_objstring($object);
1430 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1431 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1434 function common_log_objstring(&$object)
1436 if (is_null($object)) {
1439 $arr = $object->toArray();
1441 foreach ($arr as $k => $v) {
1442 $fields[] = "$k='$v'";
1444 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1448 function common_valid_http_url($url)
1450 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1453 function common_valid_tag($tag)
1455 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1456 return (Validate::email($matches[1]) ||
1457 preg_match('/^([\w-\.]+)$/', $matches[1]));
1462 // Does a little before-after block for next/prev page
1464 function common_pagination($have_before, $have_after, $page, $action, $args=null)
1467 if ($have_before || $have_after) {
1468 common_element_start('div', array('id' => 'pagination'));
1469 common_element_start('ul', array('id' => 'nav_pagination'));
1473 $pargs = array('page' => $page-1);
1474 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1476 common_element_start('li', 'before');
1477 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
1479 common_element_end('li');
1483 $pargs = array('page' => $page+1);
1484 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1485 common_element_start('li', 'after');
1486 common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
1488 common_element_end('li');
1491 if ($have_before || $have_after) {
1492 common_element_end('ul');
1493 common_element_end('div');
1497 /* Following functions are copied from MediaWiki GlobalFunctions.php
1498 * and written by Evan Prodromou. */
1500 function common_accept_to_prefs($accept, $def = '*/*')
1502 // No arg means accept anything (per HTTP spec)
1504 return array($def => 1);
1509 $parts = explode(',', $accept);
1511 foreach($parts as $part) {
1512 // FIXME: doesn't deal with params like 'text/html; level=1'
1513 @list($value, $qpart) = explode(';', $part);
1515 if(!isset($qpart)) {
1517 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1518 $prefs[$value] = $match[1];
1525 function common_mime_type_match($type, $avail)
1527 if(array_key_exists($type, $avail)) {
1530 $parts = explode('/', $type);
1531 if(array_key_exists($parts[0] . '/*', $avail)) {
1532 return $parts[0] . '/*';
1533 } elseif(array_key_exists('*/*', $avail)) {
1541 function common_negotiate_type($cprefs, $sprefs)
1545 foreach(array_keys($sprefs) as $type) {
1546 $parts = explode('/', $type);
1547 if($parts[1] != '*') {
1548 $ckey = common_mime_type_match($type, $cprefs);
1550 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1555 foreach(array_keys($cprefs) as $type) {
1556 $parts = explode('/', $type);
1557 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1558 $skey = common_mime_type_match($type, $sprefs);
1560 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1566 $besttype = "text/html";
1568 foreach(array_keys($combine) as $type) {
1569 if($combine[$type] > $bestq) {
1571 $bestq = $combine[$type];
1578 function common_config($main, $sub)
1581 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1584 function common_copy_args($from)
1587 $strip = get_magic_quotes_gpc();
1588 foreach ($from as $k => $v) {
1589 $to[$k] = ($strip) ? stripslashes($v) : $v;
1594 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1595 // This is used before handing a request off to OAuthRequest::from_request.
1596 function common_remove_magic_from_request()
1598 if(get_magic_quotes_gpc()) {
1599 $_POST=array_map('stripslashes',$_POST);
1600 $_GET=array_map('stripslashes',$_GET);
1604 function common_user_uri(&$user)
1606 return common_local_url('userbyid', array('id' => $user->id));
1609 function common_notice_uri(&$notice)
1611 return common_local_url('shownotice',
1612 array('notice' => $notice->id));
1615 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1617 function common_confirmation_code($bits)
1619 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1620 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1621 $chars = ceil($bits/5);
1623 for ($i = 0; $i < $chars; $i++) {
1624 // XXX: convert to string and back
1625 $num = hexdec(common_good_rand(1));
1626 // XXX: randomness is too precious to throw away almost
1627 // 40% of the bits we get!
1628 $code .= $codechars[$num%32];
1633 // convert markup to HTML
1635 function common_markup_to_html($c)
1637 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1638 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1639 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1640 return Markdown($c);
1643 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
1645 $avatar = $profile->getAvatar($size);
1647 return common_avatar_display_url($avatar);
1649 return common_default_avatar($size);
1653 function common_profile_uri($profile)
1658 $user = User::staticGet($profile->id);
1663 $remote = Remote_profile::staticGet($profile->id);
1665 return $remote->uri;
1667 // XXX: this is a very bad profile!
1671 function common_canonical_sms($sms)
1674 preg_replace('/\D/', '', $sms);
1678 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1682 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1686 case E_USER_WARNING:
1687 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1691 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1695 // FIXME: show error page if we're on the Web
1696 /* Don't execute PHP internal error handler */
1700 function common_session_token()
1702 common_ensure_session();
1703 if (!array_key_exists('token', $_SESSION)) {
1704 $_SESSION['token'] = common_good_rand(64);
1706 return $_SESSION['token'];
1709 function common_disfavor_form($notice)
1711 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1713 'class' => 'disfavor',
1714 'action' => common_local_url('disfavor')));
1716 common_element('input', array('type' => 'hidden',
1717 'name' => 'token-'. $notice->id,
1718 'id' => 'token-'. $notice->id,
1720 'value' => common_session_token()));
1722 common_element('input', array('type' => 'hidden',
1724 'id' => 'notice-n'. $notice->id,
1725 'class' => 'notice',
1726 'value' => $notice->id));
1728 common_element('input', array('type' => 'submit',
1729 'id' => 'disfavor-submit-' . $notice->id,
1730 'name' => 'disfavor-submit-' . $notice->id,
1731 'class' => 'disfavor',
1732 'value' => 'Disfavor favorite',
1733 'title' => 'Remove this message from favorites'));
1734 common_element_end('form');
1737 function common_favor_form($notice)
1739 common_element_start('form', array('id' => 'favor-' . $notice->id,
1742 'action' => common_local_url('favor')));
1744 common_element('input', array('type' => 'hidden',
1745 'name' => 'token-'. $notice->id,
1746 'id' => 'token-'. $notice->id,
1748 'value' => common_session_token()));
1750 common_element('input', array('type' => 'hidden',
1752 'id' => 'notice-n'. $notice->id,
1753 'class' => 'notice',
1754 'value' => $notice->id));
1756 common_element('input', array('type' => 'submit',
1757 'id' => 'favor-submit-' . $notice->id,
1758 'name' => 'favor-submit-' . $notice->id,
1760 'value' => 'Add to favorites',
1761 'title' => 'Add this message to favorites'));
1762 common_element_end('form');
1765 function common_nudge_form($profile)
1767 common_element_start('form', array('id' => 'nudge', 'method' => 'post',
1768 'action' => common_local_url('nudge', array('nickname' => $profile->nickname))));
1769 common_hidden('token', common_session_token());
1770 common_element('input', array('type' => 'submit',
1771 'class' => 'submit',
1772 'value' => _('Send a nudge')));
1773 common_element_end('form');
1775 function common_nudge_response()
1777 common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
1780 function common_subscribe_form($profile)
1782 common_element_start('form', array('id' => 'subscribe-' . $profile->id,
1784 'class' => 'subscribe',
1785 'action' => common_local_url('subscribe')));
1786 common_hidden('token', common_session_token());
1787 common_element('input', array('id' => 'subscribeto-' . $profile->id,
1788 'name' => 'subscribeto',
1790 'value' => $profile->id));
1791 common_element('input', array('type' => 'submit',
1792 'class' => 'submit',
1793 'value' => _('Subscribe')));
1794 common_element_end('form');
1797 function common_unsubscribe_form($profile)
1799 common_element_start('form', array('id' => 'unsubscribe-' . $profile->id,
1801 'class' => 'unsubscribe',
1802 'action' => common_local_url('unsubscribe')));
1803 common_hidden('token', common_session_token());
1804 common_element('input', array('id' => 'unsubscribeto-' . $profile->id,
1805 'name' => 'unsubscribeto',
1807 'value' => $profile->id));
1808 common_element('input', array('type' => 'submit',
1809 'class' => 'submit',
1810 'value' => _('Unsubscribe')));
1811 common_element_end('form');
1814 // XXX: Refactor this code
1815 function common_profile_new_message_nudge ($cur, $profile)
1817 $user = User::staticGet('id', $profile->id);
1819 if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) {
1820 common_element_start('li', array('id' => 'profile_send_a_new_message'));
1821 common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))),
1822 _('Send a message'));
1823 common_element_end('li');
1825 if ($user->email && $user->emailnotifynudge) {
1826 common_element_start('li', array('id' => 'profile_nudge'));
1827 common_nudge_form($user);
1828 common_element_end('li');
1833 function common_cache_key($extra)
1835 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1838 function common_keyize($str)
1840 $str = strtolower($str);
1841 $str = preg_replace('/\s/', '_', $str);
1845 function common_message_form($content, $user, $to)
1848 common_element_start('form', array('id' => 'message_form',
1850 'action' => common_local_url('newmessage')));
1852 $mutual_users = $user->mutuallySubscribedUsers();
1856 while ($mutual_users->fetch()) {
1857 if ($mutual_users->id != $user->id) {
1858 $mutual[$mutual_users->id] = $mutual_users->nickname;
1862 $mutual_users->free();
1863 unset($mutual_users);
1865 common_dropdown('to', _('To'), $mutual, null, false, $to->id);
1867 common_element_start('p');
1869 common_element('textarea', array('id' => 'message_content',
1872 'name' => 'content'),
1873 ($content) ? $content : '');
1875 common_element('input', array('id' => 'message_send',
1876 'name' => 'message_send',
1878 'value' => _('Send')));
1880 common_hidden('token', common_session_token());
1882 common_element_end('p');
1883 common_element_end('form');
1886 function common_memcache()
1888 static $cache = null;
1889 if (!common_config('memcached', 'enabled')) {
1893 $cache = new Memcache();
1894 $servers = common_config('memcached', 'server');
1895 if (is_array($servers)) {
1896 foreach($servers as $server) {
1897 $cache->addServer($server);
1900 $cache->addServer($servers);
1907 function common_compatible_license($from, $to)
1909 // XXX: better compatibility check needed here!
1910 return ($from == $to);
1913 /* These are almost identical, so we use a helper function */
1915 function common_block_form($profile, $args=null)
1917 common_blocking_form('block', _('Block'), $profile, $args);
1920 function common_unblock_form($profile, $args=null)
1922 common_blocking_form('unblock', _('Unblock'), $profile, $args);
1925 function common_blocking_form($type, $label, $profile, $args=null)
1927 common_element_start('form', array('id' => $type . '-' . $profile->id,
1930 'action' => common_local_url($type)));
1931 common_hidden('token', common_session_token());
1932 common_element('input', array('id' => $type . 'to-' . $profile->id,
1933 'name' => $type . 'to',
1935 'value' => $profile->id));
1936 common_element('input', array('type' => 'submit',
1937 'class' => 'submit',
1939 'value' => $label));
1941 foreach ($args as $k => $v) {
1942 common_hidden('returnto-' . $k, $v);
1945 common_element_end('form');