3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, 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) */
23 * Show a server error.
25 function common_server_error($msg, $code=500)
27 $err = new ServerErrorAction($msg, $code);
34 function common_user_error($msg, $code=400)
36 $err = new ClientErrorAction($msg, $code);
41 * This should only be used at setup; processes switching languages
42 * to send text to other users should use common_switch_locale().
44 * @param string $language Locale language code (optional; empty uses
45 * current user's preference or site default)
46 * @return mixed success
48 function common_init_locale($language=null)
51 $language = common_language();
53 putenv('LANGUAGE='.$language);
54 putenv('LANG='.$language);
55 $ok = setlocale(LC_ALL, $language . ".utf8",
65 * Initialize locale and charset settings and gettext with our message catalog,
66 * using the current user's language preference or the site default.
68 * This should generally only be run at framework initialization; code switching
69 * languages at runtime should call common_switch_language().
73 function common_init_language()
75 mb_internal_encoding('UTF-8');
77 // Note that this setlocale() call may "fail" but this is harmless;
78 // gettext will still select the right language.
79 $language = common_language();
80 $locale_set = common_init_locale($language);
83 // The requested locale doesn't exist on the system.
85 // gettext seems very picky... We first need to setlocale()
86 // to a locale which _does_ exist on the system, and _then_
87 // we can set in another locale that may not be set up
88 // (say, ga_ES for Galego/Galician) it seems to take it.
90 // For some reason C and POSIX which are guaranteed to work
91 // don't do the job. en_US.UTF-8 should be there most of the
92 // time, but not guaranteed.
93 $ok = common_init_locale("en_US");
94 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95 // Try to find a complete, working locale on Unix/Linux...
96 // @fixme shelling out feels awfully inefficient
97 // but I don't think there's a more standard way.
99 foreach (explode("\n", $all) as $locale) {
100 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101 $ok = setlocale(LC_ALL, $locale);
109 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
111 $locale_set = common_init_locale($language);
114 common_init_gettext();
120 function common_init_gettext()
122 setlocale(LC_CTYPE, 'C');
123 // So we do not have to make people install the gettext locales
124 $path = common_config('site','locale_path');
125 bindtextdomain("statusnet", $path);
126 bind_textdomain_codeset("statusnet", "UTF-8");
127 textdomain("statusnet");
131 * Switch locale during runtime, and poke gettext until it cries uncle.
132 * Otherwise, sometimes it doesn't actually switch away from the old language.
134 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
136 function common_switch_locale($language=null)
138 common_init_locale($language);
140 setlocale(LC_CTYPE, 'C');
141 // So we do not have to make people install the gettext locales
142 $path = common_config('site','locale_path');
143 bindtextdomain("statusnet", $path);
144 bind_textdomain_codeset("statusnet", "UTF-8");
145 textdomain("statusnet");
149 function common_timezone()
151 if (common_logged_in()) {
152 $user = common_current_user();
153 if ($user->timezone) {
154 return $user->timezone;
158 return common_config('site', 'timezone');
161 function common_language()
163 // If there is a user logged in and they've set a language preference
164 // then return that one...
165 if (_have_config() && common_logged_in()) {
166 $user = common_current_user();
167 $user_language = $user->language;
169 if ($user->language) {
170 // Validate -- we don't want to end up with a bogus code
171 // left over from some old junk.
172 foreach (common_config('site', 'languages') as $code => $info) {
173 if ($info['lang'] == $user_language) {
174 return $user_language;
180 // Otherwise, find the best match for the languages requested by the
182 if (common_config('site', 'langdetect')) {
183 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
184 if (!empty($httplang)) {
185 $language = client_prefered_language($httplang);
191 // Finally, if none of the above worked, use the site's default...
192 return common_config('site', 'language');
196 * Salted, hashed passwords are stored in the DB.
198 function common_munge_password($password, $id)
200 if (is_object($id) || is_object($password)) {
201 $e = new Exception();
202 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
203 str_replace("\n", " ", $e->getTraceAsString()));
205 return md5($password . $id);
209 * Check if a username exists and has matching password.
211 function common_check_user($nickname, $password)
213 // empty nickname always unacceptable
214 if (empty($nickname)) {
218 $authenticatedUser = false;
220 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
221 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
223 if (!empty($password)) { // never allow login with blank password
224 if (0 == strcmp(common_munge_password($password, $user->id),
226 //internal checking passed
227 $authenticatedUser = $user;
231 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
234 return $authenticatedUser;
238 * Is the current user logged in?
240 function common_logged_in()
242 return (!is_null(common_current_user()));
245 function common_have_session()
247 return (0 != strcmp(session_id(), ''));
250 function common_ensure_session()
253 if (array_key_exists(session_name(), $_COOKIE)) {
254 $c = $_COOKIE[session_name()];
256 if (!common_have_session()) {
257 if (common_config('sessions', 'handle')) {
258 Session::setSaveHandler();
260 if (array_key_exists(session_name(), $_GET)) {
261 $id = $_GET[session_name()];
262 } else if (array_key_exists(session_name(), $_COOKIE)) {
263 $id = $_COOKIE[session_name()];
269 if (!isset($_SESSION['started'])) {
270 $_SESSION['started'] = time();
272 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
273 ' is set but started value is null');
279 // Three kinds of arguments:
284 // Initialize to false; set to null if none found
287 function common_set_user($user)
291 if (is_null($user) && common_have_session()) {
293 unset($_SESSION['userid']);
295 } else if (is_string($user)) {
297 $user = User::staticGet('nickname', $nickname);
298 } else if (!($user instanceof User)) {
303 if (Event::handle('StartSetUser', array(&$user))) {
305 common_ensure_session();
306 $_SESSION['userid'] = $user->id;
308 Event::handle('EndSetUser', array($user));
316 function common_set_cookie($key, $value, $expiration=0)
318 $path = common_config('site', 'path');
319 $server = common_config('site', 'server');
321 if ($path && ($path != '/')) {
322 $cookiepath = '/' . $path . '/';
326 return setcookie($key,
333 define('REMEMBERME', 'rememberme');
334 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
336 function common_rememberme($user=null)
339 $user = common_current_user();
345 $rm = new Remember_me();
347 $rm->code = common_good_rand(16);
348 $rm->user_id = $user->id;
350 // Wrap the insert in some good ol' fashioned transaction code
354 $result = $rm->insert();
357 common_log_db_error($rm, 'INSERT', __FILE__);
361 $rm->query('COMMIT');
363 $cookieval = $rm->user_id . ':' . $rm->code;
365 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
367 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
372 function common_remembered_user()
376 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
382 list($id, $code) = explode(':', $packed);
384 if (!$id || !$code) {
385 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
390 $rm = Remember_me::staticGet($code);
393 common_log(LOG_WARNING, 'No such remember code: ' . $code);
398 if ($rm->user_id != $id) {
399 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
404 $user = User::staticGet($rm->user_id);
407 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
413 $result = $rm->delete();
416 common_log_db_error($rm, 'DELETE', __FILE__);
417 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
422 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
424 common_set_user($user);
425 common_real_login(false);
427 // We issue a new cookie, so they can log in
428 // automatically again after this session
430 common_rememberme($user);
436 * must be called with a valid user!
438 function common_forgetme()
440 common_set_cookie(REMEMBERME, '', 0);
444 * Who is the current user?
446 function common_current_user()
450 if (!_have_config()) {
454 if ($_cur === false) {
456 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
457 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
458 common_ensure_session();
459 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
461 $user = User::staticGet($id);
469 // that didn't work; try to remember; will init $_cur to null on failure
470 $_cur = common_remembered_user();
473 // XXX: Is this necessary?
474 $_SESSION['userid'] = $_cur->id;
482 * Logins that are 'remembered' aren't 'real' -- they're subject to
483 * cookie-stealing. So, we don't let them do certain things. New reg,
484 * OpenID, and password logins _are_ real.
486 function common_real_login($real=true)
488 common_ensure_session();
489 $_SESSION['real_login'] = $real;
492 function common_is_real_login()
494 return common_logged_in() && $_SESSION['real_login'];
498 * Get a hash portion for HTTP caching Etags and such including
499 * info on the current user's session. If login/logout state changes,
500 * or we've changed accounts, or we've renamed the current user,
501 * we'll get a new hash value.
503 * This should not be considered secure information.
505 * @param User $user (optional; uses common_current_user() if left out)
508 function common_user_cache_hash($user=false)
510 if ($user === false) {
511 $user = common_current_user();
514 return crc32($user->id . ':' . $user->nickname);
520 // get canonical version of nickname for comparison
521 function common_canonical_nickname($nickname)
523 // XXX: UTF-8 canonicalization (like combining chars)
524 return strtolower($nickname);
527 // get canonical version of email for comparison
528 function common_canonical_email($email)
530 // XXX: canonicalize UTF-8
531 // XXX: lcase the domain part
535 function common_render_content($text, $notice)
537 $r = common_render_text($text);
538 $id = $notice->profile_id;
539 $r = common_linkify_mentions($r, $notice);
540 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
544 function common_linkify_mentions($text, $notice)
546 $mentions = common_find_mentions($text, $notice);
548 // We need to go through in reverse order by position,
549 // so our positions stay valid despite our fudging with the
554 foreach ($mentions as $mention)
556 $points[$mention['position']] = $mention;
561 foreach ($points as $position => $mention) {
563 $linkText = common_linkify_mention($mention);
565 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
571 function common_linkify_mention($mention)
575 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
577 $xs = new XMLStringer(false);
579 $attrs = array('href' => $mention['url'],
582 if (!empty($mention['title'])) {
583 $attrs['title'] = $mention['title'];
586 $xs->elementStart('span', 'vcard');
587 $xs->elementStart('a', $attrs);
588 $xs->element('span', 'fn nickname', $mention['text']);
589 $xs->elementEnd('a');
590 $xs->elementEnd('span');
592 $output = $xs->getString();
594 Event::handle('EndLinkifyMention', array($mention, &$output));
600 function common_find_mentions($text, $notice)
604 $sender = Profile::staticGet('id', $notice->profile_id);
606 if (empty($sender)) {
610 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
611 // Get the context of the original notice, if any
612 $originalAuthor = null;
613 $originalNotice = null;
614 $originalMentions = array();
618 if (!empty($notice) && !empty($notice->reply_to)) {
619 $originalNotice = Notice::staticGet('id', $notice->reply_to);
620 if (!empty($originalNotice)) {
621 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
623 $ids = $originalNotice->getReplies();
625 foreach ($ids as $id) {
626 $repliedTo = Profile::staticGet('id', $id);
627 if (!empty($repliedTo)) {
628 $originalMentions[$repliedTo->nickname] = $repliedTo;
634 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
637 PREG_OFFSET_CAPTURE);
639 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
642 PREG_OFFSET_CAPTURE);
644 $matches = array_merge($tmatches[1], $atmatches[1]);
646 foreach ($matches as $match) {
647 $nickname = common_canonical_nickname($match[0]);
649 // Try to get a profile for this nickname.
650 // Start with conversation context, then go to
653 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
654 $mentioned = $originalAuthor;
655 } else if (!empty($originalMentions) &&
656 array_key_exists($nickname, $originalMentions)) {
657 $mentioned = $originalMentions[$nickname];
659 $mentioned = common_relative_profile($sender, $nickname);
662 if (!empty($mentioned)) {
663 $user = User::staticGet('id', $mentioned->id);
666 $url = common_local_url('userbyid', array('id' => $user->id));
668 $url = $mentioned->profileurl;
671 $mention = array('mentioned' => array($mentioned),
673 'position' => $match[1],
676 if (!empty($mentioned->fullname)) {
677 $mention['title'] = $mentioned->fullname;
680 $mentions[] = $mention;
684 // @#tag => mention of all subscriptions tagged 'tag'
686 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
689 PREG_OFFSET_CAPTURE);
691 foreach ($hmatches[1] as $hmatch) {
693 $tag = common_canonical_tag($hmatch[0]);
695 $tagged = Profile_tag::getTagged($sender->id, $tag);
697 $url = common_local_url('subscriptions',
698 array('nickname' => $sender->nickname,
701 $mentions[] = array('mentioned' => $tagged,
702 'text' => $hmatch[0],
703 'position' => $hmatch[1],
707 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
713 function common_render_text($text)
715 $r = htmlspecialchars($text);
717 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
718 $r = common_replace_urls_callback($r, 'common_linkify');
719 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
724 function common_replace_urls_callback($text, $callback, $notice_id = null) {
725 // Start off with a regex
727 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
730 '(?:'. //Known protocols
732 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
734 '(?:(?:mailto|aim|tel|xmpp):)'.
736 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
739 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
741 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
745 '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'. //IPv4
747 '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)'.
749 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
750 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
751 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
752 '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZW|local|loc|onion)'.
756 '(?:\:\d+)?'. //:port
757 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
758 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
759 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
760 ')(?<![\?\.\,\#\,])'.
763 //preg_match_all($regex,$text,$matches);
765 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
768 function callback_helper($matches, $callback, $notice_id) {
770 $left = strpos($matches[0],$url);
771 $right = $left+strlen($url);
773 $groupSymbolSets=array(
791 $cannotEndWith=array('.','?',',','#');
795 foreach($groupSymbolSets as $groupSymbolSet){
796 if(substr($url,-1)==$groupSymbolSet['right']){
797 $group_left_count = substr_count($url,$groupSymbolSet['left']);
798 $group_right_count = substr_count($url,$groupSymbolSet['right']);
799 if($group_left_count<$group_right_count){
801 $url=substr($url,0,-1);
805 if(in_array(substr($url,-1),$cannotEndWith)){
807 $url=substr($url,0,-1);
809 }while($original_url!=$url);
811 if(empty($notice_id)){
812 $result = call_user_func_array($callback, array($url));
814 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
816 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
819 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
820 // lambda implementation in a separate file; PHP 5.2 won't parse it.
821 require_once INSTALLDIR . "/lib/curry.php";
823 function curry($fn) {
824 $args = func_get_args();
826 $id = uniqid('_partial');
827 $GLOBALS[$id] = array($fn, $args);
828 return create_function('',
829 '$args = func_get_args(); '.
830 'return call_user_func_array('.
831 '$GLOBALS["'.$id.'"][0],'.
834 '$GLOBALS["'.$id.'"][1]));');
838 function common_linkify($url) {
839 // It comes in special'd, so we unspecial it before passing to the stringifying
841 $url = htmlspecialchars_decode($url);
843 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
844 //url is an email address without the mailto: protocol
845 $canon = "mailto:$url";
846 $longurl = "mailto:$url";
849 $canon = File_redirection::_canonUrl($url);
851 $longurl_data = File_redirection::where($canon);
852 if (is_array($longurl_data)) {
853 $longurl = $longurl_data['url'];
854 } elseif (is_string($longurl_data)) {
855 $longurl = $longurl_data;
857 // Unable to reach the server to verify contents, etc
858 // Just pass the link on through for now.
859 common_log(LOG_ERR, "Can't linkify url '$url'");
863 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
865 $is_attachment = false;
866 $attachment_id = null;
869 // Check to see whether this is a known "attachment" URL.
871 $f = File::staticGet('url', $longurl);
874 // XXX: this writes to the database. :<
875 $f = File::processNew($longurl);
879 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
880 $is_attachment = true;
881 $attachment_id = $f->id;
883 $thumb = File_thumbnail::staticGet('file_id', $f->id);
884 if (!empty($thumb)) {
891 if ($is_attachment) {
892 $attrs['class'] = 'attachment';
894 $attrs['class'] = 'attachment thumbnail';
896 $attrs['id'] = "attachment-{$attachment_id}";
899 return XMLStringer::estring('a', $attrs, $url);
902 function common_shorten_links($text, $always = false)
904 $maxLength = Notice::maxContent();
905 if (!$always && ($maxLength == 0 || mb_strlen($text) <= $maxLength)) return $text;
906 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
909 function common_xml_safe_str($str)
911 // Replace common eol and extra whitespace input chars
916 "\0", // null byte eos
917 "\x0B" // vertical tab
920 $replacement = array(
928 $str = str_replace($unWelcome, $replacement, $str);
930 // Neutralize any additional control codes and UTF-16 surrogates
931 // (Twitter uses '*')
932 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
935 function common_tag_link($tag)
937 $canonical = common_canonical_tag($tag);
938 if (common_config('singleuser', 'enabled')) {
939 // regular TagAction isn't set up in 1user mode
940 $url = common_local_url('showstream',
941 array('nickname' => common_config('singleuser', 'nickname'),
942 'tag' => $canonical));
944 $url = common_local_url('tag', array('tag' => $canonical));
946 $xs = new XMLStringer();
947 $xs->elementStart('span', 'tag');
948 $xs->element('a', array('href' => $url,
951 $xs->elementEnd('span');
952 return $xs->getString();
955 function common_canonical_tag($tag)
957 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
958 return str_replace(array('-', '_', '.'), '', $tag);
961 function common_valid_profile_tag($str)
963 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
966 function common_group_link($sender_id, $nickname)
968 $sender = Profile::staticGet($sender_id);
969 $group = User_group::getForNickname($nickname, $sender);
970 if ($sender && $group && $sender->isMember($group)) {
971 $attrs = array('href' => $group->permalink(),
973 if (!empty($group->fullname)) {
974 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
976 $xs = new XMLStringer();
977 $xs->elementStart('span', 'vcard');
978 $xs->elementStart('a', $attrs);
979 $xs->element('span', 'fn nickname', $nickname);
980 $xs->elementEnd('a');
981 $xs->elementEnd('span');
982 return $xs->getString();
988 function common_relative_profile($sender, $nickname, $dt=null)
990 // Try to find profiles this profile is subscribed to that have this nickname
991 $recipient = new Profile();
992 // XXX: use a join instead of a subquery
993 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
994 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
995 if ($recipient->find(true)) {
996 // XXX: should probably differentiate between profiles with
997 // the same name by date of most recent update
1000 // Try to find profiles that listen to this profile and that have this nickname
1001 $recipient = new Profile();
1002 // XXX: use a join instead of a subquery
1003 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1004 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1005 if ($recipient->find(true)) {
1006 // XXX: should probably differentiate between profiles with
1007 // the same name by date of most recent update
1010 // If this is a local user, try to find a local user with that nickname.
1011 $sender = User::staticGet($sender->id);
1013 $recipient_user = User::staticGet('nickname', $nickname);
1014 if ($recipient_user) {
1015 return $recipient_user->getProfile();
1018 // Otherwise, no links. @messages from local users to remote users,
1019 // or from remote users to other remote users, are just
1020 // outside our ability to make intelligent guesses about
1024 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1027 $path = $r->build($action, $args, $params, $fragment);
1029 $ssl = common_is_sensitive($action);
1031 if (common_config('site','fancy')) {
1032 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1034 if (mb_strpos($path, '/index.php') === 0) {
1035 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1037 $url = common_path('index.php'.$path, $ssl, $addSession);
1043 function common_is_sensitive($action)
1045 static $sensitive = array('login', 'register', 'passwordsettings', 'api');
1048 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1049 $ssl = in_array($action, $sensitive);
1055 function common_path($relative, $ssl=false, $addSession=true)
1057 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1059 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1060 || common_config('site', 'ssl') === 'always') {
1062 if (is_string(common_config('site', 'sslserver')) &&
1063 mb_strlen(common_config('site', 'sslserver')) > 0) {
1064 $serverpart = common_config('site', 'sslserver');
1065 } else if (common_config('site', 'server')) {
1066 $serverpart = common_config('site', 'server');
1068 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1072 if (common_config('site', 'server')) {
1073 $serverpart = common_config('site', 'server');
1075 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1080 $relative = common_inject_session($relative, $serverpart);
1083 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1086 function common_inject_session($url, $serverpart = null)
1088 if (common_have_session()) {
1090 if (empty($serverpart)) {
1091 $serverpart = parse_url($url, PHP_URL_HOST);
1094 $currentServer = $_SERVER['HTTP_HOST'];
1096 // Are we pointing to another server (like an SSL server?)
1098 if (!empty($currentServer) &&
1099 0 != strcasecmp($currentServer, $serverpart)) {
1100 // Pass the session ID as a GET parameter
1101 $sesspart = session_name() . '=' . session_id();
1102 $i = strpos($url, '?');
1103 if ($i === false) { // no GET params, just append
1104 $url .= '?' . $sesspart;
1106 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1114 function common_date_string($dt)
1116 // XXX: do some sexy date formatting
1117 // return date(DATE_RFC822, $dt);
1118 $t = strtotime($dt);
1122 if ($now < $t) { // that shouldn't happen!
1123 return common_exact_date($dt);
1124 } else if ($diff < 60) {
1125 // TRANS: Used in notices to indicate when the notice was made compared to now.
1126 return _('a few seconds ago');
1127 } else if ($diff < 92) {
1128 // TRANS: Used in notices to indicate when the notice was made compared to now.
1129 return _('about a minute ago');
1130 } else if ($diff < 3300) {
1131 $minutes = round($diff/60);
1132 // TRANS: Used in notices to indicate when the notice was made compared to now.
1133 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1134 } else if ($diff < 5400) {
1135 // TRANS: Used in notices to indicate when the notice was made compared to now.
1136 return _('about an hour ago');
1137 } else if ($diff < 22 * 3600) {
1138 $hours = round($diff/3600);
1139 // TRANS: Used in notices to indicate when the notice was made compared to now.
1140 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1141 } else if ($diff < 37 * 3600) {
1142 // TRANS: Used in notices to indicate when the notice was made compared to now.
1143 return _('about a day ago');
1144 } else if ($diff < 24 * 24 * 3600) {
1145 $days = round($diff/(24*3600));
1146 // TRANS: Used in notices to indicate when the notice was made compared to now.
1147 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1148 } else if ($diff < 46 * 24 * 3600) {
1149 // TRANS: Used in notices to indicate when the notice was made compared to now.
1150 return _('about a month ago');
1151 } else if ($diff < 330 * 24 * 3600) {
1152 $months = round($diff/(30*24*3600));
1153 // TRANS: Used in notices to indicate when the notice was made compared to now.
1154 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1155 } else if ($diff < 480 * 24 * 3600) {
1156 // TRANS: Used in notices to indicate when the notice was made compared to now.
1157 return _('about a year ago');
1159 return common_exact_date($dt);
1163 function common_exact_date($dt)
1169 $_utc = new DateTimeZone('UTC');
1170 $_siteTz = new DateTimeZone(common_timezone());
1173 $dateStr = date('d F Y H:i:s', strtotime($dt));
1174 $d = new DateTime($dateStr, $_utc);
1175 $d->setTimezone($_siteTz);
1176 return $d->format(DATE_RFC850);
1179 function common_date_w3dtf($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(DATE_W3C);
1187 function common_date_rfc2822($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('r');
1195 function common_date_iso8601($dt)
1197 $dateStr = date('d F Y H:i:s', strtotime($dt));
1198 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1199 $d->setTimezone(new DateTimeZone(common_timezone()));
1200 return $d->format('c');
1203 function common_sql_now()
1205 return common_sql_date(time());
1208 function common_sql_date($datetime)
1210 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1214 * Return an SQL fragment to calculate an age-based weight from a given
1215 * timestamp or datetime column.
1217 * @param string $column name of field we're comparing against current time
1218 * @param integer $dropoff divisor for age in seconds before exponentiation
1219 * @return string SQL fragment
1221 function common_sql_weight($column, $dropoff)
1223 if (common_config('db', 'type') == 'pgsql') {
1224 // PostgreSQL doesn't support timestampdiff function.
1225 // @fixme will this use the right time zone?
1226 // @fixme does this handle cross-year subtraction correctly?
1227 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1229 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1233 function common_redirect($url, $code=307)
1235 static $status = array(301 => "Moved Permanently",
1238 307 => "Temporary Redirect");
1240 header('HTTP/1.1 '.$code.' '.$status[$code]);
1241 header("Location: $url");
1243 $xo = new XMLOutputter();
1245 '-//W3C//DTD XHTML 1.0 Strict//EN',
1246 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1247 $xo->element('a', array('href' => $url), $url);
1252 function common_broadcast_notice($notice, $remote=false)
1258 * Stick the notice on the queue.
1260 function common_enqueue_notice($notice)
1262 static $localTransports = array('omb',
1265 $transports = array();
1266 if (common_config('sms', 'enabled')) {
1267 $transports[] = 'sms';
1269 if (Event::hasHandler('HandleQueuedNotice')) {
1270 $transports[] = 'plugin';
1273 $xmpp = common_config('xmpp', 'enabled');
1276 $transports[] = 'jabber';
1279 // We can skip these for gatewayed notices.
1280 if ($notice->isLocal()) {
1281 $transports = array_merge($transports, $localTransports);
1283 $transports[] = 'public';
1287 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1289 $qm = QueueManager::get();
1291 foreach ($transports as $transport)
1293 $qm->enqueue($notice, $transport);
1296 Event::handle('EndEnqueueNotice', array($notice, $transports));
1303 * Broadcast profile updates to OMB and other remote subscribers.
1305 * Since this may be slow with a lot of subscribers or bad remote sites,
1306 * this is run through the background queues if possible.
1308 function common_broadcast_profile(Profile $profile)
1310 $qm = QueueManager::get();
1311 $qm->enqueue($profile, "profile");
1315 function common_profile_url($nickname)
1317 return common_local_url('showstream', array('nickname' => $nickname),
1322 * Should make up a reasonable root URL
1324 function common_root_url($ssl=false)
1326 $url = common_path('', $ssl, false);
1327 $i = strpos($url, '?');
1329 $url = substr($url, 0, $i);
1335 * returns $bytes bytes of random data as a hexadecimal string
1336 * "good" here is a goal and not a guarantee
1338 function common_good_rand($bytes)
1340 // XXX: use random.org...?
1341 if (@file_exists('/dev/urandom')) {
1342 return common_urandom($bytes);
1343 } else { // FIXME: this is probably not good enough
1344 return common_mtrand($bytes);
1348 function common_urandom($bytes)
1350 $h = fopen('/dev/urandom', 'rb');
1352 $src = fread($h, $bytes);
1355 for ($i = 0; $i < $bytes; $i++) {
1356 $enc .= sprintf("%02x", (ord($src[$i])));
1361 function common_mtrand($bytes)
1364 for ($i = 0; $i < $bytes; $i++) {
1365 $enc .= sprintf("%02x", mt_rand(0, 255));
1371 * Record the given URL as the return destination for a future
1372 * form submission, to be read by common_get_returnto().
1374 * @param string $url
1376 * @fixme as a session-global setting, this can allow multiple forms
1377 * to conflict and overwrite each others' returnto destinations if
1378 * the user has multiple tabs or windows open.
1380 * Should refactor to index with a token or otherwise only pass the
1381 * data along its intended path.
1383 function common_set_returnto($url)
1385 common_ensure_session();
1386 $_SESSION['returnto'] = $url;
1390 * Fetch a return-destination URL previously recorded by
1391 * common_set_returnto().
1393 * @return mixed URL string or null
1395 * @fixme as a session-global setting, this can allow multiple forms
1396 * to conflict and overwrite each others' returnto destinations if
1397 * the user has multiple tabs or windows open.
1399 * Should refactor to index with a token or otherwise only pass the
1400 * data along its intended path.
1402 function common_get_returnto()
1404 common_ensure_session();
1405 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1408 function common_timestamp()
1410 return date('YmdHis');
1413 function common_ensure_syslog()
1415 static $initialized = false;
1416 if (!$initialized) {
1417 openlog(common_config('syslog', 'appname'), 0,
1418 common_config('syslog', 'facility'));
1419 $initialized = true;
1423 function common_log_line($priority, $msg)
1425 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1426 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1427 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1430 function common_request_id()
1433 $server = common_config('site', 'server');
1434 if (php_sapi_name() == 'cli') {
1435 $script = basename($_SERVER['PHP_SELF']);
1436 return "$server:$script:$pid";
1438 static $req_id = null;
1439 if (!isset($req_id)) {
1440 $req_id = substr(md5(mt_rand()), 0, 8);
1442 if (isset($_SERVER['REQUEST_URI'])) {
1443 $url = $_SERVER['REQUEST_URI'];
1445 $method = $_SERVER['REQUEST_METHOD'];
1446 return "$server:$pid.$req_id $method $url";
1450 function common_log($priority, $msg, $filename=null)
1452 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1453 $msg = '[' . common_request_id() . '] ' . $msg;
1454 $logfile = common_config('site', 'logfile');
1456 $log = fopen($logfile, "a");
1458 $output = common_log_line($priority, $msg);
1459 fwrite($log, $output);
1463 common_ensure_syslog();
1464 syslog($priority, $msg);
1466 Event::handle('EndLog', array($priority, $msg, $filename));
1470 function common_debug($msg, $filename=null)
1473 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1475 common_log(LOG_DEBUG, $msg);
1479 function common_log_db_error(&$object, $verb, $filename=null)
1481 $objstr = common_log_objstring($object);
1482 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1483 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1486 function common_log_objstring(&$object)
1488 if (is_null($object)) {
1491 if (!($object instanceof DB_DataObject)) {
1494 $arr = $object->toArray();
1496 foreach ($arr as $k => $v) {
1497 if (is_object($v)) {
1498 $fields[] = "$k='".get_class($v)."'";
1500 $fields[] = "$k='$v'";
1503 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1507 function common_valid_http_url($url)
1509 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1512 function common_valid_tag($tag)
1514 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1515 return (Validate::email($matches[1]) ||
1516 preg_match('/^([\w-\.]+)$/', $matches[1]));
1522 * Determine if given domain or address literal is valid
1523 * eg for use in JIDs and URLs. Does not check if the domain
1526 * @param string $domain
1527 * @return boolean valid or not
1529 function common_valid_domain($domain)
1531 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1532 $ipv4 = "(?:$octet(?:\.$octet){3})";
1533 if (preg_match("/^$ipv4$/u", $domain)) return true;
1535 $group = "(?:[0-9a-f]{1,4})";
1536 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1538 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1539 $before = explode(":", $matches[1]);
1540 $zeroes = $matches[2];
1541 $after = explode(":", $matches[3]);
1549 $explicit = count($before) + count($after);
1550 if ($explicit < $min || $explicit > $max) {
1557 require_once "Net/IDNA.php";
1558 $idn = Net_IDNA::getInstance();
1559 $domain = $idn->encode($domain);
1560 } catch (Exception $e) {
1564 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1565 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1567 return preg_match("/^$fqdn$/ui", $domain);
1570 /* Following functions are copied from MediaWiki GlobalFunctions.php
1571 * and written by Evan Prodromou. */
1573 function common_accept_to_prefs($accept, $def = '*/*')
1575 // No arg means accept anything (per HTTP spec)
1577 return array($def => 1);
1582 $parts = explode(',', $accept);
1584 foreach($parts as $part) {
1585 // FIXME: doesn't deal with params like 'text/html; level=1'
1586 @list($value, $qpart) = explode(';', trim($part));
1588 if(!isset($qpart)) {
1590 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1591 $prefs[$value] = $match[1];
1598 function common_mime_type_match($type, $avail)
1600 if(array_key_exists($type, $avail)) {
1603 $parts = explode('/', $type);
1604 if(array_key_exists($parts[0] . '/*', $avail)) {
1605 return $parts[0] . '/*';
1606 } elseif(array_key_exists('*/*', $avail)) {
1614 function common_negotiate_type($cprefs, $sprefs)
1618 foreach(array_keys($sprefs) as $type) {
1619 $parts = explode('/', $type);
1620 if($parts[1] != '*') {
1621 $ckey = common_mime_type_match($type, $cprefs);
1623 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1628 foreach(array_keys($cprefs) as $type) {
1629 $parts = explode('/', $type);
1630 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1631 $skey = common_mime_type_match($type, $sprefs);
1633 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1639 $besttype = 'text/html';
1641 foreach(array_keys($combine) as $type) {
1642 if($combine[$type] > $bestq) {
1644 $bestq = $combine[$type];
1648 if ('text/html' === $besttype) {
1649 return "text/html; charset=utf-8";
1654 function common_config($main, $sub)
1657 return (array_key_exists($main, $config) &&
1658 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1661 function common_copy_args($from)
1664 $strip = get_magic_quotes_gpc();
1665 foreach ($from as $k => $v) {
1668 $to[$k] = common_copy_args($v);
1670 $to[$k] = stripslashes($v);
1680 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1681 * This is used before handing a request off to OAuthRequest::from_request.
1682 * @fixme Doesn't consider vars other than _POST and _GET?
1683 * @fixme Can't be undone and could corrupt data if run twice.
1685 function common_remove_magic_from_request()
1687 if(get_magic_quotes_gpc()) {
1688 $_POST=array_map('stripslashes',$_POST);
1689 $_GET=array_map('stripslashes',$_GET);
1693 function common_user_uri(&$user)
1695 return common_local_url('userbyid', array('id' => $user->id),
1699 function common_notice_uri(&$notice)
1701 return common_local_url('shownotice',
1702 array('notice' => $notice->id),
1706 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1708 function common_confirmation_code($bits)
1710 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1711 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1712 $chars = ceil($bits/5);
1714 for ($i = 0; $i < $chars; $i++) {
1715 // XXX: convert to string and back
1716 $num = hexdec(common_good_rand(1));
1717 // XXX: randomness is too precious to throw away almost
1718 // 40% of the bits we get!
1719 $code .= $codechars[$num%32];
1724 // convert markup to HTML
1726 function common_markup_to_html($c)
1728 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1729 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1730 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1731 return Markdown($c);
1734 function common_profile_uri($profile)
1739 $user = User::staticGet($profile->id);
1744 $remote = Remote_profile::staticGet($profile->id);
1746 return $remote->uri;
1748 // XXX: this is a very bad profile!
1752 function common_canonical_sms($sms)
1755 preg_replace('/\D/', '', $sms);
1759 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1764 case E_COMPILE_ERROR:
1768 case E_RECOVERABLE_ERROR:
1769 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1774 case E_COMPILE_WARNING:
1775 case E_CORE_WARNING:
1776 case E_USER_WARNING:
1777 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1782 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1787 case E_USER_DEPRECATED:
1788 // XXX: config variable to log this stuff, too
1792 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1797 // FIXME: show error page if we're on the Web
1798 /* Don't execute PHP internal error handler */
1802 function common_session_token()
1804 common_ensure_session();
1805 if (!array_key_exists('token', $_SESSION)) {
1806 $_SESSION['token'] = common_good_rand(64);
1808 return $_SESSION['token'];
1811 function common_cache_key($extra)
1813 return Cache::key($extra);
1816 function common_keyize($str)
1818 return Cache::keyize($str);
1821 function common_memcache()
1823 return Cache::instance();
1826 function common_license_terms($uri)
1828 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1829 return explode('-',$matches[1]);
1834 function common_compatible_license($from, $to)
1836 $from_terms = common_license_terms($from);
1837 // public domain and cc-by are compatible with everything
1838 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1841 $to_terms = common_license_terms($to);
1842 // sa is compatible across versions. IANAL
1843 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1844 return count(array_diff($from_terms, $to_terms)) == 0;
1846 // XXX: better compatibility check needed here!
1847 // Should at least normalise URIs
1848 return ($from == $to);
1852 * returns a quoted table name, if required according to config
1854 function common_database_tablename($tablename)
1856 if(common_config('db','quote_identifiers')) {
1857 $tablename = '"'. $tablename .'"';
1859 //table prefixes could be added here later
1864 * Shorten a URL with the current user's configured shortening service,
1865 * or ur1.ca if configured, or not at all if no shortening is set up.
1866 * Length is not considered.
1868 * @param string $long_url
1869 * @return string may return the original URL if shortening failed
1871 * @fixme provide a way to specify a particular shortener
1872 * @fixme provide a way to specify to use a given user's shortening preferences
1874 function common_shorten_url($long_url)
1876 $long_url = trim($long_url);
1877 $user = common_current_user();
1879 // common current user does not find a user when called from the XMPP daemon
1880 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1881 $shortenerName = 'ur1.ca';
1883 $shortenerName = $user->urlshorteningservice;
1886 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1887 //URL wasn't shortened, so return the long url
1890 //URL was shortened, so return the result
1891 return trim($shortenedUrl);
1896 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1897 * null if not a web request
1899 * @fixme X-Forwarded-For can be chained by multiple proxies;
1900 we should parse the list and provide a cleaner array
1901 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1902 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1903 * use function to get exact request headers from Apache if possible.
1905 function common_client_ip()
1907 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1911 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1912 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1913 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1915 $proxy = $_SERVER['REMOTE_ADDR'];
1917 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1920 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1921 $ip = $_SERVER['HTTP_CLIENT_IP'];
1923 $ip = $_SERVER['REMOTE_ADDR'];
1927 return array($proxy, $ip);
1930 function common_url_to_nickname($url)
1932 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1934 $parts = parse_url($url);
1936 # If any of these parts exist, this won't work
1938 foreach ($bad as $badpart) {
1939 if (array_key_exists($badpart, $parts)) {
1944 # We just have host and/or path
1946 # If it's just a host...
1947 if (array_key_exists('host', $parts) &&
1948 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1950 $hostparts = explode('.', $parts['host']);
1952 # Try to catch common idiom of nickname.service.tld
1954 if ((count($hostparts) > 2) &&
1955 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1956 (strcmp($hostparts[0], 'www') != 0))
1958 return common_nicknamize($hostparts[0]);
1960 # Do the whole hostname
1961 return common_nicknamize($parts['host']);
1964 if (array_key_exists('path', $parts)) {
1965 # Strip starting, ending slashes
1966 $path = preg_replace('@/$@', '', $parts['path']);
1967 $path = preg_replace('@^/@', '', $path);
1968 $path = basename($path);
1970 // Hack for MediaWiki user pages, in the form:
1971 // http://example.com/wiki/User:Myname
1972 // ('User' may be localized.)
1973 if (strpos($path, ':')) {
1974 $parts = array_filter(explode(':', $path));
1975 $path = $parts[count($parts) - 1];
1979 return common_nicknamize($path);
1987 function common_nicknamize($str)
1989 $str = preg_replace('/\W/', '', $str);
1990 return strtolower($str);