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'));
910 * Very basic stripping of invalid UTF-8 input text.
913 * @return mixed string or null if invalid input
915 * @todo ideally we should drop bad chars, and maybe do some of the checks
916 * from common_xml_safe_str. But we can't strip newlines, etc.
917 * @todo Unicode normalization might also be useful, but not needed now.
919 function common_validate_utf8($str)
921 // preg_replace will return NULL on invalid UTF-8 input.
922 return preg_replace('//u', '', $str);
926 * Make sure an arbitrary string is safe for output in XML as a single line.
931 function common_xml_safe_str($str)
933 // Replace common eol and extra whitespace input chars
938 "\0", // null byte eos
939 "\x0B" // vertical tab
942 $replacement = array(
950 $str = str_replace($unWelcome, $replacement, $str);
952 // Neutralize any additional control codes and UTF-16 surrogates
953 // (Twitter uses '*')
954 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
957 function common_tag_link($tag)
959 $canonical = common_canonical_tag($tag);
960 if (common_config('singleuser', 'enabled')) {
961 // regular TagAction isn't set up in 1user mode
962 $url = common_local_url('showstream',
963 array('nickname' => common_config('singleuser', 'nickname'),
964 'tag' => $canonical));
966 $url = common_local_url('tag', array('tag' => $canonical));
968 $xs = new XMLStringer();
969 $xs->elementStart('span', 'tag');
970 $xs->element('a', array('href' => $url,
973 $xs->elementEnd('span');
974 return $xs->getString();
977 function common_canonical_tag($tag)
979 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
980 return str_replace(array('-', '_', '.'), '', $tag);
983 function common_valid_profile_tag($str)
985 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
988 function common_group_link($sender_id, $nickname)
990 $sender = Profile::staticGet($sender_id);
991 $group = User_group::getForNickname($nickname, $sender);
992 if ($sender && $group && $sender->isMember($group)) {
993 $attrs = array('href' => $group->permalink(),
995 if (!empty($group->fullname)) {
996 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
998 $xs = new XMLStringer();
999 $xs->elementStart('span', 'vcard');
1000 $xs->elementStart('a', $attrs);
1001 $xs->element('span', 'fn nickname', $nickname);
1002 $xs->elementEnd('a');
1003 $xs->elementEnd('span');
1004 return $xs->getString();
1010 function common_relative_profile($sender, $nickname, $dt=null)
1012 // Try to find profiles this profile is subscribed to that have this nickname
1013 $recipient = new Profile();
1014 // XXX: use a join instead of a subquery
1015 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1016 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1017 if ($recipient->find(true)) {
1018 // XXX: should probably differentiate between profiles with
1019 // the same name by date of most recent update
1022 // Try to find profiles that listen to this profile and that have this nickname
1023 $recipient = new Profile();
1024 // XXX: use a join instead of a subquery
1025 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1026 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1027 if ($recipient->find(true)) {
1028 // XXX: should probably differentiate between profiles with
1029 // the same name by date of most recent update
1032 // If this is a local user, try to find a local user with that nickname.
1033 $sender = User::staticGet($sender->id);
1035 $recipient_user = User::staticGet('nickname', $nickname);
1036 if ($recipient_user) {
1037 return $recipient_user->getProfile();
1040 // Otherwise, no links. @messages from local users to remote users,
1041 // or from remote users to other remote users, are just
1042 // outside our ability to make intelligent guesses about
1046 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1049 $path = $r->build($action, $args, $params, $fragment);
1051 $ssl = common_is_sensitive($action);
1053 if (common_config('site','fancy')) {
1054 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1056 if (mb_strpos($path, '/index.php') === 0) {
1057 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1059 $url = common_path('index.php'.$path, $ssl, $addSession);
1065 function common_is_sensitive($action)
1067 static $sensitive = array('login', 'register', 'passwordsettings', 'api');
1070 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1071 $ssl = in_array($action, $sensitive);
1077 function common_path($relative, $ssl=false, $addSession=true)
1079 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1081 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1082 || common_config('site', 'ssl') === 'always') {
1084 if (is_string(common_config('site', 'sslserver')) &&
1085 mb_strlen(common_config('site', 'sslserver')) > 0) {
1086 $serverpart = common_config('site', 'sslserver');
1087 } else if (common_config('site', 'server')) {
1088 $serverpart = common_config('site', 'server');
1090 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1094 if (common_config('site', 'server')) {
1095 $serverpart = common_config('site', 'server');
1097 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1102 $relative = common_inject_session($relative, $serverpart);
1105 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1108 function common_inject_session($url, $serverpart = null)
1110 if (common_have_session()) {
1112 if (empty($serverpart)) {
1113 $serverpart = parse_url($url, PHP_URL_HOST);
1116 $currentServer = $_SERVER['HTTP_HOST'];
1118 // Are we pointing to another server (like an SSL server?)
1120 if (!empty($currentServer) &&
1121 0 != strcasecmp($currentServer, $serverpart)) {
1122 // Pass the session ID as a GET parameter
1123 $sesspart = session_name() . '=' . session_id();
1124 $i = strpos($url, '?');
1125 if ($i === false) { // no GET params, just append
1126 $url .= '?' . $sesspart;
1128 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1136 function common_date_string($dt)
1138 // XXX: do some sexy date formatting
1139 // return date(DATE_RFC822, $dt);
1140 $t = strtotime($dt);
1144 if ($now < $t) { // that shouldn't happen!
1145 return common_exact_date($dt);
1146 } else if ($diff < 60) {
1147 // TRANS: Used in notices to indicate when the notice was made compared to now.
1148 return _('a few seconds ago');
1149 } else if ($diff < 92) {
1150 // TRANS: Used in notices to indicate when the notice was made compared to now.
1151 return _('about a minute ago');
1152 } else if ($diff < 3300) {
1153 $minutes = round($diff/60);
1154 // TRANS: Used in notices to indicate when the notice was made compared to now.
1155 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1156 } else if ($diff < 5400) {
1157 // TRANS: Used in notices to indicate when the notice was made compared to now.
1158 return _('about an hour ago');
1159 } else if ($diff < 22 * 3600) {
1160 $hours = round($diff/3600);
1161 // TRANS: Used in notices to indicate when the notice was made compared to now.
1162 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1163 } else if ($diff < 37 * 3600) {
1164 // TRANS: Used in notices to indicate when the notice was made compared to now.
1165 return _('about a day ago');
1166 } else if ($diff < 24 * 24 * 3600) {
1167 $days = round($diff/(24*3600));
1168 // TRANS: Used in notices to indicate when the notice was made compared to now.
1169 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1170 } else if ($diff < 46 * 24 * 3600) {
1171 // TRANS: Used in notices to indicate when the notice was made compared to now.
1172 return _('about a month ago');
1173 } else if ($diff < 330 * 24 * 3600) {
1174 $months = round($diff/(30*24*3600));
1175 // TRANS: Used in notices to indicate when the notice was made compared to now.
1176 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1177 } else if ($diff < 480 * 24 * 3600) {
1178 // TRANS: Used in notices to indicate when the notice was made compared to now.
1179 return _('about a year ago');
1181 return common_exact_date($dt);
1185 function common_exact_date($dt)
1191 $_utc = new DateTimeZone('UTC');
1192 $_siteTz = new DateTimeZone(common_timezone());
1195 $dateStr = date('d F Y H:i:s', strtotime($dt));
1196 $d = new DateTime($dateStr, $_utc);
1197 $d->setTimezone($_siteTz);
1198 return $d->format(DATE_RFC850);
1201 function common_date_w3dtf($dt)
1203 $dateStr = date('d F Y H:i:s', strtotime($dt));
1204 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1205 $d->setTimezone(new DateTimeZone(common_timezone()));
1206 return $d->format(DATE_W3C);
1209 function common_date_rfc2822($dt)
1211 $dateStr = date('d F Y H:i:s', strtotime($dt));
1212 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1213 $d->setTimezone(new DateTimeZone(common_timezone()));
1214 return $d->format('r');
1217 function common_date_iso8601($dt)
1219 $dateStr = date('d F Y H:i:s', strtotime($dt));
1220 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1221 $d->setTimezone(new DateTimeZone(common_timezone()));
1222 return $d->format('c');
1225 function common_sql_now()
1227 return common_sql_date(time());
1230 function common_sql_date($datetime)
1232 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1236 * Return an SQL fragment to calculate an age-based weight from a given
1237 * timestamp or datetime column.
1239 * @param string $column name of field we're comparing against current time
1240 * @param integer $dropoff divisor for age in seconds before exponentiation
1241 * @return string SQL fragment
1243 function common_sql_weight($column, $dropoff)
1245 if (common_config('db', 'type') == 'pgsql') {
1246 // PostgreSQL doesn't support timestampdiff function.
1247 // @fixme will this use the right time zone?
1248 // @fixme does this handle cross-year subtraction correctly?
1249 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1251 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1255 function common_redirect($url, $code=307)
1257 static $status = array(301 => "Moved Permanently",
1260 307 => "Temporary Redirect");
1262 header('HTTP/1.1 '.$code.' '.$status[$code]);
1263 header("Location: $url");
1265 $xo = new XMLOutputter();
1267 '-//W3C//DTD XHTML 1.0 Strict//EN',
1268 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1269 $xo->element('a', array('href' => $url), $url);
1274 function common_broadcast_notice($notice, $remote=false)
1280 * Stick the notice on the queue.
1282 function common_enqueue_notice($notice)
1284 static $localTransports = array('omb',
1287 $transports = array();
1288 if (common_config('sms', 'enabled')) {
1289 $transports[] = 'sms';
1291 if (Event::hasHandler('HandleQueuedNotice')) {
1292 $transports[] = 'plugin';
1295 $xmpp = common_config('xmpp', 'enabled');
1298 $transports[] = 'jabber';
1301 // We can skip these for gatewayed notices.
1302 if ($notice->isLocal()) {
1303 $transports = array_merge($transports, $localTransports);
1305 $transports[] = 'public';
1309 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1311 $qm = QueueManager::get();
1313 foreach ($transports as $transport)
1315 $qm->enqueue($notice, $transport);
1318 Event::handle('EndEnqueueNotice', array($notice, $transports));
1325 * Broadcast profile updates to OMB and other remote subscribers.
1327 * Since this may be slow with a lot of subscribers or bad remote sites,
1328 * this is run through the background queues if possible.
1330 function common_broadcast_profile(Profile $profile)
1332 $qm = QueueManager::get();
1333 $qm->enqueue($profile, "profile");
1337 function common_profile_url($nickname)
1339 return common_local_url('showstream', array('nickname' => $nickname),
1344 * Should make up a reasonable root URL
1346 function common_root_url($ssl=false)
1348 $url = common_path('', $ssl, false);
1349 $i = strpos($url, '?');
1351 $url = substr($url, 0, $i);
1357 * returns $bytes bytes of random data as a hexadecimal string
1358 * "good" here is a goal and not a guarantee
1360 function common_good_rand($bytes)
1362 // XXX: use random.org...?
1363 if (@file_exists('/dev/urandom')) {
1364 return common_urandom($bytes);
1365 } else { // FIXME: this is probably not good enough
1366 return common_mtrand($bytes);
1370 function common_urandom($bytes)
1372 $h = fopen('/dev/urandom', 'rb');
1374 $src = fread($h, $bytes);
1377 for ($i = 0; $i < $bytes; $i++) {
1378 $enc .= sprintf("%02x", (ord($src[$i])));
1383 function common_mtrand($bytes)
1386 for ($i = 0; $i < $bytes; $i++) {
1387 $enc .= sprintf("%02x", mt_rand(0, 255));
1393 * Record the given URL as the return destination for a future
1394 * form submission, to be read by common_get_returnto().
1396 * @param string $url
1398 * @fixme as a session-global setting, this can allow multiple forms
1399 * to conflict and overwrite each others' returnto destinations if
1400 * the user has multiple tabs or windows open.
1402 * Should refactor to index with a token or otherwise only pass the
1403 * data along its intended path.
1405 function common_set_returnto($url)
1407 common_ensure_session();
1408 $_SESSION['returnto'] = $url;
1412 * Fetch a return-destination URL previously recorded by
1413 * common_set_returnto().
1415 * @return mixed URL string or null
1417 * @fixme as a session-global setting, this can allow multiple forms
1418 * to conflict and overwrite each others' returnto destinations if
1419 * the user has multiple tabs or windows open.
1421 * Should refactor to index with a token or otherwise only pass the
1422 * data along its intended path.
1424 function common_get_returnto()
1426 common_ensure_session();
1427 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1430 function common_timestamp()
1432 return date('YmdHis');
1435 function common_ensure_syslog()
1437 static $initialized = false;
1438 if (!$initialized) {
1439 openlog(common_config('syslog', 'appname'), 0,
1440 common_config('syslog', 'facility'));
1441 $initialized = true;
1445 function common_log_line($priority, $msg)
1447 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1448 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1449 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1452 function common_request_id()
1455 $server = common_config('site', 'server');
1456 if (php_sapi_name() == 'cli') {
1457 $script = basename($_SERVER['PHP_SELF']);
1458 return "$server:$script:$pid";
1460 static $req_id = null;
1461 if (!isset($req_id)) {
1462 $req_id = substr(md5(mt_rand()), 0, 8);
1464 if (isset($_SERVER['REQUEST_URI'])) {
1465 $url = $_SERVER['REQUEST_URI'];
1467 $method = $_SERVER['REQUEST_METHOD'];
1468 return "$server:$pid.$req_id $method $url";
1472 function common_log($priority, $msg, $filename=null)
1474 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1475 $msg = '[' . common_request_id() . '] ' . $msg;
1476 $logfile = common_config('site', 'logfile');
1478 $log = fopen($logfile, "a");
1480 $output = common_log_line($priority, $msg);
1481 fwrite($log, $output);
1485 common_ensure_syslog();
1486 syslog($priority, $msg);
1488 Event::handle('EndLog', array($priority, $msg, $filename));
1492 function common_debug($msg, $filename=null)
1495 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1497 common_log(LOG_DEBUG, $msg);
1501 function common_log_db_error(&$object, $verb, $filename=null)
1503 $objstr = common_log_objstring($object);
1504 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1505 if (is_object($last_error)) {
1506 $msg = $last_error->message;
1508 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1510 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1513 function common_log_objstring(&$object)
1515 if (is_null($object)) {
1518 if (!($object instanceof DB_DataObject)) {
1521 $arr = $object->toArray();
1523 foreach ($arr as $k => $v) {
1524 if (is_object($v)) {
1525 $fields[] = "$k='".get_class($v)."'";
1527 $fields[] = "$k='$v'";
1530 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1534 function common_valid_http_url($url)
1536 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1539 function common_valid_tag($tag)
1541 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1542 return (Validate::email($matches[1]) ||
1543 preg_match('/^([\w-\.]+)$/', $matches[1]));
1549 * Determine if given domain or address literal is valid
1550 * eg for use in JIDs and URLs. Does not check if the domain
1553 * @param string $domain
1554 * @return boolean valid or not
1556 function common_valid_domain($domain)
1558 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1559 $ipv4 = "(?:$octet(?:\.$octet){3})";
1560 if (preg_match("/^$ipv4$/u", $domain)) return true;
1562 $group = "(?:[0-9a-f]{1,4})";
1563 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1565 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1566 $before = explode(":", $matches[1]);
1567 $zeroes = $matches[2];
1568 $after = explode(":", $matches[3]);
1576 $explicit = count($before) + count($after);
1577 if ($explicit < $min || $explicit > $max) {
1584 require_once "Net/IDNA.php";
1585 $idn = Net_IDNA::getInstance();
1586 $domain = $idn->encode($domain);
1587 } catch (Exception $e) {
1591 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1592 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1594 return preg_match("/^$fqdn$/ui", $domain);
1597 /* Following functions are copied from MediaWiki GlobalFunctions.php
1598 * and written by Evan Prodromou. */
1600 function common_accept_to_prefs($accept, $def = '*/*')
1602 // No arg means accept anything (per HTTP spec)
1604 return array($def => 1);
1609 $parts = explode(',', $accept);
1611 foreach($parts as $part) {
1612 // FIXME: doesn't deal with params like 'text/html; level=1'
1613 @list($value, $qpart) = explode(';', trim($part));
1615 if(!isset($qpart)) {
1617 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1618 $prefs[$value] = $match[1];
1625 function common_mime_type_match($type, $avail)
1627 if(array_key_exists($type, $avail)) {
1630 $parts = explode('/', $type);
1631 if(array_key_exists($parts[0] . '/*', $avail)) {
1632 return $parts[0] . '/*';
1633 } elseif(array_key_exists('*/*', $avail)) {
1641 function common_negotiate_type($cprefs, $sprefs)
1645 foreach(array_keys($sprefs) as $type) {
1646 $parts = explode('/', $type);
1647 if($parts[1] != '*') {
1648 $ckey = common_mime_type_match($type, $cprefs);
1650 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1655 foreach(array_keys($cprefs) as $type) {
1656 $parts = explode('/', $type);
1657 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1658 $skey = common_mime_type_match($type, $sprefs);
1660 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1666 $besttype = 'text/html';
1668 foreach(array_keys($combine) as $type) {
1669 if($combine[$type] > $bestq) {
1671 $bestq = $combine[$type];
1675 if ('text/html' === $besttype) {
1676 return "text/html; charset=utf-8";
1681 function common_config($main, $sub)
1684 return (array_key_exists($main, $config) &&
1685 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1689 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1690 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1692 * @param array $from
1695 function common_copy_args($from)
1698 $strip = get_magic_quotes_gpc();
1699 foreach ($from as $k => $v) {
1701 $to[$k] = common_copy_args($v);
1704 $v = stripslashes($v);
1706 $to[$k] = strval(common_validate_utf8($v));
1713 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1714 * This is used before handing a request off to OAuthRequest::from_request.
1715 * @fixme Doesn't consider vars other than _POST and _GET?
1716 * @fixme Can't be undone and could corrupt data if run twice.
1718 function common_remove_magic_from_request()
1720 if(get_magic_quotes_gpc()) {
1721 $_POST=array_map('stripslashes',$_POST);
1722 $_GET=array_map('stripslashes',$_GET);
1726 function common_user_uri(&$user)
1728 return common_local_url('userbyid', array('id' => $user->id),
1732 function common_notice_uri(&$notice)
1734 return common_local_url('shownotice',
1735 array('notice' => $notice->id),
1739 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1741 function common_confirmation_code($bits)
1743 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1744 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1745 $chars = ceil($bits/5);
1747 for ($i = 0; $i < $chars; $i++) {
1748 // XXX: convert to string and back
1749 $num = hexdec(common_good_rand(1));
1750 // XXX: randomness is too precious to throw away almost
1751 // 40% of the bits we get!
1752 $code .= $codechars[$num%32];
1757 // convert markup to HTML
1759 function common_markup_to_html($c)
1761 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1762 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1763 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1764 return Markdown($c);
1767 function common_profile_uri($profile)
1772 $user = User::staticGet($profile->id);
1777 $remote = Remote_profile::staticGet($profile->id);
1779 return $remote->uri;
1781 // XXX: this is a very bad profile!
1785 function common_canonical_sms($sms)
1788 preg_replace('/\D/', '', $sms);
1792 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1797 case E_COMPILE_ERROR:
1801 case E_RECOVERABLE_ERROR:
1802 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1807 case E_COMPILE_WARNING:
1808 case E_CORE_WARNING:
1809 case E_USER_WARNING:
1810 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1815 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1820 case E_USER_DEPRECATED:
1821 // XXX: config variable to log this stuff, too
1825 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1830 // FIXME: show error page if we're on the Web
1831 /* Don't execute PHP internal error handler */
1835 function common_session_token()
1837 common_ensure_session();
1838 if (!array_key_exists('token', $_SESSION)) {
1839 $_SESSION['token'] = common_good_rand(64);
1841 return $_SESSION['token'];
1844 function common_cache_key($extra)
1846 return Cache::key($extra);
1849 function common_keyize($str)
1851 return Cache::keyize($str);
1854 function common_memcache()
1856 return Cache::instance();
1859 function common_license_terms($uri)
1861 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1862 return explode('-',$matches[1]);
1867 function common_compatible_license($from, $to)
1869 $from_terms = common_license_terms($from);
1870 // public domain and cc-by are compatible with everything
1871 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1874 $to_terms = common_license_terms($to);
1875 // sa is compatible across versions. IANAL
1876 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1877 return count(array_diff($from_terms, $to_terms)) == 0;
1879 // XXX: better compatibility check needed here!
1880 // Should at least normalise URIs
1881 return ($from == $to);
1885 * returns a quoted table name, if required according to config
1887 function common_database_tablename($tablename)
1889 if(common_config('db','quote_identifiers')) {
1890 $tablename = '"'. $tablename .'"';
1892 //table prefixes could be added here later
1897 * Shorten a URL with the current user's configured shortening service,
1898 * or ur1.ca if configured, or not at all if no shortening is set up.
1899 * Length is not considered.
1901 * @param string $long_url
1902 * @return string may return the original URL if shortening failed
1904 * @fixme provide a way to specify a particular shortener
1905 * @fixme provide a way to specify to use a given user's shortening preferences
1907 function common_shorten_url($long_url)
1909 $long_url = trim($long_url);
1910 $user = common_current_user();
1912 // common current user does not find a user when called from the XMPP daemon
1913 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1914 $shortenerName = 'ur1.ca';
1916 $shortenerName = $user->urlshorteningservice;
1919 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1920 //URL wasn't shortened, so return the long url
1923 //URL was shortened, so return the result
1924 return trim($shortenedUrl);
1929 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1930 * null if not a web request
1932 * @fixme X-Forwarded-For can be chained by multiple proxies;
1933 we should parse the list and provide a cleaner array
1934 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1935 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1936 * use function to get exact request headers from Apache if possible.
1938 function common_client_ip()
1940 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1944 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1945 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1946 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1948 $proxy = $_SERVER['REMOTE_ADDR'];
1950 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1953 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1954 $ip = $_SERVER['HTTP_CLIENT_IP'];
1956 $ip = $_SERVER['REMOTE_ADDR'];
1960 return array($proxy, $ip);
1963 function common_url_to_nickname($url)
1965 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1967 $parts = parse_url($url);
1969 # If any of these parts exist, this won't work
1971 foreach ($bad as $badpart) {
1972 if (array_key_exists($badpart, $parts)) {
1977 # We just have host and/or path
1979 # If it's just a host...
1980 if (array_key_exists('host', $parts) &&
1981 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1983 $hostparts = explode('.', $parts['host']);
1985 # Try to catch common idiom of nickname.service.tld
1987 if ((count($hostparts) > 2) &&
1988 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1989 (strcmp($hostparts[0], 'www') != 0))
1991 return common_nicknamize($hostparts[0]);
1993 # Do the whole hostname
1994 return common_nicknamize($parts['host']);
1997 if (array_key_exists('path', $parts)) {
1998 # Strip starting, ending slashes
1999 $path = preg_replace('@/$@', '', $parts['path']);
2000 $path = preg_replace('@^/@', '', $path);
2001 $path = basename($path);
2003 // Hack for MediaWiki user pages, in the form:
2004 // http://example.com/wiki/User:Myname
2005 // ('User' may be localized.)
2006 if (strpos($path, ':')) {
2007 $parts = array_filter(explode(':', $path));
2008 $path = $parts[count($parts) - 1];
2012 return common_nicknamize($path);
2020 function common_nicknamize($str)
2022 $str = preg_replace('/\W/', '', $str);
2023 return strtolower($str);