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 return setlocale(LC_ALL, $language . ".utf8",
51 function common_init_language()
53 mb_internal_encoding('UTF-8');
55 // Note that this setlocale() call may "fail" but this is harmless;
56 // gettext will still select the right language.
57 $language = common_language();
58 $locale_set = common_init_locale($language);
61 // The requested locale doesn't exist on the system.
63 // gettext seems very picky... We first need to setlocale()
64 // to a locale which _does_ exist on the system, and _then_
65 // we can set in another locale that may not be set up
66 // (say, ga_ES for Galego/Galician) it seems to take it.
68 // For some reason C and POSIX which are guaranteed to work
69 // don't do the job. en_US.UTF-8 should be there most of the
70 // time, but not guaranteed.
71 $ok = common_init_locale("en_US");
73 // Try to find a complete, working locale...
74 // @fixme shelling out feels awfully inefficient
75 // but I don't think there's a more standard way.
77 foreach (explode("\n", $all) as $locale) {
78 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
79 $ok = setlocale(LC_ALL, $locale);
86 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
89 $locale_set = common_init_locale($language);
92 setlocale(LC_CTYPE, 'C');
93 // So we do not have to make people install the gettext locales
94 $path = common_config('site','locale_path');
95 bindtextdomain("statusnet", $path);
96 bind_textdomain_codeset("statusnet", "UTF-8");
97 textdomain("statusnet");
100 function common_timezone()
102 if (common_logged_in()) {
103 $user = common_current_user();
104 if ($user->timezone) {
105 return $user->timezone;
109 return common_config('site', 'timezone');
112 function common_language()
115 // If there is a user logged in and they've set a language preference
116 // then return that one...
117 if (_have_config() && common_logged_in()) {
118 $user = common_current_user();
119 $user_language = $user->language;
121 if ($user->language) {
122 // Validate -- we don't want to end up with a bogus code
123 // left over from some old junk.
124 foreach (common_config('site', 'languages') as $code => $info) {
125 if ($info['lang'] == $user_language) {
126 return $user_language;
132 // Otherwise, find the best match for the languages requested by the
134 if (common_config('site', 'langdetect')) {
135 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
136 if (!empty($httplang)) {
137 $language = client_prefered_language($httplang);
143 // Finally, if none of the above worked, use the site's default...
144 return common_config('site', 'language');
146 // salted, hashed passwords are stored in the DB
148 function common_munge_password($password, $id)
150 if (is_object($id) || is_object($password)) {
151 $e = new Exception();
152 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
153 str_replace("\n", " ", $e->getTraceAsString()));
155 return md5($password . $id);
158 // check if a username exists and has matching password
160 function common_check_user($nickname, $password)
162 // empty nickname always unacceptable
163 if (empty($nickname)) {
167 $authenticatedUser = false;
169 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
170 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
172 if (!empty($password)) { // never allow login with blank password
173 if (0 == strcmp(common_munge_password($password, $user->id),
175 //internal checking passed
176 $authenticatedUser = $user;
180 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
183 return $authenticatedUser;
186 // is the current user logged in?
187 function common_logged_in()
189 return (!is_null(common_current_user()));
192 function common_have_session()
194 return (0 != strcmp(session_id(), ''));
197 function common_ensure_session()
200 if (array_key_exists(session_name(), $_COOKIE)) {
201 $c = $_COOKIE[session_name()];
203 if (!common_have_session()) {
204 if (common_config('sessions', 'handle')) {
205 Session::setSaveHandler();
207 if (array_key_exists(session_name(), $_GET)) {
208 $id = $_GET[session_name()];
209 } else if (array_key_exists(session_name(), $_COOKIE)) {
210 $id = $_COOKIE[session_name()];
216 if (!isset($_SESSION['started'])) {
217 $_SESSION['started'] = time();
219 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
220 ' is set but started value is null');
226 // Three kinds of arguments:
231 // Initialize to false; set to null if none found
235 function common_set_user($user)
240 if (is_null($user) && common_have_session()) {
242 unset($_SESSION['userid']);
244 } else if (is_string($user)) {
246 $user = User::staticGet('nickname', $nickname);
247 } else if (!($user instanceof User)) {
252 if (Event::handle('StartSetUser', array(&$user))) {
254 common_ensure_session();
255 $_SESSION['userid'] = $user->id;
257 Event::handle('EndSetUser', array($user));
265 function common_set_cookie($key, $value, $expiration=0)
267 $path = common_config('site', 'path');
268 $server = common_config('site', 'server');
270 if ($path && ($path != '/')) {
271 $cookiepath = '/' . $path . '/';
275 return setcookie($key,
282 define('REMEMBERME', 'rememberme');
283 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
285 function common_rememberme($user=null)
288 $user = common_current_user();
294 $rm = new Remember_me();
296 $rm->code = common_good_rand(16);
297 $rm->user_id = $user->id;
299 // Wrap the insert in some good ol' fashioned transaction code
303 $result = $rm->insert();
306 common_log_db_error($rm, 'INSERT', __FILE__);
310 $rm->query('COMMIT');
312 $cookieval = $rm->user_id . ':' . $rm->code;
314 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
316 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
321 function common_remembered_user()
326 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
332 list($id, $code) = explode(':', $packed);
334 if (!$id || !$code) {
335 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
340 $rm = Remember_me::staticGet($code);
343 common_log(LOG_WARNING, 'No such remember code: ' . $code);
348 if ($rm->user_id != $id) {
349 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
354 $user = User::staticGet($rm->user_id);
357 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
363 $result = $rm->delete();
366 common_log_db_error($rm, 'DELETE', __FILE__);
367 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
372 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
374 common_set_user($user);
375 common_real_login(false);
377 // We issue a new cookie, so they can log in
378 // automatically again after this session
380 common_rememberme($user);
385 // must be called with a valid user!
387 function common_forgetme()
389 common_set_cookie(REMEMBERME, '', 0);
392 // who is the current user?
393 function common_current_user()
397 if (!_have_config()) {
401 if ($_cur === false) {
403 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
404 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
405 common_ensure_session();
406 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
408 $user = User::staticGet($id);
416 // that didn't work; try to remember; will init $_cur to null on failure
417 $_cur = common_remembered_user();
420 // XXX: Is this necessary?
421 $_SESSION['userid'] = $_cur->id;
428 // Logins that are 'remembered' aren't 'real' -- they're subject to
429 // cookie-stealing. So, we don't let them do certain things. New reg,
430 // OpenID, and password logins _are_ real.
432 function common_real_login($real=true)
434 common_ensure_session();
435 $_SESSION['real_login'] = $real;
438 function common_is_real_login()
440 return common_logged_in() && $_SESSION['real_login'];
443 // get canonical version of nickname for comparison
444 function common_canonical_nickname($nickname)
446 // XXX: UTF-8 canonicalization (like combining chars)
447 return strtolower($nickname);
450 // get canonical version of email for comparison
451 function common_canonical_email($email)
453 // XXX: canonicalize UTF-8
454 // XXX: lcase the domain part
458 function common_render_content($text, $notice)
460 $r = common_render_text($text);
461 $id = $notice->profile_id;
462 $r = common_linkify_mentions($r, $notice);
463 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
467 function common_linkify_mentions($text, $notice)
469 $mentions = common_find_mentions($text, $notice);
471 // We need to go through in reverse order by position,
472 // so our positions stay valid despite our fudging with the
477 foreach ($mentions as $mention)
479 $points[$mention['position']] = $mention;
484 foreach ($points as $position => $mention) {
486 $linkText = common_linkify_mention($mention);
488 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
494 function common_linkify_mention($mention)
498 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
500 $xs = new XMLStringer(false);
502 $attrs = array('href' => $mention['url'],
505 if (!empty($mention['title'])) {
506 $attrs['title'] = $mention['title'];
509 $xs->elementStart('span', 'vcard');
510 $xs->elementStart('a', $attrs);
511 $xs->element('span', 'fn nickname', $mention['text']);
512 $xs->elementEnd('a');
513 $xs->elementEnd('span');
515 $output = $xs->getString();
517 Event::handle('EndLinkifyMention', array($mention, &$output));
523 function common_find_mentions($text, $notice)
527 $sender = Profile::staticGet('id', $notice->profile_id);
529 if (empty($sender)) {
533 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
535 // Get the context of the original notice, if any
537 $originalAuthor = null;
538 $originalNotice = null;
539 $originalMentions = array();
543 if (!empty($notice) && !empty($notice->reply_to)) {
544 $originalNotice = Notice::staticGet('id', $notice->reply_to);
545 if (!empty($originalNotice)) {
546 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
548 $ids = $originalNotice->getReplies();
550 foreach ($ids as $id) {
551 $repliedTo = Profile::staticGet('id', $id);
552 if (!empty($repliedTo)) {
553 $originalMentions[$repliedTo->nickname] = $repliedTo;
559 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
562 PREG_OFFSET_CAPTURE);
564 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
567 PREG_OFFSET_CAPTURE);
569 $matches = array_merge($tmatches[1], $atmatches[1]);
571 foreach ($matches as $match) {
573 $nickname = common_canonical_nickname($match[0]);
575 // Try to get a profile for this nickname.
576 // Start with conversation context, then go to
579 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
581 $mentioned = $originalAuthor;
583 } else if (!empty($originalMentions) &&
584 array_key_exists($nickname, $originalMentions)) {
586 $mentioned = $originalMentions[$nickname];
588 $mentioned = common_relative_profile($sender, $nickname);
591 if (!empty($mentioned)) {
593 $user = User::staticGet('id', $mentioned->id);
596 $url = common_local_url('userbyid', array('id' => $user->id));
598 $url = $mentioned->profileurl;
601 $mention = array('mentioned' => array($mentioned),
603 'position' => $match[1],
606 if (!empty($mentioned->fullname)) {
607 $mention['title'] = $mentioned->fullname;
610 $mentions[] = $mention;
614 // @#tag => mention of all subscriptions tagged 'tag'
616 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
619 PREG_OFFSET_CAPTURE);
621 foreach ($hmatches[1] as $hmatch) {
623 $tag = common_canonical_tag($hmatch[0]);
625 $tagged = Profile_tag::getTagged($sender->id, $tag);
627 $url = common_local_url('subscriptions',
628 array('nickname' => $sender->nickname,
631 $mentions[] = array('mentioned' => $tagged,
632 'text' => $hmatch[0],
633 'position' => $hmatch[1],
637 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
643 function common_render_text($text)
645 $r = htmlspecialchars($text);
647 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
648 $r = common_replace_urls_callback($r, 'common_linkify');
649 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
654 function common_replace_urls_callback($text, $callback, $notice_id = null) {
655 // Start off with a regex
657 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
660 '(?:'. //Known protocols
662 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
664 '(?:(?:mailto|aim|tel|xmpp):)'.
666 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
669 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
671 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
675 '|(?:(?: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
677 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
679 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
680 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
681 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
682 '(?: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)'.
686 '(?:\:\d+)?'. //:port
687 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
688 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
689 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
690 ')(?<![\?\.\,\#\,])'.
693 //preg_match_all($regex,$text,$matches);
695 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
698 function callback_helper($matches, $callback, $notice_id) {
700 $left = strpos($matches[0],$url);
701 $right = $left+strlen($url);
703 $groupSymbolSets=array(
721 $cannotEndWith=array('.','?',',','#');
725 foreach($groupSymbolSets as $groupSymbolSet){
726 if(substr($url,-1)==$groupSymbolSet['right']){
727 $group_left_count = substr_count($url,$groupSymbolSet['left']);
728 $group_right_count = substr_count($url,$groupSymbolSet['right']);
729 if($group_left_count<$group_right_count){
731 $url=substr($url,0,-1);
735 if(in_array(substr($url,-1),$cannotEndWith)){
737 $url=substr($url,0,-1);
739 }while($original_url!=$url);
741 if(empty($notice_id)){
742 $result = call_user_func_array($callback, array($url));
744 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
746 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
749 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
750 // lambda implementation in a separate file; PHP 5.2 won't parse it.
751 require_once INSTALLDIR . "/lib/curry.php";
753 function curry($fn) {
754 $args = func_get_args();
756 $id = uniqid('_partial');
757 $GLOBALS[$id] = array($fn, $args);
758 return create_function('',
759 '$args = func_get_args(); '.
760 'return call_user_func_array('.
761 '$GLOBALS["'.$id.'"][0],'.
764 '$GLOBALS["'.$id.'"][1]));');
768 function common_linkify($url) {
769 // It comes in special'd, so we unspecial it before passing to the stringifying
771 $url = htmlspecialchars_decode($url);
773 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
774 //url is an email address without the mailto: protocol
775 $canon = "mailto:$url";
776 $longurl = "mailto:$url";
779 $canon = File_redirection::_canonUrl($url);
781 $longurl_data = File_redirection::where($canon);
782 if (is_array($longurl_data)) {
783 $longurl = $longurl_data['url'];
784 } elseif (is_string($longurl_data)) {
785 $longurl = $longurl_data;
787 throw new ServerException("Can't linkify url '$url'");
790 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
792 $is_attachment = false;
793 $attachment_id = null;
796 // Check to see whether this is a known "attachment" URL.
798 $f = File::staticGet('url', $longurl);
801 // XXX: this writes to the database. :<
802 $f = File::processNew($longurl);
806 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
807 $is_attachment = true;
808 $attachment_id = $f->id;
810 $thumb = File_thumbnail::staticGet('file_id', $f->id);
811 if (!empty($thumb)) {
818 if ($is_attachment) {
819 $attrs['class'] = 'attachment';
821 $attrs['class'] = 'attachment thumbnail';
823 $attrs['id'] = "attachment-{$attachment_id}";
826 return XMLStringer::estring('a', $attrs, $url);
829 function common_shorten_links($text)
831 common_debug("common_shorten_links() called");
833 $user = common_current_user();
835 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
837 common_debug("maxLength = $maxLength");
839 if (mb_strlen($text) > $maxLength) {
840 common_debug("Forcing shortening");
841 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'));
843 common_debug("Not forcing shortening");
844 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
848 function common_xml_safe_str($str)
850 // Replace common eol and extra whitespace input chars
855 "\0", // null byte eos
856 "\x0B" // vertical tab
859 $replacement = array(
867 $str = str_replace($unWelcome, $replacement, $str);
869 // Neutralize any additional control codes and UTF-16 surrogates
870 // (Twitter uses '*')
871 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
874 function common_tag_link($tag)
876 $canonical = common_canonical_tag($tag);
877 if (common_config('singleuser', 'enabled')) {
878 // regular TagAction isn't set up in 1user mode
879 $url = common_local_url('showstream',
880 array('nickname' => common_config('singleuser', 'nickname'),
881 'tag' => $canonical));
883 $url = common_local_url('tag', array('tag' => $canonical));
885 $xs = new XMLStringer();
886 $xs->elementStart('span', 'tag');
887 $xs->element('a', array('href' => $url,
890 $xs->elementEnd('span');
891 return $xs->getString();
894 function common_canonical_tag($tag)
896 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
897 return str_replace(array('-', '_', '.'), '', $tag);
900 function common_valid_profile_tag($str)
902 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
905 function common_group_link($sender_id, $nickname)
907 $sender = Profile::staticGet($sender_id);
908 $group = User_group::getForNickname($nickname, $sender);
909 if ($sender && $group && $sender->isMember($group)) {
910 $attrs = array('href' => $group->permalink(),
912 if (!empty($group->fullname)) {
913 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
915 $xs = new XMLStringer();
916 $xs->elementStart('span', 'vcard');
917 $xs->elementStart('a', $attrs);
918 $xs->element('span', 'fn nickname', $nickname);
919 $xs->elementEnd('a');
920 $xs->elementEnd('span');
921 return $xs->getString();
927 function common_relative_profile($sender, $nickname, $dt=null)
929 // Try to find profiles this profile is subscribed to that have this nickname
930 $recipient = new Profile();
931 // XXX: use a join instead of a subquery
932 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
933 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
934 if ($recipient->find(true)) {
935 // XXX: should probably differentiate between profiles with
936 // the same name by date of most recent update
939 // Try to find profiles that listen to this profile and that have this nickname
940 $recipient = new Profile();
941 // XXX: use a join instead of a subquery
942 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
943 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
944 if ($recipient->find(true)) {
945 // XXX: should probably differentiate between profiles with
946 // the same name by date of most recent update
949 // If this is a local user, try to find a local user with that nickname.
950 $sender = User::staticGet($sender->id);
952 $recipient_user = User::staticGet('nickname', $nickname);
953 if ($recipient_user) {
954 return $recipient_user->getProfile();
957 // Otherwise, no links. @messages from local users to remote users,
958 // or from remote users to other remote users, are just
959 // outside our ability to make intelligent guesses about
963 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
966 $path = $r->build($action, $args, $params, $fragment);
968 $ssl = common_is_sensitive($action);
970 if (common_config('site','fancy')) {
971 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
973 if (mb_strpos($path, '/index.php') === 0) {
974 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
976 $url = common_path('index.php'.$path, $ssl, $addSession);
982 function common_is_sensitive($action)
984 static $sensitive = array('login', 'register', 'passwordsettings',
985 'twittersettings', 'api');
988 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
989 $ssl = in_array($action, $sensitive);
995 function common_path($relative, $ssl=false, $addSession=true)
997 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
999 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1000 || common_config('site', 'ssl') === 'always') {
1002 if (is_string(common_config('site', 'sslserver')) &&
1003 mb_strlen(common_config('site', 'sslserver')) > 0) {
1004 $serverpart = common_config('site', 'sslserver');
1005 } else if (common_config('site', 'server')) {
1006 $serverpart = common_config('site', 'server');
1008 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1012 if (common_config('site', 'server')) {
1013 $serverpart = common_config('site', 'server');
1015 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1020 $relative = common_inject_session($relative, $serverpart);
1023 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1026 function common_inject_session($url, $serverpart = null)
1028 if (common_have_session()) {
1030 if (empty($serverpart)) {
1031 $serverpart = parse_url($url, PHP_URL_HOST);
1034 $currentServer = $_SERVER['HTTP_HOST'];
1036 // Are we pointing to another server (like an SSL server?)
1038 if (!empty($currentServer) &&
1039 0 != strcasecmp($currentServer, $serverpart)) {
1040 // Pass the session ID as a GET parameter
1041 $sesspart = session_name() . '=' . session_id();
1042 $i = strpos($url, '?');
1043 if ($i === false) { // no GET params, just append
1044 $url .= '?' . $sesspart;
1046 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1054 function common_date_string($dt)
1056 // XXX: do some sexy date formatting
1057 // return date(DATE_RFC822, $dt);
1058 $t = strtotime($dt);
1062 if ($now < $t) { // that shouldn't happen!
1063 return common_exact_date($dt);
1064 } else if ($diff < 60) {
1065 // TRANS: Used in notices to indicate when the notice was made compared to now.
1066 return _('a few seconds ago');
1067 } else if ($diff < 92) {
1068 // TRANS: Used in notices to indicate when the notice was made compared to now.
1069 return _('about a minute ago');
1070 } else if ($diff < 3300) {
1071 // XXX: should support plural.
1072 // TRANS: Used in notices to indicate when the notice was made compared to now.
1073 return sprintf(_('about %d minutes ago'), round($diff/60));
1074 } else if ($diff < 5400) {
1075 // TRANS: Used in notices to indicate when the notice was made compared to now.
1076 return _('about an hour ago');
1077 } else if ($diff < 22 * 3600) {
1078 // XXX: should support plural.
1079 // TRANS: Used in notices to indicate when the notice was made compared to now.
1080 return sprintf(_('about %d hours ago'), round($diff/3600));
1081 } else if ($diff < 37 * 3600) {
1082 // TRANS: Used in notices to indicate when the notice was made compared to now.
1083 return _('about a day ago');
1084 } else if ($diff < 24 * 24 * 3600) {
1085 // XXX: should support plural.
1086 // TRANS: Used in notices to indicate when the notice was made compared to now.
1087 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1088 } else if ($diff < 46 * 24 * 3600) {
1089 // TRANS: Used in notices to indicate when the notice was made compared to now.
1090 return _('about a month ago');
1091 } else if ($diff < 330 * 24 * 3600) {
1092 // XXX: should support plural.
1093 // TRANS: Used in notices to indicate when the notice was made compared to now.
1094 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1095 } else if ($diff < 480 * 24 * 3600) {
1096 // TRANS: Used in notices to indicate when the notice was made compared to now.
1097 return _('about a year ago');
1099 return common_exact_date($dt);
1103 function common_exact_date($dt)
1109 $_utc = new DateTimeZone('UTC');
1110 $_siteTz = new DateTimeZone(common_timezone());
1113 $dateStr = date('d F Y H:i:s', strtotime($dt));
1114 $d = new DateTime($dateStr, $_utc);
1115 $d->setTimezone($_siteTz);
1116 return $d->format(DATE_RFC850);
1119 function common_date_w3dtf($dt)
1121 $dateStr = date('d F Y H:i:s', strtotime($dt));
1122 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1123 $d->setTimezone(new DateTimeZone(common_timezone()));
1124 return $d->format(DATE_W3C);
1127 function common_date_rfc2822($dt)
1129 $dateStr = date('d F Y H:i:s', strtotime($dt));
1130 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1131 $d->setTimezone(new DateTimeZone(common_timezone()));
1132 return $d->format('r');
1135 function common_date_iso8601($dt)
1137 $dateStr = date('d F Y H:i:s', strtotime($dt));
1138 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1139 $d->setTimezone(new DateTimeZone(common_timezone()));
1140 return $d->format('c');
1143 function common_sql_now()
1145 return common_sql_date(time());
1148 function common_sql_date($datetime)
1150 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1154 * Return an SQL fragment to calculate an age-based weight from a given
1155 * timestamp or datetime column.
1157 * @param string $column name of field we're comparing against current time
1158 * @param integer $dropoff divisor for age in seconds before exponentiation
1159 * @return string SQL fragment
1161 function common_sql_weight($column, $dropoff)
1163 if (common_config('db', 'type') == 'pgsql') {
1164 // PostgreSQL doesn't support timestampdiff function.
1165 // @fixme will this use the right time zone?
1166 // @fixme does this handle cross-year subtraction correctly?
1167 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1169 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1173 function common_redirect($url, $code=307)
1175 static $status = array(301 => "Moved Permanently",
1178 307 => "Temporary Redirect");
1180 header('HTTP/1.1 '.$code.' '.$status[$code]);
1181 header("Location: $url");
1183 $xo = new XMLOutputter();
1185 '-//W3C//DTD XHTML 1.0 Strict//EN',
1186 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1187 $xo->element('a', array('href' => $url), $url);
1192 function common_broadcast_notice($notice, $remote=false)
1197 // Stick the notice on the queue
1199 function common_enqueue_notice($notice)
1201 static $localTransports = array('omb',
1204 $transports = array();
1205 if (common_config('sms', 'enabled')) {
1206 $transports[] = 'sms';
1208 if (Event::hasHandler('HandleQueuedNotice')) {
1209 $transports[] = 'plugin';
1212 // @fixme move these checks into QueueManager and/or individual handlers
1213 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1214 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1215 $transports = array_merge($transports, $localTransports);
1218 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1220 $qm = QueueManager::get();
1222 foreach ($transports as $transport)
1224 $qm->enqueue($notice, $transport);
1227 Event::handle('EndEnqueueNotice', array($notice, $transports));
1234 * Broadcast profile updates to OMB and other remote subscribers.
1236 * Since this may be slow with a lot of subscribers or bad remote sites,
1237 * this is run through the background queues if possible.
1239 function common_broadcast_profile(Profile $profile)
1241 $qm = QueueManager::get();
1242 $qm->enqueue($profile, "profile");
1246 function common_profile_url($nickname)
1248 return common_local_url('showstream', array('nickname' => $nickname),
1252 // Should make up a reasonable root URL
1254 function common_root_url($ssl=false)
1256 $url = common_path('', $ssl, false);
1257 $i = strpos($url, '?');
1259 $url = substr($url, 0, $i);
1264 // returns $bytes bytes of random data as a hexadecimal string
1265 // "good" here is a goal and not a guarantee
1267 function common_good_rand($bytes)
1269 // XXX: use random.org...?
1270 if (@file_exists('/dev/urandom')) {
1271 return common_urandom($bytes);
1272 } else { // FIXME: this is probably not good enough
1273 return common_mtrand($bytes);
1277 function common_urandom($bytes)
1279 $h = fopen('/dev/urandom', 'rb');
1281 $src = fread($h, $bytes);
1284 for ($i = 0; $i < $bytes; $i++) {
1285 $enc .= sprintf("%02x", (ord($src[$i])));
1290 function common_mtrand($bytes)
1293 for ($i = 0; $i < $bytes; $i++) {
1294 $enc .= sprintf("%02x", mt_rand(0, 255));
1300 * Record the given URL as the return destination for a future
1301 * form submission, to be read by common_get_returnto().
1303 * @param string $url
1305 * @fixme as a session-global setting, this can allow multiple forms
1306 * to conflict and overwrite each others' returnto destinations if
1307 * the user has multiple tabs or windows open.
1309 * Should refactor to index with a token or otherwise only pass the
1310 * data along its intended path.
1312 function common_set_returnto($url)
1314 common_ensure_session();
1315 $_SESSION['returnto'] = $url;
1319 * Fetch a return-destination URL previously recorded by
1320 * common_set_returnto().
1322 * @return mixed URL string or null
1324 * @fixme as a session-global setting, this can allow multiple forms
1325 * to conflict and overwrite each others' returnto destinations if
1326 * the user has multiple tabs or windows open.
1328 * Should refactor to index with a token or otherwise only pass the
1329 * data along its intended path.
1331 function common_get_returnto()
1333 common_ensure_session();
1334 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1337 function common_timestamp()
1339 return date('YmdHis');
1342 function common_ensure_syslog()
1344 static $initialized = false;
1345 if (!$initialized) {
1346 openlog(common_config('syslog', 'appname'), 0,
1347 common_config('syslog', 'facility'));
1348 $initialized = true;
1352 function common_log_line($priority, $msg)
1354 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1355 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1356 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1359 function common_request_id()
1362 $server = common_config('site', 'server');
1363 if (php_sapi_name() == 'cli') {
1364 $script = basename($_SERVER['PHP_SELF']);
1365 return "$server:$script:$pid";
1367 static $req_id = null;
1368 if (!isset($req_id)) {
1369 $req_id = substr(md5(mt_rand()), 0, 8);
1371 if (isset($_SERVER['REQUEST_URI'])) {
1372 $url = $_SERVER['REQUEST_URI'];
1374 $method = $_SERVER['REQUEST_METHOD'];
1375 return "$server:$pid.$req_id $method $url";
1379 function common_log($priority, $msg, $filename=null)
1381 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1382 $msg = '[' . common_request_id() . '] ' . $msg;
1383 $logfile = common_config('site', 'logfile');
1385 $log = fopen($logfile, "a");
1387 $output = common_log_line($priority, $msg);
1388 fwrite($log, $output);
1392 common_ensure_syslog();
1393 syslog($priority, $msg);
1395 Event::handle('EndLog', array($priority, $msg, $filename));
1399 function common_debug($msg, $filename=null)
1402 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1404 common_log(LOG_DEBUG, $msg);
1408 function common_log_db_error(&$object, $verb, $filename=null)
1410 $objstr = common_log_objstring($object);
1411 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1412 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1415 function common_log_objstring(&$object)
1417 if (is_null($object)) {
1420 if (!($object instanceof DB_DataObject)) {
1423 $arr = $object->toArray();
1425 foreach ($arr as $k => $v) {
1426 if (is_object($v)) {
1427 $fields[] = "$k='".get_class($v)."'";
1429 $fields[] = "$k='$v'";
1432 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1436 function common_valid_http_url($url)
1438 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1441 function common_valid_tag($tag)
1443 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1444 return (Validate::email($matches[1]) ||
1445 preg_match('/^([\w-\.]+)$/', $matches[1]));
1451 * Determine if given domain or address literal is valid
1452 * eg for use in JIDs and URLs. Does not check if the domain
1455 * @param string $domain
1456 * @return boolean valid or not
1458 function common_valid_domain($domain)
1460 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1461 $ipv4 = "(?:$octet(?:\.$octet){3})";
1462 if (preg_match("/^$ipv4$/u", $domain)) return true;
1464 $group = "(?:[0-9a-f]{1,4})";
1465 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1467 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1468 $before = explode(":", $matches[1]);
1469 $zeroes = $matches[2];
1470 $after = explode(":", $matches[3]);
1478 $explicit = count($before) + count($after);
1479 if ($explicit < $min || $explicit > $max) {
1486 require_once "Net/IDNA.php";
1487 $idn = Net_IDNA::getInstance();
1488 $domain = $idn->encode($domain);
1489 } catch (Exception $e) {
1493 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1494 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1496 return preg_match("/^$fqdn$/ui", $domain);
1499 /* Following functions are copied from MediaWiki GlobalFunctions.php
1500 * and written by Evan Prodromou. */
1502 function common_accept_to_prefs($accept, $def = '*/*')
1504 // No arg means accept anything (per HTTP spec)
1506 return array($def => 1);
1511 $parts = explode(',', $accept);
1513 foreach($parts as $part) {
1514 // FIXME: doesn't deal with params like 'text/html; level=1'
1515 @list($value, $qpart) = explode(';', trim($part));
1517 if(!isset($qpart)) {
1519 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1520 $prefs[$value] = $match[1];
1527 function common_mime_type_match($type, $avail)
1529 if(array_key_exists($type, $avail)) {
1532 $parts = explode('/', $type);
1533 if(array_key_exists($parts[0] . '/*', $avail)) {
1534 return $parts[0] . '/*';
1535 } elseif(array_key_exists('*/*', $avail)) {
1543 function common_negotiate_type($cprefs, $sprefs)
1547 foreach(array_keys($sprefs) as $type) {
1548 $parts = explode('/', $type);
1549 if($parts[1] != '*') {
1550 $ckey = common_mime_type_match($type, $cprefs);
1552 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1557 foreach(array_keys($cprefs) as $type) {
1558 $parts = explode('/', $type);
1559 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1560 $skey = common_mime_type_match($type, $sprefs);
1562 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1568 $besttype = 'text/html';
1570 foreach(array_keys($combine) as $type) {
1571 if($combine[$type] > $bestq) {
1573 $bestq = $combine[$type];
1577 if ('text/html' === $besttype) {
1578 return "text/html; charset=utf-8";
1583 function common_config($main, $sub)
1586 return (array_key_exists($main, $config) &&
1587 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1590 function common_copy_args($from)
1593 $strip = get_magic_quotes_gpc();
1594 foreach ($from as $k => $v) {
1597 $to[$k] = common_copy_args($v);
1599 $to[$k] = stripslashes($v);
1609 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1610 * This is used before handing a request off to OAuthRequest::from_request.
1611 * @fixme Doesn't consider vars other than _POST and _GET?
1612 * @fixme Can't be undone and could corrupt data if run twice.
1614 function common_remove_magic_from_request()
1616 if(get_magic_quotes_gpc()) {
1617 $_POST=array_map('stripslashes',$_POST);
1618 $_GET=array_map('stripslashes',$_GET);
1622 function common_user_uri(&$user)
1624 return common_local_url('userbyid', array('id' => $user->id),
1628 function common_notice_uri(&$notice)
1630 return common_local_url('shownotice',
1631 array('notice' => $notice->id),
1635 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1637 function common_confirmation_code($bits)
1639 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1640 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1641 $chars = ceil($bits/5);
1643 for ($i = 0; $i < $chars; $i++) {
1644 // XXX: convert to string and back
1645 $num = hexdec(common_good_rand(1));
1646 // XXX: randomness is too precious to throw away almost
1647 // 40% of the bits we get!
1648 $code .= $codechars[$num%32];
1653 // convert markup to HTML
1655 function common_markup_to_html($c)
1657 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1658 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1659 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1660 return Markdown($c);
1663 function common_profile_uri($profile)
1668 $user = User::staticGet($profile->id);
1673 $remote = Remote_profile::staticGet($profile->id);
1675 return $remote->uri;
1677 // XXX: this is a very bad profile!
1681 function common_canonical_sms($sms)
1684 preg_replace('/\D/', '', $sms);
1688 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1693 case E_COMPILE_ERROR:
1697 case E_RECOVERABLE_ERROR:
1698 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1703 case E_COMPILE_WARNING:
1704 case E_CORE_WARNING:
1705 case E_USER_WARNING:
1706 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1711 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1716 case E_USER_DEPRECATED:
1717 // XXX: config variable to log this stuff, too
1721 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1726 // FIXME: show error page if we're on the Web
1727 /* Don't execute PHP internal error handler */
1731 function common_session_token()
1733 common_ensure_session();
1734 if (!array_key_exists('token', $_SESSION)) {
1735 $_SESSION['token'] = common_good_rand(64);
1737 return $_SESSION['token'];
1740 function common_cache_key($extra)
1742 return Cache::key($extra);
1745 function common_keyize($str)
1747 return Cache::keyize($str);
1750 function common_memcache()
1752 return Cache::instance();
1755 function common_license_terms($uri)
1757 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1758 return explode('-',$matches[1]);
1763 function common_compatible_license($from, $to)
1765 $from_terms = common_license_terms($from);
1766 // public domain and cc-by are compatible with everything
1767 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1770 $to_terms = common_license_terms($to);
1771 // sa is compatible across versions. IANAL
1772 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1773 return count(array_diff($from_terms, $to_terms)) == 0;
1775 // XXX: better compatibility check needed here!
1776 // Should at least normalise URIs
1777 return ($from == $to);
1781 * returns a quoted table name, if required according to config
1783 function common_database_tablename($tablename)
1786 if(common_config('db','quote_identifiers')) {
1787 $tablename = '"'. $tablename .'"';
1789 //table prefixes could be added here later
1794 * Shorten a URL with the current user's configured shortening service,
1795 * or ur1.ca if configured, or not at all if no shortening is set up.
1797 * @param string $long_url original URL
1798 * @param boolean $force Force shortening (used when notice is too long)
1800 * @return string may return the original URL if shortening failed
1802 * @fixme provide a way to specify a particular shortener
1803 * @fixme provide a way to specify to use a given user's shortening preferences
1806 function common_shorten_url($long_url, $force = false)
1808 common_debug("Shortening URL '$long_url' (force = $force)");
1810 $long_url = trim($long_url);
1812 $user = common_current_user();
1814 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
1815 common_debug("maxUrlLength = $maxUrlLength");
1817 // $force forces shortening even if it's not strictly needed
1819 if (mb_strlen($long_url) < $maxUrlLength && !$force) {
1820 common_debug("Skipped shortening URL.");
1824 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
1826 common_debug("Shortener name = '$shortenerName'");
1828 if (Event::handle('StartShortenUrl', array($long_url, $shortenerName, &$shortenedUrl))) {
1829 //URL wasn't shortened, so return the long url
1832 //URL was shortened, so return the result
1833 return trim($shortenedUrl);
1838 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1839 * null if not a web request
1841 * @fixme X-Forwarded-For can be chained by multiple proxies;
1842 we should parse the list and provide a cleaner array
1843 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1844 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1845 * use function to get exact request headers from Apache if possible.
1847 function common_client_ip()
1849 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1853 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1854 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1855 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1857 $proxy = $_SERVER['REMOTE_ADDR'];
1859 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1862 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1863 $ip = $_SERVER['HTTP_CLIENT_IP'];
1865 $ip = $_SERVER['REMOTE_ADDR'];
1869 return array($proxy, $ip);
1872 function common_url_to_nickname($url)
1874 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1876 $parts = parse_url($url);
1878 # If any of these parts exist, this won't work
1880 foreach ($bad as $badpart) {
1881 if (array_key_exists($badpart, $parts)) {
1886 # We just have host and/or path
1888 # If it's just a host...
1889 if (array_key_exists('host', $parts) &&
1890 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1892 $hostparts = explode('.', $parts['host']);
1894 # Try to catch common idiom of nickname.service.tld
1896 if ((count($hostparts) > 2) &&
1897 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1898 (strcmp($hostparts[0], 'www') != 0))
1900 return common_nicknamize($hostparts[0]);
1902 # Do the whole hostname
1903 return common_nicknamize($parts['host']);
1906 if (array_key_exists('path', $parts)) {
1907 # Strip starting, ending slashes
1908 $path = preg_replace('@/$@', '', $parts['path']);
1909 $path = preg_replace('@^/@', '', $path);
1910 $path = basename($path);
1912 return common_nicknamize($path);
1920 function common_nicknamize($str)
1922 $str = preg_replace('/\W/', '', $str);
1923 return strtolower($str);