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) */
22 // Show a server error
24 function common_server_error($msg, $code=500)
26 $err = new ServerErrorAction($msg, $code);
31 function common_user_error($msg, $code=400)
33 $err = new ClientErrorAction($msg, $code);
38 * This should only be used at setup; processes switching languages
39 * to send text to other users should use common_switch_locale().
41 * @param string $language Locale language code (optional; empty uses
42 * current user's preference or site default)
43 * @return mixed success
45 function common_init_locale($language=null)
48 $language = common_language();
50 putenv('LANGUAGE='.$language);
51 putenv('LANG='.$language);
52 $ok = setlocale(LC_ALL, $language . ".utf8",
62 * Initialize locale and charset settings and gettext with our message catalog,
63 * using the current user's language preference or the site default.
65 * This should generally only be run at framework initialization; code switching
66 * languages at runtime should call common_switch_language().
70 function common_init_language()
72 mb_internal_encoding('UTF-8');
74 // Note that this setlocale() call may "fail" but this is harmless;
75 // gettext will still select the right language.
76 $language = common_language();
77 $locale_set = common_init_locale($language);
80 // The requested locale doesn't exist on the system.
82 // gettext seems very picky... We first need to setlocale()
83 // to a locale which _does_ exist on the system, and _then_
84 // we can set in another locale that may not be set up
85 // (say, ga_ES for Galego/Galician) it seems to take it.
87 // For some reason C and POSIX which are guaranteed to work
88 // don't do the job. en_US.UTF-8 should be there most of the
89 // time, but not guaranteed.
90 $ok = common_init_locale("en_US");
91 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
92 // Try to find a complete, working locale on Unix/Linux...
93 // @fixme shelling out feels awfully inefficient
94 // but I don't think there's a more standard way.
96 foreach (explode("\n", $all) as $locale) {
97 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
98 $ok = setlocale(LC_ALL, $locale);
106 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
108 $locale_set = common_init_locale($language);
111 common_init_gettext();
117 function common_init_gettext()
119 setlocale(LC_CTYPE, 'C');
120 // So we do not have to make people install the gettext locales
121 $path = common_config('site','locale_path');
122 bindtextdomain("statusnet", $path);
123 bind_textdomain_codeset("statusnet", "UTF-8");
124 textdomain("statusnet");
128 * Switch locale during runtime, and poke gettext until it cries uncle.
129 * Otherwise, sometimes it doesn't actually switch away from the old language.
131 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
133 function common_switch_locale($language=null)
135 common_init_locale($language);
137 setlocale(LC_CTYPE, 'C');
138 // So we do not have to make people install the gettext locales
139 $path = common_config('site','locale_path');
140 bindtextdomain("statusnet", $path);
141 bind_textdomain_codeset("statusnet", "UTF-8");
142 textdomain("statusnet");
146 function common_timezone()
148 if (common_logged_in()) {
149 $user = common_current_user();
150 if ($user->timezone) {
151 return $user->timezone;
155 return common_config('site', 'timezone');
158 function common_valid_language($lang)
161 // Validate -- we don't want to end up with a bogus code
162 // left over from some old junk.
163 foreach (common_config('site', 'languages') as $code => $info) {
164 if ($info['lang'] == $lang) {
172 function common_language()
174 // Allow ?uselang=xx override, very useful for debugging
175 // and helping translators check usage and context.
176 if (isset($_GET['uselang'])) {
177 $uselang = strval($_GET['uselang']);
178 if (common_valid_language($uselang)) {
183 // If there is a user logged in and they've set a language preference
184 // then return that one...
185 if (_have_config() && common_logged_in()) {
186 $user = common_current_user();
188 if (common_valid_language($user->language)) {
189 return $user->language;
193 // Otherwise, find the best match for the languages requested by the
195 if (common_config('site', 'langdetect')) {
196 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
197 if (!empty($httplang)) {
198 $language = client_prefered_language($httplang);
204 // Finally, if none of the above worked, use the site's default...
205 return common_config('site', 'language');
207 // salted, hashed passwords are stored in the DB
209 function common_munge_password($password, $id)
211 if (is_object($id) || is_object($password)) {
212 $e = new Exception();
213 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
214 str_replace("\n", " ", $e->getTraceAsString()));
216 return md5($password . $id);
219 // check if a username exists and has matching password
221 function common_check_user($nickname, $password)
223 // empty nickname always unacceptable
224 if (empty($nickname)) {
228 $authenticatedUser = false;
230 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
231 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
233 if (!empty($password)) { // never allow login with blank password
234 if (0 == strcmp(common_munge_password($password, $user->id),
236 //internal checking passed
237 $authenticatedUser = $user;
241 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
244 return $authenticatedUser;
247 // is the current user logged in?
248 function common_logged_in()
250 return (!is_null(common_current_user()));
253 function common_have_session()
255 return (0 != strcmp(session_id(), ''));
258 function common_ensure_session()
261 if (array_key_exists(session_name(), $_COOKIE)) {
262 $c = $_COOKIE[session_name()];
264 if (!common_have_session()) {
265 if (common_config('sessions', 'handle')) {
266 Session::setSaveHandler();
268 if (array_key_exists(session_name(), $_GET)) {
269 $id = $_GET[session_name()];
270 } else if (array_key_exists(session_name(), $_COOKIE)) {
271 $id = $_COOKIE[session_name()];
277 if (!isset($_SESSION['started'])) {
278 $_SESSION['started'] = time();
280 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
281 ' is set but started value is null');
287 // Three kinds of arguments:
292 // Initialize to false; set to null if none found
296 function common_set_user($user)
301 if (is_null($user) && common_have_session()) {
303 unset($_SESSION['userid']);
305 } else if (is_string($user)) {
307 $user = User::staticGet('nickname', $nickname);
308 } else if (!($user instanceof User)) {
313 if (Event::handle('StartSetUser', array(&$user))) {
315 common_ensure_session();
316 $_SESSION['userid'] = $user->id;
318 Event::handle('EndSetUser', array($user));
326 function common_set_cookie($key, $value, $expiration=0)
328 $path = common_config('site', 'path');
329 $server = common_config('site', 'server');
331 if ($path && ($path != '/')) {
332 $cookiepath = '/' . $path . '/';
336 return setcookie($key,
343 define('REMEMBERME', 'rememberme');
344 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
346 function common_rememberme($user=null)
349 $user = common_current_user();
355 $rm = new Remember_me();
357 $rm->code = common_good_rand(16);
358 $rm->user_id = $user->id;
360 // Wrap the insert in some good ol' fashioned transaction code
364 $result = $rm->insert();
367 common_log_db_error($rm, 'INSERT', __FILE__);
371 $rm->query('COMMIT');
373 $cookieval = $rm->user_id . ':' . $rm->code;
375 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
377 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
382 function common_remembered_user()
387 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
393 list($id, $code) = explode(':', $packed);
395 if (!$id || !$code) {
396 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
401 $rm = Remember_me::staticGet($code);
404 common_log(LOG_WARNING, 'No such remember code: ' . $code);
409 if ($rm->user_id != $id) {
410 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
415 $user = User::staticGet($rm->user_id);
418 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
424 $result = $rm->delete();
427 common_log_db_error($rm, 'DELETE', __FILE__);
428 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
433 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
435 common_set_user($user);
436 common_real_login(false);
438 // We issue a new cookie, so they can log in
439 // automatically again after this session
441 common_rememberme($user);
446 // must be called with a valid user!
448 function common_forgetme()
450 common_set_cookie(REMEMBERME, '', 0);
453 // who is the current user?
454 function common_current_user()
458 if (!_have_config()) {
462 if ($_cur === false) {
464 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
465 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
466 common_ensure_session();
467 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
469 $user = User::staticGet($id);
477 // that didn't work; try to remember; will init $_cur to null on failure
478 $_cur = common_remembered_user();
481 // XXX: Is this necessary?
482 $_SESSION['userid'] = $_cur->id;
489 // Logins that are 'remembered' aren't 'real' -- they're subject to
490 // cookie-stealing. So, we don't let them do certain things. New reg,
491 // OpenID, and password logins _are_ real.
493 function common_real_login($real=true)
495 common_ensure_session();
496 $_SESSION['real_login'] = $real;
499 function common_is_real_login()
501 return common_logged_in() && $_SESSION['real_login'];
504 // get canonical version of nickname for comparison
505 function common_canonical_nickname($nickname)
507 // XXX: UTF-8 canonicalization (like combining chars)
508 return strtolower($nickname);
511 // get canonical version of email for comparison
512 function common_canonical_email($email)
514 // XXX: canonicalize UTF-8
515 // XXX: lcase the domain part
519 function common_render_content($text, $notice)
521 $r = common_render_text($text);
522 $id = $notice->profile_id;
523 $r = common_linkify_mentions($r, $notice);
524 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
528 function common_linkify_mentions($text, $notice)
530 $mentions = common_find_mentions($text, $notice);
532 // We need to go through in reverse order by position,
533 // so our positions stay valid despite our fudging with the
538 foreach ($mentions as $mention)
540 $points[$mention['position']] = $mention;
545 foreach ($points as $position => $mention) {
547 $linkText = common_linkify_mention($mention);
549 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
555 function common_linkify_mention($mention)
559 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
561 $xs = new XMLStringer(false);
563 $attrs = array('href' => $mention['url'],
566 if (!empty($mention['title'])) {
567 $attrs['title'] = $mention['title'];
570 $xs->elementStart('span', 'vcard');
571 $xs->elementStart('a', $attrs);
572 $xs->element('span', 'fn nickname', $mention['text']);
573 $xs->elementEnd('a');
574 $xs->elementEnd('span');
576 $output = $xs->getString();
578 Event::handle('EndLinkifyMention', array($mention, &$output));
584 function common_find_mentions($text, $notice)
588 $sender = Profile::staticGet('id', $notice->profile_id);
590 if (empty($sender)) {
594 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
596 // Get the context of the original notice, if any
598 $originalAuthor = null;
599 $originalNotice = null;
600 $originalMentions = array();
604 if (!empty($notice) && !empty($notice->reply_to)) {
605 $originalNotice = Notice::staticGet('id', $notice->reply_to);
606 if (!empty($originalNotice)) {
607 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
609 $ids = $originalNotice->getReplies();
611 foreach ($ids as $id) {
612 $repliedTo = Profile::staticGet('id', $id);
613 if (!empty($repliedTo)) {
614 $originalMentions[$repliedTo->nickname] = $repliedTo;
620 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
623 PREG_OFFSET_CAPTURE);
625 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
628 PREG_OFFSET_CAPTURE);
630 $matches = array_merge($tmatches[1], $atmatches[1]);
632 foreach ($matches as $match) {
634 $nickname = common_canonical_nickname($match[0]);
636 // Try to get a profile for this nickname.
637 // Start with conversation context, then go to
640 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
642 $mentioned = $originalAuthor;
644 } else if (!empty($originalMentions) &&
645 array_key_exists($nickname, $originalMentions)) {
647 $mentioned = $originalMentions[$nickname];
649 $mentioned = common_relative_profile($sender, $nickname);
652 if (!empty($mentioned)) {
654 $user = User::staticGet('id', $mentioned->id);
657 $url = common_local_url('userbyid', array('id' => $user->id));
659 $url = $mentioned->profileurl;
662 $mention = array('mentioned' => array($mentioned),
664 'position' => $match[1],
667 if (!empty($mentioned->fullname)) {
668 $mention['title'] = $mentioned->fullname;
671 $mentions[] = $mention;
675 // @#tag => mention of all subscriptions tagged 'tag'
677 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
680 PREG_OFFSET_CAPTURE);
682 foreach ($hmatches[1] as $hmatch) {
684 $tag = common_canonical_tag($hmatch[0]);
686 $tagged = Profile_tag::getTagged($sender->id, $tag);
688 $url = common_local_url('subscriptions',
689 array('nickname' => $sender->nickname,
692 $mentions[] = array('mentioned' => $tagged,
693 'text' => $hmatch[0],
694 'position' => $hmatch[1],
698 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
704 function common_render_text($text)
706 $r = htmlspecialchars($text);
708 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
709 $r = common_replace_urls_callback($r, 'common_linkify');
710 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
715 function common_replace_urls_callback($text, $callback, $notice_id = null) {
716 // Start off with a regex
718 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
721 '(?:'. //Known protocols
723 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
725 '(?:(?:mailto|aim|tel|xmpp):)'.
727 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
730 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
732 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
736 '|(?:(?: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
738 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
740 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
741 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
742 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
743 '(?: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)'.
747 '(?:\:\d+)?'. //:port
748 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
749 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
750 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
751 ')(?<![\?\.\,\#\,])'.
754 //preg_match_all($regex,$text,$matches);
756 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
759 function callback_helper($matches, $callback, $notice_id) {
761 $left = strpos($matches[0],$url);
762 $right = $left+strlen($url);
764 $groupSymbolSets=array(
782 $cannotEndWith=array('.','?',',','#');
786 foreach($groupSymbolSets as $groupSymbolSet){
787 if(substr($url,-1)==$groupSymbolSet['right']){
788 $group_left_count = substr_count($url,$groupSymbolSet['left']);
789 $group_right_count = substr_count($url,$groupSymbolSet['right']);
790 if($group_left_count<$group_right_count){
792 $url=substr($url,0,-1);
796 if(in_array(substr($url,-1),$cannotEndWith)){
798 $url=substr($url,0,-1);
800 }while($original_url!=$url);
802 if(empty($notice_id)){
803 $result = call_user_func_array($callback, array($url));
805 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
807 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
810 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
811 // lambda implementation in a separate file; PHP 5.2 won't parse it.
812 require_once INSTALLDIR . "/lib/curry.php";
814 function curry($fn) {
815 $args = func_get_args();
817 $id = uniqid('_partial');
818 $GLOBALS[$id] = array($fn, $args);
819 return create_function('',
820 '$args = func_get_args(); '.
821 'return call_user_func_array('.
822 '$GLOBALS["'.$id.'"][0],'.
825 '$GLOBALS["'.$id.'"][1]));');
829 function common_linkify($url) {
830 // It comes in special'd, so we unspecial it before passing to the stringifying
832 $url = htmlspecialchars_decode($url);
834 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
835 //url is an email address without the mailto: protocol
836 $canon = "mailto:$url";
837 $longurl = "mailto:$url";
840 $canon = File_redirection::_canonUrl($url);
842 $longurl_data = File_redirection::where($canon);
843 if (is_array($longurl_data)) {
844 $longurl = $longurl_data['url'];
845 } elseif (is_string($longurl_data)) {
846 $longurl = $longurl_data;
848 throw new ServerException("Can't linkify url '$url'");
851 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
853 $is_attachment = false;
854 $attachment_id = null;
857 // Check to see whether this is a known "attachment" URL.
859 $f = File::staticGet('url', $longurl);
862 // XXX: this writes to the database. :<
863 $f = File::processNew($longurl);
867 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
868 $is_attachment = true;
869 $attachment_id = $f->id;
871 $thumb = File_thumbnail::staticGet('file_id', $f->id);
872 if (!empty($thumb)) {
879 if ($is_attachment) {
880 $attrs['class'] = 'attachment';
882 $attrs['class'] = 'attachment thumbnail';
884 $attrs['id'] = "attachment-{$attachment_id}";
887 return XMLStringer::estring('a', $attrs, $url);
890 function common_shorten_links($text, $always = false)
892 common_debug("common_shorten_links() called");
894 $user = common_current_user();
896 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
898 common_debug("maxLength = $maxLength");
900 if ($always || mb_strlen($text) > $maxLength) {
901 common_debug("Forcing shortening");
902 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'));
904 common_debug("Not forcing shortening");
905 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',
1046 'twittersettings', 'api');
1049 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1050 $ssl = in_array($action, $sensitive);
1056 function common_path($relative, $ssl=false, $addSession=true)
1058 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1060 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1061 || common_config('site', 'ssl') === 'always') {
1063 if (is_string(common_config('site', 'sslserver')) &&
1064 mb_strlen(common_config('site', 'sslserver')) > 0) {
1065 $serverpart = common_config('site', 'sslserver');
1066 } else if (common_config('site', 'server')) {
1067 $serverpart = common_config('site', 'server');
1069 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1073 if (common_config('site', 'server')) {
1074 $serverpart = common_config('site', 'server');
1076 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1081 $relative = common_inject_session($relative, $serverpart);
1084 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1087 function common_inject_session($url, $serverpart = null)
1089 if (common_have_session()) {
1091 if (empty($serverpart)) {
1092 $serverpart = parse_url($url, PHP_URL_HOST);
1095 $currentServer = $_SERVER['HTTP_HOST'];
1097 // Are we pointing to another server (like an SSL server?)
1099 if (!empty($currentServer) &&
1100 0 != strcasecmp($currentServer, $serverpart)) {
1101 // Pass the session ID as a GET parameter
1102 $sesspart = session_name() . '=' . session_id();
1103 $i = strpos($url, '?');
1104 if ($i === false) { // no GET params, just append
1105 $url .= '?' . $sesspart;
1107 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1115 function common_date_string($dt)
1117 // XXX: do some sexy date formatting
1118 // return date(DATE_RFC822, $dt);
1119 $t = strtotime($dt);
1123 if ($now < $t) { // that shouldn't happen!
1124 return common_exact_date($dt);
1125 } else if ($diff < 60) {
1126 // TRANS: Used in notices to indicate when the notice was made compared to now.
1127 return _('a few seconds ago');
1128 } else if ($diff < 92) {
1129 // TRANS: Used in notices to indicate when the notice was made compared to now.
1130 return _('about a minute ago');
1131 } else if ($diff < 3300) {
1132 // XXX: should support plural.
1133 // TRANS: Used in notices to indicate when the notice was made compared to now.
1134 return sprintf(_('about %d minutes ago'), round($diff/60));
1135 } else if ($diff < 5400) {
1136 // TRANS: Used in notices to indicate when the notice was made compared to now.
1137 return _('about an hour ago');
1138 } else if ($diff < 22 * 3600) {
1139 // XXX: should support plural.
1140 // TRANS: Used in notices to indicate when the notice was made compared to now.
1141 return sprintf(_('about %d hours ago'), round($diff/3600));
1142 } else if ($diff < 37 * 3600) {
1143 // TRANS: Used in notices to indicate when the notice was made compared to now.
1144 return _('about a day ago');
1145 } else if ($diff < 24 * 24 * 3600) {
1146 // XXX: should support plural.
1147 // TRANS: Used in notices to indicate when the notice was made compared to now.
1148 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1149 } else if ($diff < 46 * 24 * 3600) {
1150 // TRANS: Used in notices to indicate when the notice was made compared to now.
1151 return _('about a month ago');
1152 } else if ($diff < 330 * 24 * 3600) {
1153 // XXX: should support plural.
1154 // TRANS: Used in notices to indicate when the notice was made compared to now.
1155 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1156 } else if ($diff < 480 * 24 * 3600) {
1157 // TRANS: Used in notices to indicate when the notice was made compared to now.
1158 return _('about a year ago');
1160 return common_exact_date($dt);
1164 function common_exact_date($dt)
1170 $_utc = new DateTimeZone('UTC');
1171 $_siteTz = new DateTimeZone(common_timezone());
1174 $dateStr = date('d F Y H:i:s', strtotime($dt));
1175 $d = new DateTime($dateStr, $_utc);
1176 $d->setTimezone($_siteTz);
1177 return $d->format(DATE_RFC850);
1180 function common_date_w3dtf($dt)
1182 $dateStr = date('d F Y H:i:s', strtotime($dt));
1183 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1184 $d->setTimezone(new DateTimeZone(common_timezone()));
1185 return $d->format(DATE_W3C);
1188 function common_date_rfc2822($dt)
1190 $dateStr = date('d F Y H:i:s', strtotime($dt));
1191 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1192 $d->setTimezone(new DateTimeZone(common_timezone()));
1193 return $d->format('r');
1196 function common_date_iso8601($dt)
1198 $dateStr = date('d F Y H:i:s', strtotime($dt));
1199 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1200 $d->setTimezone(new DateTimeZone(common_timezone()));
1201 return $d->format('c');
1204 function common_sql_now()
1206 return common_sql_date(time());
1209 function common_sql_date($datetime)
1211 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1215 * Return an SQL fragment to calculate an age-based weight from a given
1216 * timestamp or datetime column.
1218 * @param string $column name of field we're comparing against current time
1219 * @param integer $dropoff divisor for age in seconds before exponentiation
1220 * @return string SQL fragment
1222 function common_sql_weight($column, $dropoff)
1224 if (common_config('db', 'type') == 'pgsql') {
1225 // PostgreSQL doesn't support timestampdiff function.
1226 // @fixme will this use the right time zone?
1227 // @fixme does this handle cross-year subtraction correctly?
1228 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1230 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1234 function common_redirect($url, $code=307)
1236 static $status = array(301 => "Moved Permanently",
1239 307 => "Temporary Redirect");
1241 header('HTTP/1.1 '.$code.' '.$status[$code]);
1242 header("Location: $url");
1244 $xo = new XMLOutputter();
1246 '-//W3C//DTD XHTML 1.0 Strict//EN',
1247 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1248 $xo->element('a', array('href' => $url), $url);
1253 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 // We can skip these for gatewayed notices.
1274 if ($notice->isLocal()) {
1275 $transports = array_merge($transports, $localTransports);
1278 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1280 $qm = QueueManager::get();
1282 foreach ($transports as $transport)
1284 $qm->enqueue($notice, $transport);
1287 Event::handle('EndEnqueueNotice', array($notice, $transports));
1294 * Broadcast profile updates to OMB and other remote subscribers.
1296 * Since this may be slow with a lot of subscribers or bad remote sites,
1297 * this is run through the background queues if possible.
1299 function common_broadcast_profile(Profile $profile)
1301 $qm = QueueManager::get();
1302 $qm->enqueue($profile, "profile");
1306 function common_profile_url($nickname)
1308 return common_local_url('showstream', array('nickname' => $nickname),
1312 // Should make up a reasonable root URL
1314 function common_root_url($ssl=false)
1316 $url = common_path('', $ssl, false);
1317 $i = strpos($url, '?');
1319 $url = substr($url, 0, $i);
1324 // returns $bytes bytes of random data as a hexadecimal string
1325 // "good" here is a goal and not a guarantee
1327 function common_good_rand($bytes)
1329 // XXX: use random.org...?
1330 if (@file_exists('/dev/urandom')) {
1331 return common_urandom($bytes);
1332 } else { // FIXME: this is probably not good enough
1333 return common_mtrand($bytes);
1337 function common_urandom($bytes)
1339 $h = fopen('/dev/urandom', 'rb');
1341 $src = fread($h, $bytes);
1344 for ($i = 0; $i < $bytes; $i++) {
1345 $enc .= sprintf("%02x", (ord($src[$i])));
1350 function common_mtrand($bytes)
1353 for ($i = 0; $i < $bytes; $i++) {
1354 $enc .= sprintf("%02x", mt_rand(0, 255));
1360 * Record the given URL as the return destination for a future
1361 * form submission, to be read by common_get_returnto().
1363 * @param string $url
1365 * @fixme as a session-global setting, this can allow multiple forms
1366 * to conflict and overwrite each others' returnto destinations if
1367 * the user has multiple tabs or windows open.
1369 * Should refactor to index with a token or otherwise only pass the
1370 * data along its intended path.
1372 function common_set_returnto($url)
1374 common_ensure_session();
1375 $_SESSION['returnto'] = $url;
1379 * Fetch a return-destination URL previously recorded by
1380 * common_set_returnto().
1382 * @return mixed URL string or null
1384 * @fixme as a session-global setting, this can allow multiple forms
1385 * to conflict and overwrite each others' returnto destinations if
1386 * the user has multiple tabs or windows open.
1388 * Should refactor to index with a token or otherwise only pass the
1389 * data along its intended path.
1391 function common_get_returnto()
1393 common_ensure_session();
1394 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1397 function common_timestamp()
1399 return date('YmdHis');
1402 function common_ensure_syslog()
1404 static $initialized = false;
1405 if (!$initialized) {
1406 openlog(common_config('syslog', 'appname'), 0,
1407 common_config('syslog', 'facility'));
1408 $initialized = true;
1412 function common_log_line($priority, $msg)
1414 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1415 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1416 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1419 function common_request_id()
1422 $server = common_config('site', 'server');
1423 if (php_sapi_name() == 'cli') {
1424 $script = basename($_SERVER['PHP_SELF']);
1425 return "$server:$script:$pid";
1427 static $req_id = null;
1428 if (!isset($req_id)) {
1429 $req_id = substr(md5(mt_rand()), 0, 8);
1431 if (isset($_SERVER['REQUEST_URI'])) {
1432 $url = $_SERVER['REQUEST_URI'];
1434 $method = $_SERVER['REQUEST_METHOD'];
1435 return "$server:$pid.$req_id $method $url";
1439 function common_log($priority, $msg, $filename=null)
1441 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1442 $msg = '[' . common_request_id() . '] ' . $msg;
1443 $logfile = common_config('site', 'logfile');
1445 $log = fopen($logfile, "a");
1447 $output = common_log_line($priority, $msg);
1448 fwrite($log, $output);
1452 common_ensure_syslog();
1453 syslog($priority, $msg);
1455 Event::handle('EndLog', array($priority, $msg, $filename));
1459 function common_debug($msg, $filename=null)
1462 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1464 common_log(LOG_DEBUG, $msg);
1468 function common_log_db_error(&$object, $verb, $filename=null)
1470 $objstr = common_log_objstring($object);
1471 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1472 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1475 function common_log_objstring(&$object)
1477 if (is_null($object)) {
1480 if (!($object instanceof DB_DataObject)) {
1483 $arr = $object->toArray();
1485 foreach ($arr as $k => $v) {
1486 if (is_object($v)) {
1487 $fields[] = "$k='".get_class($v)."'";
1489 $fields[] = "$k='$v'";
1492 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1496 function common_valid_http_url($url)
1498 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1501 function common_valid_tag($tag)
1503 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1504 return (Validate::email($matches[1]) ||
1505 preg_match('/^([\w-\.]+)$/', $matches[1]));
1511 * Determine if given domain or address literal is valid
1512 * eg for use in JIDs and URLs. Does not check if the domain
1515 * @param string $domain
1516 * @return boolean valid or not
1518 function common_valid_domain($domain)
1520 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1521 $ipv4 = "(?:$octet(?:\.$octet){3})";
1522 if (preg_match("/^$ipv4$/u", $domain)) return true;
1524 $group = "(?:[0-9a-f]{1,4})";
1525 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1527 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1528 $before = explode(":", $matches[1]);
1529 $zeroes = $matches[2];
1530 $after = explode(":", $matches[3]);
1538 $explicit = count($before) + count($after);
1539 if ($explicit < $min || $explicit > $max) {
1546 require_once "Net/IDNA.php";
1547 $idn = Net_IDNA::getInstance();
1548 $domain = $idn->encode($domain);
1549 } catch (Exception $e) {
1553 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1554 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1556 return preg_match("/^$fqdn$/ui", $domain);
1559 /* Following functions are copied from MediaWiki GlobalFunctions.php
1560 * and written by Evan Prodromou. */
1562 function common_accept_to_prefs($accept, $def = '*/*')
1564 // No arg means accept anything (per HTTP spec)
1566 return array($def => 1);
1571 $parts = explode(',', $accept);
1573 foreach($parts as $part) {
1574 // FIXME: doesn't deal with params like 'text/html; level=1'
1575 @list($value, $qpart) = explode(';', trim($part));
1577 if(!isset($qpart)) {
1579 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1580 $prefs[$value] = $match[1];
1587 function common_mime_type_match($type, $avail)
1589 if(array_key_exists($type, $avail)) {
1592 $parts = explode('/', $type);
1593 if(array_key_exists($parts[0] . '/*', $avail)) {
1594 return $parts[0] . '/*';
1595 } elseif(array_key_exists('*/*', $avail)) {
1603 function common_negotiate_type($cprefs, $sprefs)
1607 foreach(array_keys($sprefs) as $type) {
1608 $parts = explode('/', $type);
1609 if($parts[1] != '*') {
1610 $ckey = common_mime_type_match($type, $cprefs);
1612 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1617 foreach(array_keys($cprefs) as $type) {
1618 $parts = explode('/', $type);
1619 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1620 $skey = common_mime_type_match($type, $sprefs);
1622 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1628 $besttype = 'text/html';
1630 foreach(array_keys($combine) as $type) {
1631 if($combine[$type] > $bestq) {
1633 $bestq = $combine[$type];
1637 if ('text/html' === $besttype) {
1638 return "text/html; charset=utf-8";
1643 function common_config($main, $sub)
1646 return (array_key_exists($main, $config) &&
1647 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1650 function common_copy_args($from)
1653 $strip = get_magic_quotes_gpc();
1654 foreach ($from as $k => $v) {
1657 $to[$k] = common_copy_args($v);
1659 $to[$k] = stripslashes($v);
1669 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1670 * This is used before handing a request off to OAuthRequest::from_request.
1671 * @fixme Doesn't consider vars other than _POST and _GET?
1672 * @fixme Can't be undone and could corrupt data if run twice.
1674 function common_remove_magic_from_request()
1676 if(get_magic_quotes_gpc()) {
1677 $_POST=array_map('stripslashes',$_POST);
1678 $_GET=array_map('stripslashes',$_GET);
1682 function common_user_uri(&$user)
1684 return common_local_url('userbyid', array('id' => $user->id),
1688 function common_notice_uri(&$notice)
1690 return common_local_url('shownotice',
1691 array('notice' => $notice->id),
1695 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1697 function common_confirmation_code($bits)
1699 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1700 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1701 $chars = ceil($bits/5);
1703 for ($i = 0; $i < $chars; $i++) {
1704 // XXX: convert to string and back
1705 $num = hexdec(common_good_rand(1));
1706 // XXX: randomness is too precious to throw away almost
1707 // 40% of the bits we get!
1708 $code .= $codechars[$num%32];
1713 // convert markup to HTML
1715 function common_markup_to_html($c)
1717 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1718 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1719 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1720 return Markdown($c);
1723 function common_profile_uri($profile)
1728 $user = User::staticGet($profile->id);
1733 $remote = Remote_profile::staticGet($profile->id);
1735 return $remote->uri;
1737 // XXX: this is a very bad profile!
1741 function common_canonical_sms($sms)
1744 preg_replace('/\D/', '', $sms);
1748 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1753 case E_COMPILE_ERROR:
1757 case E_RECOVERABLE_ERROR:
1758 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1763 case E_COMPILE_WARNING:
1764 case E_CORE_WARNING:
1765 case E_USER_WARNING:
1766 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1771 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1776 case E_USER_DEPRECATED:
1777 // XXX: config variable to log this stuff, too
1781 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1786 // FIXME: show error page if we're on the Web
1787 /* Don't execute PHP internal error handler */
1791 function common_session_token()
1793 common_ensure_session();
1794 if (!array_key_exists('token', $_SESSION)) {
1795 $_SESSION['token'] = common_good_rand(64);
1797 return $_SESSION['token'];
1800 function common_cache_key($extra)
1802 return Cache::key($extra);
1805 function common_keyize($str)
1807 return Cache::keyize($str);
1810 function common_memcache()
1812 return Cache::instance();
1815 function common_license_terms($uri)
1817 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1818 return explode('-',$matches[1]);
1823 function common_compatible_license($from, $to)
1825 $from_terms = common_license_terms($from);
1826 // public domain and cc-by are compatible with everything
1827 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1830 $to_terms = common_license_terms($to);
1831 // sa is compatible across versions. IANAL
1832 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1833 return count(array_diff($from_terms, $to_terms)) == 0;
1835 // XXX: better compatibility check needed here!
1836 // Should at least normalise URIs
1837 return ($from == $to);
1841 * returns a quoted table name, if required according to config
1843 function common_database_tablename($tablename)
1846 if(common_config('db','quote_identifiers')) {
1847 $tablename = '"'. $tablename .'"';
1849 //table prefixes could be added here later
1854 * Shorten a URL with the current user's configured shortening service,
1855 * or ur1.ca if configured, or not at all if no shortening is set up.
1857 * @param string $long_url original URL
1858 * @param boolean $force Force shortening (used when notice is too long)
1860 * @return string may return the original URL if shortening failed
1862 * @fixme provide a way to specify a particular shortener
1863 * @fixme provide a way to specify to use a given user's shortening preferences
1866 function common_shorten_url($long_url, $force = false)
1868 common_debug("Shortening URL '$long_url' (force = $force)");
1870 $long_url = trim($long_url);
1872 $user = common_current_user();
1874 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
1875 common_debug("maxUrlLength = $maxUrlLength");
1877 // $force forces shortening even if it's not strictly needed
1879 if (mb_strlen($long_url) < $maxUrlLength && !$force) {
1880 common_debug("Skipped shortening URL.");
1884 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
1886 common_debug("Shortener name = '$shortenerName'");
1888 if (Event::handle('StartShortenUrl', array($long_url, $shortenerName, &$shortenedUrl))) {
1889 //URL wasn't shortened, so return the long url
1892 //URL was shortened, so return the result
1893 return trim($shortenedUrl);
1898 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1899 * null if not a web request
1901 * @fixme X-Forwarded-For can be chained by multiple proxies;
1902 we should parse the list and provide a cleaner array
1903 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1904 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1905 * use function to get exact request headers from Apache if possible.
1907 function common_client_ip()
1909 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1913 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1914 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1915 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1917 $proxy = $_SERVER['REMOTE_ADDR'];
1919 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1922 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1923 $ip = $_SERVER['HTTP_CLIENT_IP'];
1925 $ip = $_SERVER['REMOTE_ADDR'];
1929 return array($proxy, $ip);
1932 function common_url_to_nickname($url)
1934 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1936 $parts = parse_url($url);
1938 # If any of these parts exist, this won't work
1940 foreach ($bad as $badpart) {
1941 if (array_key_exists($badpart, $parts)) {
1946 # We just have host and/or path
1948 # If it's just a host...
1949 if (array_key_exists('host', $parts) &&
1950 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1952 $hostparts = explode('.', $parts['host']);
1954 # Try to catch common idiom of nickname.service.tld
1956 if ((count($hostparts) > 2) &&
1957 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1958 (strcmp($hostparts[0], 'www') != 0))
1960 return common_nicknamize($hostparts[0]);
1962 # Do the whole hostname
1963 return common_nicknamize($parts['host']);
1966 if (array_key_exists('path', $parts)) {
1967 # Strip starting, ending slashes
1968 $path = preg_replace('@/$@', '', $parts['path']);
1969 $path = preg_replace('@^/@', '', $path);
1970 $path = basename($path);
1972 // Hack for MediaWiki user pages, in the form:
1973 // http://example.com/wiki/User:Myname
1974 // ('User' may be localized.)
1975 if (strpos($path, ':')) {
1976 $parts = array_filter(explode(':', $path));
1977 $path = $parts[count($parts) - 1];
1981 return common_nicknamize($path);
1989 function common_nicknamize($str)
1991 $str = preg_replace('/\W/', '', $str);
1992 return strtolower($str);