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);
37 function common_init_locale($language=null)
40 $language = common_language();
42 putenv('LANGUAGE='.$language);
43 putenv('LANG='.$language);
44 $ok = setlocale(LC_ALL, $language . ".utf8",
53 function common_init_language()
55 mb_internal_encoding('UTF-8');
57 // Note that this setlocale() call may "fail" but this is harmless;
58 // gettext will still select the right language.
59 $language = common_language();
60 $locale_set = common_init_locale($language);
63 // The requested locale doesn't exist on the system.
65 // gettext seems very picky... We first need to setlocale()
66 // to a locale which _does_ exist on the system, and _then_
67 // we can set in another locale that may not be set up
68 // (say, ga_ES for Galego/Galician) it seems to take it.
70 // For some reason C and POSIX which are guaranteed to work
71 // don't do the job. en_US.UTF-8 should be there most of the
72 // time, but not guaranteed.
73 $ok = common_init_locale("en_US");
75 // Try to find a complete, working locale...
76 // @fixme shelling out feels awfully inefficient
77 // but I don't think there's a more standard way.
79 foreach (explode("\n", $all) as $locale) {
80 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
81 $ok = setlocale(LC_ALL, $locale);
88 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
91 $locale_set = common_init_locale($language);
94 common_init_gettext();
100 function common_init_gettext()
102 setlocale(LC_CTYPE, 'C');
103 // So we do not have to make people install the gettext locales
104 $path = common_config('site','locale_path');
105 bindtextdomain("statusnet", $path);
106 bind_textdomain_codeset("statusnet", "UTF-8");
107 textdomain("statusnet");
111 * Switch locale during runtime, and poke gettext until it cries uncle.
112 * Otherwise, sometimes it doesn't actually switch away from the old language.
114 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
116 function common_switch_locale($language=null)
118 common_init_locale($language);
120 setlocale(LC_CTYPE, 'C');
121 // So we do not have to make people install the gettext locales
122 $path = common_config('site','locale_path');
123 bindtextdomain("statusnet", $path);
124 bind_textdomain_codeset("statusnet", "UTF-8");
125 textdomain("statusnet");
129 function common_timezone()
131 if (common_logged_in()) {
132 $user = common_current_user();
133 if ($user->timezone) {
134 return $user->timezone;
138 return common_config('site', 'timezone');
141 function common_language()
144 // If there is a user logged in and they've set a language preference
145 // then return that one...
146 if (_have_config() && common_logged_in()) {
147 $user = common_current_user();
148 $user_language = $user->language;
150 if ($user->language) {
151 // Validate -- we don't want to end up with a bogus code
152 // left over from some old junk.
153 foreach (common_config('site', 'languages') as $code => $info) {
154 if ($info['lang'] == $user_language) {
155 return $user_language;
161 // Otherwise, find the best match for the languages requested by the
163 if (common_config('site', 'langdetect')) {
164 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
165 if (!empty($httplang)) {
166 $language = client_prefered_language($httplang);
172 // Finally, if none of the above worked, use the site's default...
173 return common_config('site', 'language');
175 // salted, hashed passwords are stored in the DB
177 function common_munge_password($password, $id)
179 if (is_object($id) || is_object($password)) {
180 $e = new Exception();
181 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
182 str_replace("\n", " ", $e->getTraceAsString()));
184 return md5($password . $id);
187 // check if a username exists and has matching password
189 function common_check_user($nickname, $password)
191 // empty nickname always unacceptable
192 if (empty($nickname)) {
196 $authenticatedUser = false;
198 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
199 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
201 if (!empty($password)) { // never allow login with blank password
202 if (0 == strcmp(common_munge_password($password, $user->id),
204 //internal checking passed
205 $authenticatedUser = $user;
209 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
212 return $authenticatedUser;
215 // is the current user logged in?
216 function common_logged_in()
218 return (!is_null(common_current_user()));
221 function common_have_session()
223 return (0 != strcmp(session_id(), ''));
226 function common_ensure_session()
229 if (array_key_exists(session_name(), $_COOKIE)) {
230 $c = $_COOKIE[session_name()];
232 if (!common_have_session()) {
233 if (common_config('sessions', 'handle')) {
234 Session::setSaveHandler();
236 if (array_key_exists(session_name(), $_GET)) {
237 $id = $_GET[session_name()];
238 } else if (array_key_exists(session_name(), $_COOKIE)) {
239 $id = $_COOKIE[session_name()];
245 if (!isset($_SESSION['started'])) {
246 $_SESSION['started'] = time();
248 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
249 ' is set but started value is null');
255 // Three kinds of arguments:
260 // Initialize to false; set to null if none found
264 function common_set_user($user)
269 if (is_null($user) && common_have_session()) {
271 unset($_SESSION['userid']);
273 } else if (is_string($user)) {
275 $user = User::staticGet('nickname', $nickname);
276 } else if (!($user instanceof User)) {
281 if (Event::handle('StartSetUser', array(&$user))) {
283 common_ensure_session();
284 $_SESSION['userid'] = $user->id;
286 Event::handle('EndSetUser', array($user));
294 function common_set_cookie($key, $value, $expiration=0)
296 $path = common_config('site', 'path');
297 $server = common_config('site', 'server');
299 if ($path && ($path != '/')) {
300 $cookiepath = '/' . $path . '/';
304 return setcookie($key,
311 define('REMEMBERME', 'rememberme');
312 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
314 function common_rememberme($user=null)
317 $user = common_current_user();
323 $rm = new Remember_me();
325 $rm->code = common_good_rand(16);
326 $rm->user_id = $user->id;
328 // Wrap the insert in some good ol' fashioned transaction code
332 $result = $rm->insert();
335 common_log_db_error($rm, 'INSERT', __FILE__);
339 $rm->query('COMMIT');
341 $cookieval = $rm->user_id . ':' . $rm->code;
343 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
345 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
350 function common_remembered_user()
355 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
361 list($id, $code) = explode(':', $packed);
363 if (!$id || !$code) {
364 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
369 $rm = Remember_me::staticGet($code);
372 common_log(LOG_WARNING, 'No such remember code: ' . $code);
377 if ($rm->user_id != $id) {
378 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
383 $user = User::staticGet($rm->user_id);
386 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
392 $result = $rm->delete();
395 common_log_db_error($rm, 'DELETE', __FILE__);
396 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
401 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
403 common_set_user($user);
404 common_real_login(false);
406 // We issue a new cookie, so they can log in
407 // automatically again after this session
409 common_rememberme($user);
414 // must be called with a valid user!
416 function common_forgetme()
418 common_set_cookie(REMEMBERME, '', 0);
421 // who is the current user?
422 function common_current_user()
426 if (!_have_config()) {
430 if ($_cur === false) {
432 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
433 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
434 common_ensure_session();
435 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
437 $user = User::staticGet($id);
445 // that didn't work; try to remember; will init $_cur to null on failure
446 $_cur = common_remembered_user();
449 // XXX: Is this necessary?
450 $_SESSION['userid'] = $_cur->id;
457 // Logins that are 'remembered' aren't 'real' -- they're subject to
458 // cookie-stealing. So, we don't let them do certain things. New reg,
459 // OpenID, and password logins _are_ real.
461 function common_real_login($real=true)
463 common_ensure_session();
464 $_SESSION['real_login'] = $real;
467 function common_is_real_login()
469 return common_logged_in() && $_SESSION['real_login'];
472 // get canonical version of nickname for comparison
473 function common_canonical_nickname($nickname)
475 // XXX: UTF-8 canonicalization (like combining chars)
476 return strtolower($nickname);
479 // get canonical version of email for comparison
480 function common_canonical_email($email)
482 // XXX: canonicalize UTF-8
483 // XXX: lcase the domain part
487 function common_render_content($text, $notice)
489 $r = common_render_text($text);
490 $id = $notice->profile_id;
491 $r = common_linkify_mentions($r, $notice);
492 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
496 function common_linkify_mentions($text, $notice)
498 $mentions = common_find_mentions($text, $notice);
500 // We need to go through in reverse order by position,
501 // so our positions stay valid despite our fudging with the
506 foreach ($mentions as $mention)
508 $points[$mention['position']] = $mention;
513 foreach ($points as $position => $mention) {
515 $linkText = common_linkify_mention($mention);
517 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
523 function common_linkify_mention($mention)
527 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
529 $xs = new XMLStringer(false);
531 $attrs = array('href' => $mention['url'],
534 if (!empty($mention['title'])) {
535 $attrs['title'] = $mention['title'];
538 $xs->elementStart('span', 'vcard');
539 $xs->elementStart('a', $attrs);
540 $xs->element('span', 'fn nickname', $mention['text']);
541 $xs->elementEnd('a');
542 $xs->elementEnd('span');
544 $output = $xs->getString();
546 Event::handle('EndLinkifyMention', array($mention, &$output));
552 function common_find_mentions($text, $notice)
556 $sender = Profile::staticGet('id', $notice->profile_id);
558 if (empty($sender)) {
562 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
564 // Get the context of the original notice, if any
566 $originalAuthor = null;
567 $originalNotice = null;
568 $originalMentions = array();
572 if (!empty($notice) && !empty($notice->reply_to)) {
573 $originalNotice = Notice::staticGet('id', $notice->reply_to);
574 if (!empty($originalNotice)) {
575 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
577 $ids = $originalNotice->getReplies();
579 foreach ($ids as $id) {
580 $repliedTo = Profile::staticGet('id', $id);
581 if (!empty($repliedTo)) {
582 $originalMentions[$repliedTo->nickname] = $repliedTo;
588 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
591 PREG_OFFSET_CAPTURE);
593 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
596 PREG_OFFSET_CAPTURE);
598 $matches = array_merge($tmatches[1], $atmatches[1]);
600 foreach ($matches as $match) {
602 $nickname = common_canonical_nickname($match[0]);
604 // Try to get a profile for this nickname.
605 // Start with conversation context, then go to
608 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
610 $mentioned = $originalAuthor;
612 } else if (!empty($originalMentions) &&
613 array_key_exists($nickname, $originalMentions)) {
615 $mentioned = $originalMentions[$nickname];
617 $mentioned = common_relative_profile($sender, $nickname);
620 if (!empty($mentioned)) {
622 $user = User::staticGet('id', $mentioned->id);
625 $url = common_local_url('userbyid', array('id' => $user->id));
627 $url = $mentioned->profileurl;
630 $mention = array('mentioned' => array($mentioned),
632 'position' => $match[1],
635 if (!empty($mentioned->fullname)) {
636 $mention['title'] = $mentioned->fullname;
639 $mentions[] = $mention;
643 // @#tag => mention of all subscriptions tagged 'tag'
645 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
648 PREG_OFFSET_CAPTURE);
650 foreach ($hmatches[1] as $hmatch) {
652 $tag = common_canonical_tag($hmatch[0]);
654 $tagged = Profile_tag::getTagged($sender->id, $tag);
656 $url = common_local_url('subscriptions',
657 array('nickname' => $sender->nickname,
660 $mentions[] = array('mentioned' => $tagged,
661 'text' => $hmatch[0],
662 'position' => $hmatch[1],
666 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
672 function common_render_text($text)
674 $r = htmlspecialchars($text);
676 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
677 $r = common_replace_urls_callback($r, 'common_linkify');
678 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
683 function common_replace_urls_callback($text, $callback, $notice_id = null) {
684 // Start off with a regex
686 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
689 '(?:'. //Known protocols
691 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
693 '(?:(?:mailto|aim|tel|xmpp):)'.
695 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
698 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
700 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
704 '|(?:(?: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
706 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
708 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
709 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
710 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
711 '(?: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)'.
715 '(?:\:\d+)?'. //:port
716 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
717 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
718 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
719 ')(?<![\?\.\,\#\,])'.
722 //preg_match_all($regex,$text,$matches);
724 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
727 function callback_helper($matches, $callback, $notice_id) {
729 $left = strpos($matches[0],$url);
730 $right = $left+strlen($url);
732 $groupSymbolSets=array(
750 $cannotEndWith=array('.','?',',','#');
754 foreach($groupSymbolSets as $groupSymbolSet){
755 if(substr($url,-1)==$groupSymbolSet['right']){
756 $group_left_count = substr_count($url,$groupSymbolSet['left']);
757 $group_right_count = substr_count($url,$groupSymbolSet['right']);
758 if($group_left_count<$group_right_count){
760 $url=substr($url,0,-1);
764 if(in_array(substr($url,-1),$cannotEndWith)){
766 $url=substr($url,0,-1);
768 }while($original_url!=$url);
770 if(empty($notice_id)){
771 $result = call_user_func_array($callback, array($url));
773 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
775 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
778 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
779 // lambda implementation in a separate file; PHP 5.2 won't parse it.
780 require_once INSTALLDIR . "/lib/curry.php";
782 function curry($fn) {
783 $args = func_get_args();
785 $id = uniqid('_partial');
786 $GLOBALS[$id] = array($fn, $args);
787 return create_function('',
788 '$args = func_get_args(); '.
789 'return call_user_func_array('.
790 '$GLOBALS["'.$id.'"][0],'.
793 '$GLOBALS["'.$id.'"][1]));');
797 function common_linkify($url) {
798 // It comes in special'd, so we unspecial it before passing to the stringifying
800 $url = htmlspecialchars_decode($url);
802 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
803 //url is an email address without the mailto: protocol
804 $canon = "mailto:$url";
805 $longurl = "mailto:$url";
808 $canon = File_redirection::_canonUrl($url);
810 $longurl_data = File_redirection::where($canon);
811 if (is_array($longurl_data)) {
812 $longurl = $longurl_data['url'];
813 } elseif (is_string($longurl_data)) {
814 $longurl = $longurl_data;
816 throw new ServerException("Can't linkify url '$url'");
819 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
821 $is_attachment = false;
822 $attachment_id = null;
825 // Check to see whether this is a known "attachment" URL.
827 $f = File::staticGet('url', $longurl);
830 // XXX: this writes to the database. :<
831 $f = File::processNew($longurl);
835 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
836 $is_attachment = true;
837 $attachment_id = $f->id;
839 $thumb = File_thumbnail::staticGet('file_id', $f->id);
840 if (!empty($thumb)) {
847 if ($is_attachment) {
848 $attrs['class'] = 'attachment';
850 $attrs['class'] = 'attachment thumbnail';
852 $attrs['id'] = "attachment-{$attachment_id}";
855 return XMLStringer::estring('a', $attrs, $url);
858 function common_shorten_links($text)
860 $maxLength = Notice::maxContent();
861 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
862 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
865 function common_xml_safe_str($str)
867 // Replace common eol and extra whitespace input chars
872 "\0", // null byte eos
873 "\x0B" // vertical tab
876 $replacement = array(
884 $str = str_replace($unWelcome, $replacement, $str);
886 // Neutralize any additional control codes and UTF-16 surrogates
887 // (Twitter uses '*')
888 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
891 function common_tag_link($tag)
893 $canonical = common_canonical_tag($tag);
894 if (common_config('singleuser', 'enabled')) {
895 // regular TagAction isn't set up in 1user mode
896 $url = common_local_url('showstream',
897 array('nickname' => common_config('singleuser', 'nickname'),
898 'tag' => $canonical));
900 $url = common_local_url('tag', array('tag' => $canonical));
902 $xs = new XMLStringer();
903 $xs->elementStart('span', 'tag');
904 $xs->element('a', array('href' => $url,
907 $xs->elementEnd('span');
908 return $xs->getString();
911 function common_canonical_tag($tag)
913 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
914 return str_replace(array('-', '_', '.'), '', $tag);
917 function common_valid_profile_tag($str)
919 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
922 function common_group_link($sender_id, $nickname)
924 $sender = Profile::staticGet($sender_id);
925 $group = User_group::getForNickname($nickname, $sender);
926 if ($sender && $group && $sender->isMember($group)) {
927 $attrs = array('href' => $group->permalink(),
929 if (!empty($group->fullname)) {
930 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
932 $xs = new XMLStringer();
933 $xs->elementStart('span', 'vcard');
934 $xs->elementStart('a', $attrs);
935 $xs->element('span', 'fn nickname', $nickname);
936 $xs->elementEnd('a');
937 $xs->elementEnd('span');
938 return $xs->getString();
944 function common_relative_profile($sender, $nickname, $dt=null)
946 // Try to find profiles this profile is subscribed to that have this nickname
947 $recipient = new Profile();
948 // XXX: use a join instead of a subquery
949 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
950 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
951 if ($recipient->find(true)) {
952 // XXX: should probably differentiate between profiles with
953 // the same name by date of most recent update
956 // Try to find profiles that listen to this profile and that have this nickname
957 $recipient = new Profile();
958 // XXX: use a join instead of a subquery
959 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
960 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
961 if ($recipient->find(true)) {
962 // XXX: should probably differentiate between profiles with
963 // the same name by date of most recent update
966 // If this is a local user, try to find a local user with that nickname.
967 $sender = User::staticGet($sender->id);
969 $recipient_user = User::staticGet('nickname', $nickname);
970 if ($recipient_user) {
971 return $recipient_user->getProfile();
974 // Otherwise, no links. @messages from local users to remote users,
975 // or from remote users to other remote users, are just
976 // outside our ability to make intelligent guesses about
980 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
983 $path = $r->build($action, $args, $params, $fragment);
985 $ssl = common_is_sensitive($action);
987 if (common_config('site','fancy')) {
988 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
990 if (mb_strpos($path, '/index.php') === 0) {
991 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
993 $url = common_path('index.php'.$path, $ssl, $addSession);
999 function common_is_sensitive($action)
1001 static $sensitive = array('login', 'register', 'passwordsettings',
1002 'twittersettings', 'api');
1005 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1006 $ssl = in_array($action, $sensitive);
1012 function common_path($relative, $ssl=false, $addSession=true)
1014 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1016 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1017 || common_config('site', 'ssl') === 'always') {
1019 if (is_string(common_config('site', 'sslserver')) &&
1020 mb_strlen(common_config('site', 'sslserver')) > 0) {
1021 $serverpart = common_config('site', 'sslserver');
1022 } else if (common_config('site', 'server')) {
1023 $serverpart = common_config('site', 'server');
1025 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1029 if (common_config('site', 'server')) {
1030 $serverpart = common_config('site', 'server');
1032 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1037 $relative = common_inject_session($relative, $serverpart);
1040 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1043 function common_inject_session($url, $serverpart = null)
1045 if (common_have_session()) {
1047 if (empty($serverpart)) {
1048 $serverpart = parse_url($url, PHP_URL_HOST);
1051 $currentServer = $_SERVER['HTTP_HOST'];
1053 // Are we pointing to another server (like an SSL server?)
1055 if (!empty($currentServer) &&
1056 0 != strcasecmp($currentServer, $serverpart)) {
1057 // Pass the session ID as a GET parameter
1058 $sesspart = session_name() . '=' . session_id();
1059 $i = strpos($url, '?');
1060 if ($i === false) { // no GET params, just append
1061 $url .= '?' . $sesspart;
1063 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1071 function common_date_string($dt)
1073 // XXX: do some sexy date formatting
1074 // return date(DATE_RFC822, $dt);
1075 $t = strtotime($dt);
1079 if ($now < $t) { // that shouldn't happen!
1080 return common_exact_date($dt);
1081 } else if ($diff < 60) {
1082 // TRANS: Used in notices to indicate when the notice was made compared to now.
1083 return _('a few seconds ago');
1084 } else if ($diff < 92) {
1085 // TRANS: Used in notices to indicate when the notice was made compared to now.
1086 return _('about a minute ago');
1087 } else if ($diff < 3300) {
1088 // XXX: should support plural.
1089 // TRANS: Used in notices to indicate when the notice was made compared to now.
1090 return sprintf(_('about %d minutes ago'), round($diff/60));
1091 } else if ($diff < 5400) {
1092 // TRANS: Used in notices to indicate when the notice was made compared to now.
1093 return _('about an hour ago');
1094 } else if ($diff < 22 * 3600) {
1095 // XXX: should support plural.
1096 // TRANS: Used in notices to indicate when the notice was made compared to now.
1097 return sprintf(_('about %d hours ago'), round($diff/3600));
1098 } else if ($diff < 37 * 3600) {
1099 // TRANS: Used in notices to indicate when the notice was made compared to now.
1100 return _('about a day ago');
1101 } else if ($diff < 24 * 24 * 3600) {
1102 // XXX: should support plural.
1103 // TRANS: Used in notices to indicate when the notice was made compared to now.
1104 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1105 } else if ($diff < 46 * 24 * 3600) {
1106 // TRANS: Used in notices to indicate when the notice was made compared to now.
1107 return _('about a month ago');
1108 } else if ($diff < 330 * 24 * 3600) {
1109 // XXX: should support plural.
1110 // TRANS: Used in notices to indicate when the notice was made compared to now.
1111 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1112 } else if ($diff < 480 * 24 * 3600) {
1113 // TRANS: Used in notices to indicate when the notice was made compared to now.
1114 return _('about a year ago');
1116 return common_exact_date($dt);
1120 function common_exact_date($dt)
1126 $_utc = new DateTimeZone('UTC');
1127 $_siteTz = new DateTimeZone(common_timezone());
1130 $dateStr = date('d F Y H:i:s', strtotime($dt));
1131 $d = new DateTime($dateStr, $_utc);
1132 $d->setTimezone($_siteTz);
1133 return $d->format(DATE_RFC850);
1136 function common_date_w3dtf($dt)
1138 $dateStr = date('d F Y H:i:s', strtotime($dt));
1139 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1140 $d->setTimezone(new DateTimeZone(common_timezone()));
1141 return $d->format(DATE_W3C);
1144 function common_date_rfc2822($dt)
1146 $dateStr = date('d F Y H:i:s', strtotime($dt));
1147 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1148 $d->setTimezone(new DateTimeZone(common_timezone()));
1149 return $d->format('r');
1152 function common_date_iso8601($dt)
1154 $dateStr = date('d F Y H:i:s', strtotime($dt));
1155 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1156 $d->setTimezone(new DateTimeZone(common_timezone()));
1157 return $d->format('c');
1160 function common_sql_now()
1162 return common_sql_date(time());
1165 function common_sql_date($datetime)
1167 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1171 * Return an SQL fragment to calculate an age-based weight from a given
1172 * timestamp or datetime column.
1174 * @param string $column name of field we're comparing against current time
1175 * @param integer $dropoff divisor for age in seconds before exponentiation
1176 * @return string SQL fragment
1178 function common_sql_weight($column, $dropoff)
1180 if (common_config('db', 'type') == 'pgsql') {
1181 // PostgreSQL doesn't support timestampdiff function.
1182 // @fixme will this use the right time zone?
1183 // @fixme does this handle cross-year subtraction correctly?
1184 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1186 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1190 function common_redirect($url, $code=307)
1192 static $status = array(301 => "Moved Permanently",
1195 307 => "Temporary Redirect");
1197 header('HTTP/1.1 '.$code.' '.$status[$code]);
1198 header("Location: $url");
1200 $xo = new XMLOutputter();
1202 '-//W3C//DTD XHTML 1.0 Strict//EN',
1203 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1204 $xo->element('a', array('href' => $url), $url);
1209 function common_broadcast_notice($notice, $remote=false)
1214 // Stick the notice on the queue
1216 function common_enqueue_notice($notice)
1218 static $localTransports = array('omb',
1221 $transports = array();
1222 if (common_config('sms', 'enabled')) {
1223 $transports[] = 'sms';
1225 if (Event::hasHandler('HandleQueuedNotice')) {
1226 $transports[] = 'plugin';
1229 $xmpp = common_config('xmpp', 'enabled');
1232 $transports[] = 'jabber';
1235 // @fixme move these checks into QueueManager and/or individual handlers
1236 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1237 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1238 $transports = array_merge($transports, $localTransports);
1240 $transports[] = 'public';
1244 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1246 $qm = QueueManager::get();
1248 foreach ($transports as $transport)
1250 $qm->enqueue($notice, $transport);
1253 Event::handle('EndEnqueueNotice', array($notice, $transports));
1260 * Broadcast profile updates to OMB and other remote subscribers.
1262 * Since this may be slow with a lot of subscribers or bad remote sites,
1263 * this is run through the background queues if possible.
1265 function common_broadcast_profile(Profile $profile)
1267 $qm = QueueManager::get();
1268 $qm->enqueue($profile, "profile");
1272 function common_profile_url($nickname)
1274 return common_local_url('showstream', array('nickname' => $nickname),
1278 // Should make up a reasonable root URL
1280 function common_root_url($ssl=false)
1282 $url = common_path('', $ssl, false);
1283 $i = strpos($url, '?');
1285 $url = substr($url, 0, $i);
1290 // returns $bytes bytes of random data as a hexadecimal string
1291 // "good" here is a goal and not a guarantee
1293 function common_good_rand($bytes)
1295 // XXX: use random.org...?
1296 if (@file_exists('/dev/urandom')) {
1297 return common_urandom($bytes);
1298 } else { // FIXME: this is probably not good enough
1299 return common_mtrand($bytes);
1303 function common_urandom($bytes)
1305 $h = fopen('/dev/urandom', 'rb');
1307 $src = fread($h, $bytes);
1310 for ($i = 0; $i < $bytes; $i++) {
1311 $enc .= sprintf("%02x", (ord($src[$i])));
1316 function common_mtrand($bytes)
1319 for ($i = 0; $i < $bytes; $i++) {
1320 $enc .= sprintf("%02x", mt_rand(0, 255));
1326 * Record the given URL as the return destination for a future
1327 * form submission, to be read by common_get_returnto().
1329 * @param string $url
1331 * @fixme as a session-global setting, this can allow multiple forms
1332 * to conflict and overwrite each others' returnto destinations if
1333 * the user has multiple tabs or windows open.
1335 * Should refactor to index with a token or otherwise only pass the
1336 * data along its intended path.
1338 function common_set_returnto($url)
1340 common_ensure_session();
1341 $_SESSION['returnto'] = $url;
1345 * Fetch a return-destination URL previously recorded by
1346 * common_set_returnto().
1348 * @return mixed URL string or null
1350 * @fixme as a session-global setting, this can allow multiple forms
1351 * to conflict and overwrite each others' returnto destinations if
1352 * the user has multiple tabs or windows open.
1354 * Should refactor to index with a token or otherwise only pass the
1355 * data along its intended path.
1357 function common_get_returnto()
1359 common_ensure_session();
1360 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1363 function common_timestamp()
1365 return date('YmdHis');
1368 function common_ensure_syslog()
1370 static $initialized = false;
1371 if (!$initialized) {
1372 openlog(common_config('syslog', 'appname'), 0,
1373 common_config('syslog', 'facility'));
1374 $initialized = true;
1378 function common_log_line($priority, $msg)
1380 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1381 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1382 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1385 function common_request_id()
1388 $server = common_config('site', 'server');
1389 if (php_sapi_name() == 'cli') {
1390 $script = basename($_SERVER['PHP_SELF']);
1391 return "$server:$script:$pid";
1393 static $req_id = null;
1394 if (!isset($req_id)) {
1395 $req_id = substr(md5(mt_rand()), 0, 8);
1397 if (isset($_SERVER['REQUEST_URI'])) {
1398 $url = $_SERVER['REQUEST_URI'];
1400 $method = $_SERVER['REQUEST_METHOD'];
1401 return "$server:$pid.$req_id $method $url";
1405 function common_log($priority, $msg, $filename=null)
1407 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1408 $msg = '[' . common_request_id() . '] ' . $msg;
1409 $logfile = common_config('site', 'logfile');
1411 $log = fopen($logfile, "a");
1413 $output = common_log_line($priority, $msg);
1414 fwrite($log, $output);
1418 common_ensure_syslog();
1419 syslog($priority, $msg);
1421 Event::handle('EndLog', array($priority, $msg, $filename));
1425 function common_debug($msg, $filename=null)
1428 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1430 common_log(LOG_DEBUG, $msg);
1434 function common_log_db_error(&$object, $verb, $filename=null)
1436 $objstr = common_log_objstring($object);
1437 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1438 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1441 function common_log_objstring(&$object)
1443 if (is_null($object)) {
1446 if (!($object instanceof DB_DataObject)) {
1449 $arr = $object->toArray();
1451 foreach ($arr as $k => $v) {
1452 if (is_object($v)) {
1453 $fields[] = "$k='".get_class($v)."'";
1455 $fields[] = "$k='$v'";
1458 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1462 function common_valid_http_url($url)
1464 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1467 function common_valid_tag($tag)
1469 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1470 return (Validate::email($matches[1]) ||
1471 preg_match('/^([\w-\.]+)$/', $matches[1]));
1477 * Determine if given domain or address literal is valid
1478 * eg for use in JIDs and URLs. Does not check if the domain
1481 * @param string $domain
1482 * @return boolean valid or not
1484 function common_valid_domain($domain)
1486 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1487 $ipv4 = "(?:$octet(?:\.$octet){3})";
1488 if (preg_match("/^$ipv4$/u", $domain)) return true;
1490 $group = "(?:[0-9a-f]{1,4})";
1491 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1493 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1494 $before = explode(":", $matches[1]);
1495 $zeroes = $matches[2];
1496 $after = explode(":", $matches[3]);
1504 $explicit = count($before) + count($after);
1505 if ($explicit < $min || $explicit > $max) {
1512 require_once "Net/IDNA.php";
1513 $idn = Net_IDNA::getInstance();
1514 $domain = $idn->encode($domain);
1515 } catch (Exception $e) {
1519 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1520 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1522 return preg_match("/^$fqdn$/ui", $domain);
1525 /* Following functions are copied from MediaWiki GlobalFunctions.php
1526 * and written by Evan Prodromou. */
1528 function common_accept_to_prefs($accept, $def = '*/*')
1530 // No arg means accept anything (per HTTP spec)
1532 return array($def => 1);
1537 $parts = explode(',', $accept);
1539 foreach($parts as $part) {
1540 // FIXME: doesn't deal with params like 'text/html; level=1'
1541 @list($value, $qpart) = explode(';', trim($part));
1543 if(!isset($qpart)) {
1545 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1546 $prefs[$value] = $match[1];
1553 function common_mime_type_match($type, $avail)
1555 if(array_key_exists($type, $avail)) {
1558 $parts = explode('/', $type);
1559 if(array_key_exists($parts[0] . '/*', $avail)) {
1560 return $parts[0] . '/*';
1561 } elseif(array_key_exists('*/*', $avail)) {
1569 function common_negotiate_type($cprefs, $sprefs)
1573 foreach(array_keys($sprefs) as $type) {
1574 $parts = explode('/', $type);
1575 if($parts[1] != '*') {
1576 $ckey = common_mime_type_match($type, $cprefs);
1578 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1583 foreach(array_keys($cprefs) as $type) {
1584 $parts = explode('/', $type);
1585 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1586 $skey = common_mime_type_match($type, $sprefs);
1588 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1594 $besttype = 'text/html';
1596 foreach(array_keys($combine) as $type) {
1597 if($combine[$type] > $bestq) {
1599 $bestq = $combine[$type];
1603 if ('text/html' === $besttype) {
1604 return "text/html; charset=utf-8";
1609 function common_config($main, $sub)
1612 return (array_key_exists($main, $config) &&
1613 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1616 function common_copy_args($from)
1619 $strip = get_magic_quotes_gpc();
1620 foreach ($from as $k => $v) {
1623 $to[$k] = common_copy_args($v);
1625 $to[$k] = stripslashes($v);
1635 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1636 * This is used before handing a request off to OAuthRequest::from_request.
1637 * @fixme Doesn't consider vars other than _POST and _GET?
1638 * @fixme Can't be undone and could corrupt data if run twice.
1640 function common_remove_magic_from_request()
1642 if(get_magic_quotes_gpc()) {
1643 $_POST=array_map('stripslashes',$_POST);
1644 $_GET=array_map('stripslashes',$_GET);
1648 function common_user_uri(&$user)
1650 return common_local_url('userbyid', array('id' => $user->id),
1654 function common_notice_uri(&$notice)
1656 return common_local_url('shownotice',
1657 array('notice' => $notice->id),
1661 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1663 function common_confirmation_code($bits)
1665 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1666 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1667 $chars = ceil($bits/5);
1669 for ($i = 0; $i < $chars; $i++) {
1670 // XXX: convert to string and back
1671 $num = hexdec(common_good_rand(1));
1672 // XXX: randomness is too precious to throw away almost
1673 // 40% of the bits we get!
1674 $code .= $codechars[$num%32];
1679 // convert markup to HTML
1681 function common_markup_to_html($c)
1683 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1684 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1685 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1686 return Markdown($c);
1689 function common_profile_uri($profile)
1694 $user = User::staticGet($profile->id);
1699 $remote = Remote_profile::staticGet($profile->id);
1701 return $remote->uri;
1703 // XXX: this is a very bad profile!
1707 function common_canonical_sms($sms)
1710 preg_replace('/\D/', '', $sms);
1714 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1719 case E_COMPILE_ERROR:
1723 case E_RECOVERABLE_ERROR:
1724 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1729 case E_COMPILE_WARNING:
1730 case E_CORE_WARNING:
1731 case E_USER_WARNING:
1732 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1737 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1742 case E_USER_DEPRECATED:
1743 // XXX: config variable to log this stuff, too
1747 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1752 // FIXME: show error page if we're on the Web
1753 /* Don't execute PHP internal error handler */
1757 function common_session_token()
1759 common_ensure_session();
1760 if (!array_key_exists('token', $_SESSION)) {
1761 $_SESSION['token'] = common_good_rand(64);
1763 return $_SESSION['token'];
1766 function common_cache_key($extra)
1768 return Cache::key($extra);
1771 function common_keyize($str)
1773 return Cache::keyize($str);
1776 function common_memcache()
1778 return Cache::instance();
1781 function common_license_terms($uri)
1783 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1784 return explode('-',$matches[1]);
1789 function common_compatible_license($from, $to)
1791 $from_terms = common_license_terms($from);
1792 // public domain and cc-by are compatible with everything
1793 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1796 $to_terms = common_license_terms($to);
1797 // sa is compatible across versions. IANAL
1798 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1799 return count(array_diff($from_terms, $to_terms)) == 0;
1801 // XXX: better compatibility check needed here!
1802 // Should at least normalise URIs
1803 return ($from == $to);
1807 * returns a quoted table name, if required according to config
1809 function common_database_tablename($tablename)
1812 if(common_config('db','quote_identifiers')) {
1813 $tablename = '"'. $tablename .'"';
1815 //table prefixes could be added here later
1820 * Shorten a URL with the current user's configured shortening service,
1821 * or ur1.ca if configured, or not at all if no shortening is set up.
1822 * Length is not considered.
1824 * @param string $long_url
1825 * @return string may return the original URL if shortening failed
1827 * @fixme provide a way to specify a particular shortener
1828 * @fixme provide a way to specify to use a given user's shortening preferences
1830 function common_shorten_url($long_url)
1832 $long_url = trim($long_url);
1833 $user = common_current_user();
1835 // common current user does not find a user when called from the XMPP daemon
1836 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1837 $shortenerName = 'ur1.ca';
1839 $shortenerName = $user->urlshorteningservice;
1842 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1843 //URL wasn't shortened, so return the long url
1846 //URL was shortened, so return the result
1847 return trim($shortenedUrl);
1852 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1853 * null if not a web request
1855 * @fixme X-Forwarded-For can be chained by multiple proxies;
1856 we should parse the list and provide a cleaner array
1857 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1858 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1859 * use function to get exact request headers from Apache if possible.
1861 function common_client_ip()
1863 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1867 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1868 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1869 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1871 $proxy = $_SERVER['REMOTE_ADDR'];
1873 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1876 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1877 $ip = $_SERVER['HTTP_CLIENT_IP'];
1879 $ip = $_SERVER['REMOTE_ADDR'];
1883 return array($proxy, $ip);
1886 function common_url_to_nickname($url)
1888 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1890 $parts = parse_url($url);
1892 # If any of these parts exist, this won't work
1894 foreach ($bad as $badpart) {
1895 if (array_key_exists($badpart, $parts)) {
1900 # We just have host and/or path
1902 # If it's just a host...
1903 if (array_key_exists('host', $parts) &&
1904 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1906 $hostparts = explode('.', $parts['host']);
1908 # Try to catch common idiom of nickname.service.tld
1910 if ((count($hostparts) > 2) &&
1911 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1912 (strcmp($hostparts[0], 'www') != 0))
1914 return common_nicknamize($hostparts[0]);
1916 # Do the whole hostname
1917 return common_nicknamize($parts['host']);
1920 if (array_key_exists('path', $parts)) {
1921 # Strip starting, ending slashes
1922 $path = preg_replace('@/$@', '', $parts['path']);
1923 $path = preg_replace('@^/@', '', $path);
1924 $path = basename($path);
1926 return common_nicknamize($path);
1934 function common_nicknamize($str)
1936 $str = preg_replace('/\W/', '', $str);
1937 return strtolower($str);