3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, user, files) */
22 // Show a server error
24 function common_server_error($msg, $code=500)
26 $err = new ServerErrorAction($msg, $code);
31 function common_user_error($msg, $code=400)
33 $err = new ClientErrorAction($msg, $code);
38 * This should only be used at setup; processes switching languages
39 * to send text to other users should use common_switch_locale().
41 * @param string $language Locale language code (optional; empty uses
42 * current user's preference or site default)
43 * @return mixed success
45 function common_init_locale($language=null)
48 $language = common_language();
50 putenv('LANGUAGE='.$language);
51 putenv('LANG='.$language);
52 $ok = setlocale(LC_ALL, $language . ".utf8",
62 * Initialize locale and charset settings and gettext with our message catalog,
63 * using the current user's language preference or the site default.
65 * This should generally only be run at framework initialization; code switching
66 * languages at runtime should call common_switch_language().
70 function common_init_language()
72 mb_internal_encoding('UTF-8');
74 // Note that this setlocale() call may "fail" but this is harmless;
75 // gettext will still select the right language.
76 $language = common_language();
77 $locale_set = common_init_locale($language);
80 // The requested locale doesn't exist on the system.
82 // gettext seems very picky... We first need to setlocale()
83 // to a locale which _does_ exist on the system, and _then_
84 // we can set in another locale that may not be set up
85 // (say, ga_ES for Galego/Galician) it seems to take it.
87 // For some reason C and POSIX which are guaranteed to work
88 // don't do the job. en_US.UTF-8 should be there most of the
89 // time, but not guaranteed.
90 $ok = common_init_locale("en_US");
91 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
92 // Try to find a complete, working locale on Unix/Linux...
93 // @fixme shelling out feels awfully inefficient
94 // but I don't think there's a more standard way.
96 foreach (explode("\n", $all) as $locale) {
97 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
98 $ok = setlocale(LC_ALL, $locale);
106 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
108 $locale_set = common_init_locale($language);
111 common_init_gettext();
117 function common_init_gettext()
119 setlocale(LC_CTYPE, 'C');
120 // So we do not have to make people install the gettext locales
121 $path = common_config('site','locale_path');
122 bindtextdomain("statusnet", $path);
123 bind_textdomain_codeset("statusnet", "UTF-8");
124 textdomain("statusnet");
128 * Switch locale during runtime, and poke gettext until it cries uncle.
129 * Otherwise, sometimes it doesn't actually switch away from the old language.
131 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
133 function common_switch_locale($language=null)
135 common_init_locale($language);
137 setlocale(LC_CTYPE, 'C');
138 // So we do not have to make people install the gettext locales
139 $path = common_config('site','locale_path');
140 bindtextdomain("statusnet", $path);
141 bind_textdomain_codeset("statusnet", "UTF-8");
142 textdomain("statusnet");
146 function common_timezone()
148 if (common_logged_in()) {
149 $user = common_current_user();
150 if ($user->timezone) {
151 return $user->timezone;
155 return common_config('site', 'timezone');
158 function common_language()
161 // If there is a user logged in and they've set a language preference
162 // then return that one...
163 if (_have_config() && common_logged_in()) {
164 $user = common_current_user();
165 $user_language = $user->language;
167 if ($user->language) {
168 // Validate -- we don't want to end up with a bogus code
169 // left over from some old junk.
170 foreach (common_config('site', 'languages') as $code => $info) {
171 if ($info['lang'] == $user_language) {
172 return $user_language;
178 // Otherwise, find the best match for the languages requested by the
180 if (common_config('site', 'langdetect')) {
181 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
182 if (!empty($httplang)) {
183 $language = client_prefered_language($httplang);
189 // Finally, if none of the above worked, use the site's default...
190 return common_config('site', 'language');
192 // salted, hashed passwords are stored in the DB
194 function common_munge_password($password, $id)
196 if (is_object($id) || is_object($password)) {
197 $e = new Exception();
198 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
199 str_replace("\n", " ", $e->getTraceAsString()));
201 return md5($password . $id);
204 // check if a username exists and has matching password
206 function common_check_user($nickname, $password)
208 // empty nickname always unacceptable
209 if (empty($nickname)) {
213 $authenticatedUser = false;
215 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
216 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
218 if (!empty($password)) { // never allow login with blank password
219 if (0 == strcmp(common_munge_password($password, $user->id),
221 //internal checking passed
222 $authenticatedUser = $user;
226 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
229 return $authenticatedUser;
232 // is the current user logged in?
233 function common_logged_in()
235 return (!is_null(common_current_user()));
238 function common_have_session()
240 return (0 != strcmp(session_id(), ''));
243 function common_ensure_session()
246 if (array_key_exists(session_name(), $_COOKIE)) {
247 $c = $_COOKIE[session_name()];
249 if (!common_have_session()) {
250 if (common_config('sessions', 'handle')) {
251 Session::setSaveHandler();
253 if (array_key_exists(session_name(), $_GET)) {
254 $id = $_GET[session_name()];
255 } else if (array_key_exists(session_name(), $_COOKIE)) {
256 $id = $_COOKIE[session_name()];
262 if (!isset($_SESSION['started'])) {
263 $_SESSION['started'] = time();
265 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
266 ' is set but started value is null');
272 // Three kinds of arguments:
277 // Initialize to false; set to null if none found
281 function common_set_user($user)
286 if (is_null($user) && common_have_session()) {
288 unset($_SESSION['userid']);
290 } else if (is_string($user)) {
292 $user = User::staticGet('nickname', $nickname);
293 } else if (!($user instanceof User)) {
298 if (Event::handle('StartSetUser', array(&$user))) {
300 common_ensure_session();
301 $_SESSION['userid'] = $user->id;
303 Event::handle('EndSetUser', array($user));
311 function common_set_cookie($key, $value, $expiration=0)
313 $path = common_config('site', 'path');
314 $server = common_config('site', 'server');
316 if ($path && ($path != '/')) {
317 $cookiepath = '/' . $path . '/';
321 return setcookie($key,
328 define('REMEMBERME', 'rememberme');
329 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
331 function common_rememberme($user=null)
334 $user = common_current_user();
340 $rm = new Remember_me();
342 $rm->code = common_good_rand(16);
343 $rm->user_id = $user->id;
345 // Wrap the insert in some good ol' fashioned transaction code
349 $result = $rm->insert();
352 common_log_db_error($rm, 'INSERT', __FILE__);
356 $rm->query('COMMIT');
358 $cookieval = $rm->user_id . ':' . $rm->code;
360 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
362 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
367 function common_remembered_user()
372 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
378 list($id, $code) = explode(':', $packed);
380 if (!$id || !$code) {
381 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
386 $rm = Remember_me::staticGet($code);
389 common_log(LOG_WARNING, 'No such remember code: ' . $code);
394 if ($rm->user_id != $id) {
395 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
400 $user = User::staticGet($rm->user_id);
403 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
409 $result = $rm->delete();
412 common_log_db_error($rm, 'DELETE', __FILE__);
413 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
418 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
420 common_set_user($user);
421 common_real_login(false);
423 // We issue a new cookie, so they can log in
424 // automatically again after this session
426 common_rememberme($user);
431 // must be called with a valid user!
433 function common_forgetme()
435 common_set_cookie(REMEMBERME, '', 0);
438 // who is the current user?
439 function common_current_user()
443 if (!_have_config()) {
447 if ($_cur === false) {
449 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
450 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
451 common_ensure_session();
452 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
454 $user = User::staticGet($id);
462 // that didn't work; try to remember; will init $_cur to null on failure
463 $_cur = common_remembered_user();
466 // XXX: Is this necessary?
467 $_SESSION['userid'] = $_cur->id;
474 // Logins that are 'remembered' aren't 'real' -- they're subject to
475 // cookie-stealing. So, we don't let them do certain things. New reg,
476 // OpenID, and password logins _are_ real.
478 function common_real_login($real=true)
480 common_ensure_session();
481 $_SESSION['real_login'] = $real;
484 function common_is_real_login()
486 return common_logged_in() && $_SESSION['real_login'];
489 // get canonical version of nickname for comparison
490 function common_canonical_nickname($nickname)
492 // XXX: UTF-8 canonicalization (like combining chars)
493 return strtolower($nickname);
496 // get canonical version of email for comparison
497 function common_canonical_email($email)
499 // XXX: canonicalize UTF-8
500 // XXX: lcase the domain part
504 function common_render_content($text, $notice)
506 $r = common_render_text($text);
507 $id = $notice->profile_id;
508 $r = common_linkify_mentions($r, $notice);
509 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
513 function common_linkify_mentions($text, $notice)
515 $mentions = common_find_mentions($text, $notice);
517 // We need to go through in reverse order by position,
518 // so our positions stay valid despite our fudging with the
523 foreach ($mentions as $mention)
525 $points[$mention['position']] = $mention;
530 foreach ($points as $position => $mention) {
532 $linkText = common_linkify_mention($mention);
534 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
540 function common_linkify_mention($mention)
544 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
546 $xs = new XMLStringer(false);
548 $attrs = array('href' => $mention['url'],
551 if (!empty($mention['title'])) {
552 $attrs['title'] = $mention['title'];
555 $xs->elementStart('span', 'vcard');
556 $xs->elementStart('a', $attrs);
557 $xs->element('span', 'fn nickname', $mention['text']);
558 $xs->elementEnd('a');
559 $xs->elementEnd('span');
561 $output = $xs->getString();
563 Event::handle('EndLinkifyMention', array($mention, &$output));
569 function common_find_mentions($text, $notice)
573 $sender = Profile::staticGet('id', $notice->profile_id);
575 if (empty($sender)) {
579 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
581 // Get the context of the original notice, if any
583 $originalAuthor = null;
584 $originalNotice = null;
585 $originalMentions = array();
589 if (!empty($notice) && !empty($notice->reply_to)) {
590 $originalNotice = Notice::staticGet('id', $notice->reply_to);
591 if (!empty($originalNotice)) {
592 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
594 $ids = $originalNotice->getReplies();
596 foreach ($ids as $id) {
597 $repliedTo = Profile::staticGet('id', $id);
598 if (!empty($repliedTo)) {
599 $originalMentions[$repliedTo->nickname] = $repliedTo;
605 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
608 PREG_OFFSET_CAPTURE);
610 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
613 PREG_OFFSET_CAPTURE);
615 $matches = array_merge($tmatches[1], $atmatches[1]);
617 foreach ($matches as $match) {
619 $nickname = common_canonical_nickname($match[0]);
621 // Try to get a profile for this nickname.
622 // Start with conversation context, then go to
625 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
627 $mentioned = $originalAuthor;
629 } else if (!empty($originalMentions) &&
630 array_key_exists($nickname, $originalMentions)) {
632 $mentioned = $originalMentions[$nickname];
634 $mentioned = common_relative_profile($sender, $nickname);
637 if (!empty($mentioned)) {
639 $user = User::staticGet('id', $mentioned->id);
642 $url = common_local_url('userbyid', array('id' => $user->id));
644 $url = $mentioned->profileurl;
647 $mention = array('mentioned' => array($mentioned),
649 'position' => $match[1],
652 if (!empty($mentioned->fullname)) {
653 $mention['title'] = $mentioned->fullname;
656 $mentions[] = $mention;
660 // @#tag => mention of all subscriptions tagged 'tag'
662 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
665 PREG_OFFSET_CAPTURE);
667 foreach ($hmatches[1] as $hmatch) {
669 $tag = common_canonical_tag($hmatch[0]);
671 $tagged = Profile_tag::getTagged($sender->id, $tag);
673 $url = common_local_url('subscriptions',
674 array('nickname' => $sender->nickname,
677 $mentions[] = array('mentioned' => $tagged,
678 'text' => $hmatch[0],
679 'position' => $hmatch[1],
683 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
689 function common_render_text($text)
691 $r = htmlspecialchars($text);
693 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
694 $r = common_replace_urls_callback($r, 'common_linkify');
695 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
700 function common_replace_urls_callback($text, $callback, $notice_id = null) {
701 // Start off with a regex
703 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
706 '(?:'. //Known protocols
708 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
710 '(?:(?:mailto|aim|tel|xmpp):)'.
712 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
715 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
717 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
721 '|(?:(?: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
723 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
725 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
726 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
727 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
728 '(?: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)'.
732 '(?:\:\d+)?'. //:port
733 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
734 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
735 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
736 ')(?<![\?\.\,\#\,])'.
739 //preg_match_all($regex,$text,$matches);
741 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
744 function callback_helper($matches, $callback, $notice_id) {
746 $left = strpos($matches[0],$url);
747 $right = $left+strlen($url);
749 $groupSymbolSets=array(
767 $cannotEndWith=array('.','?',',','#');
771 foreach($groupSymbolSets as $groupSymbolSet){
772 if(substr($url,-1)==$groupSymbolSet['right']){
773 $group_left_count = substr_count($url,$groupSymbolSet['left']);
774 $group_right_count = substr_count($url,$groupSymbolSet['right']);
775 if($group_left_count<$group_right_count){
777 $url=substr($url,0,-1);
781 if(in_array(substr($url,-1),$cannotEndWith)){
783 $url=substr($url,0,-1);
785 }while($original_url!=$url);
787 if(empty($notice_id)){
788 $result = call_user_func_array($callback, array($url));
790 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
792 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
795 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
796 // lambda implementation in a separate file; PHP 5.2 won't parse it.
797 require_once INSTALLDIR . "/lib/curry.php";
799 function curry($fn) {
800 $args = func_get_args();
802 $id = uniqid('_partial');
803 $GLOBALS[$id] = array($fn, $args);
804 return create_function('',
805 '$args = func_get_args(); '.
806 'return call_user_func_array('.
807 '$GLOBALS["'.$id.'"][0],'.
810 '$GLOBALS["'.$id.'"][1]));');
814 function common_linkify($url) {
815 // It comes in special'd, so we unspecial it before passing to the stringifying
817 $url = htmlspecialchars_decode($url);
819 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
820 //url is an email address without the mailto: protocol
821 $canon = "mailto:$url";
822 $longurl = "mailto:$url";
825 $canon = File_redirection::_canonUrl($url);
827 $longurl_data = File_redirection::where($canon);
828 if (is_array($longurl_data)) {
829 $longurl = $longurl_data['url'];
830 } elseif (is_string($longurl_data)) {
831 $longurl = $longurl_data;
833 throw new ServerException("Can't linkify url '$url'");
836 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
838 $is_attachment = false;
839 $attachment_id = null;
842 // Check to see whether this is a known "attachment" URL.
844 $f = File::staticGet('url', $longurl);
847 // XXX: this writes to the database. :<
848 $f = File::processNew($longurl);
852 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
853 $is_attachment = true;
854 $attachment_id = $f->id;
856 $thumb = File_thumbnail::staticGet('file_id', $f->id);
857 if (!empty($thumb)) {
864 if ($is_attachment) {
865 $attrs['class'] = 'attachment';
867 $attrs['class'] = 'attachment thumbnail';
869 $attrs['id'] = "attachment-{$attachment_id}";
872 return XMLStringer::estring('a', $attrs, $url);
875 function common_shorten_links($text, $always = false)
877 $maxLength = Notice::maxContent();
878 if (!$always && ($maxLength == 0 || mb_strlen($text) <= $maxLength)) return $text;
879 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
882 function common_xml_safe_str($str)
884 // Replace common eol and extra whitespace input chars
889 "\0", // null byte eos
890 "\x0B" // vertical tab
893 $replacement = array(
901 $str = str_replace($unWelcome, $replacement, $str);
903 // Neutralize any additional control codes and UTF-16 surrogates
904 // (Twitter uses '*')
905 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
908 function common_tag_link($tag)
910 $canonical = common_canonical_tag($tag);
911 if (common_config('singleuser', 'enabled')) {
912 // regular TagAction isn't set up in 1user mode
913 $url = common_local_url('showstream',
914 array('nickname' => common_config('singleuser', 'nickname'),
915 'tag' => $canonical));
917 $url = common_local_url('tag', array('tag' => $canonical));
919 $xs = new XMLStringer();
920 $xs->elementStart('span', 'tag');
921 $xs->element('a', array('href' => $url,
924 $xs->elementEnd('span');
925 return $xs->getString();
928 function common_canonical_tag($tag)
930 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
931 return str_replace(array('-', '_', '.'), '', $tag);
934 function common_valid_profile_tag($str)
936 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
939 function common_group_link($sender_id, $nickname)
941 $sender = Profile::staticGet($sender_id);
942 $group = User_group::getForNickname($nickname, $sender);
943 if ($sender && $group && $sender->isMember($group)) {
944 $attrs = array('href' => $group->permalink(),
946 if (!empty($group->fullname)) {
947 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
949 $xs = new XMLStringer();
950 $xs->elementStart('span', 'vcard');
951 $xs->elementStart('a', $attrs);
952 $xs->element('span', 'fn nickname', $nickname);
953 $xs->elementEnd('a');
954 $xs->elementEnd('span');
955 return $xs->getString();
961 function common_relative_profile($sender, $nickname, $dt=null)
963 // Try to find profiles this profile is subscribed to that have this nickname
964 $recipient = new Profile();
965 // XXX: use a join instead of a subquery
966 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
967 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
968 if ($recipient->find(true)) {
969 // XXX: should probably differentiate between profiles with
970 // the same name by date of most recent update
973 // Try to find profiles that listen to this profile and that have this nickname
974 $recipient = new Profile();
975 // XXX: use a join instead of a subquery
976 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
977 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
978 if ($recipient->find(true)) {
979 // XXX: should probably differentiate between profiles with
980 // the same name by date of most recent update
983 // If this is a local user, try to find a local user with that nickname.
984 $sender = User::staticGet($sender->id);
986 $recipient_user = User::staticGet('nickname', $nickname);
987 if ($recipient_user) {
988 return $recipient_user->getProfile();
991 // Otherwise, no links. @messages from local users to remote users,
992 // or from remote users to other remote users, are just
993 // outside our ability to make intelligent guesses about
997 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1000 $path = $r->build($action, $args, $params, $fragment);
1002 $ssl = common_is_sensitive($action);
1004 if (common_config('site','fancy')) {
1005 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1007 if (mb_strpos($path, '/index.php') === 0) {
1008 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1010 $url = common_path('index.php'.$path, $ssl, $addSession);
1016 function common_is_sensitive($action)
1018 static $sensitive = array('login', 'register', 'passwordsettings',
1019 'twittersettings', 'api');
1022 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1023 $ssl = in_array($action, $sensitive);
1029 function common_path($relative, $ssl=false, $addSession=true)
1031 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1033 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1034 || common_config('site', 'ssl') === 'always') {
1036 if (is_string(common_config('site', 'sslserver')) &&
1037 mb_strlen(common_config('site', 'sslserver')) > 0) {
1038 $serverpart = common_config('site', 'sslserver');
1039 } else if (common_config('site', 'server')) {
1040 $serverpart = common_config('site', 'server');
1042 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1046 if (common_config('site', 'server')) {
1047 $serverpart = common_config('site', 'server');
1049 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1054 $relative = common_inject_session($relative, $serverpart);
1057 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1060 function common_inject_session($url, $serverpart = null)
1062 if (common_have_session()) {
1064 if (empty($serverpart)) {
1065 $serverpart = parse_url($url, PHP_URL_HOST);
1068 $currentServer = $_SERVER['HTTP_HOST'];
1070 // Are we pointing to another server (like an SSL server?)
1072 if (!empty($currentServer) &&
1073 0 != strcasecmp($currentServer, $serverpart)) {
1074 // Pass the session ID as a GET parameter
1075 $sesspart = session_name() . '=' . session_id();
1076 $i = strpos($url, '?');
1077 if ($i === false) { // no GET params, just append
1078 $url .= '?' . $sesspart;
1080 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1088 function common_date_string($dt)
1090 // XXX: do some sexy date formatting
1091 // return date(DATE_RFC822, $dt);
1092 $t = strtotime($dt);
1096 if ($now < $t) { // that shouldn't happen!
1097 return common_exact_date($dt);
1098 } else if ($diff < 60) {
1099 // TRANS: Used in notices to indicate when the notice was made compared to now.
1100 return _('a few seconds ago');
1101 } else if ($diff < 92) {
1102 // TRANS: Used in notices to indicate when the notice was made compared to now.
1103 return _('about a minute ago');
1104 } else if ($diff < 3300) {
1105 // XXX: should support plural.
1106 // TRANS: Used in notices to indicate when the notice was made compared to now.
1107 return sprintf(_('about %d minutes ago'), round($diff/60));
1108 } else if ($diff < 5400) {
1109 // TRANS: Used in notices to indicate when the notice was made compared to now.
1110 return _('about an hour ago');
1111 } else if ($diff < 22 * 3600) {
1112 // XXX: should support plural.
1113 // TRANS: Used in notices to indicate when the notice was made compared to now.
1114 return sprintf(_('about %d hours ago'), round($diff/3600));
1115 } else if ($diff < 37 * 3600) {
1116 // TRANS: Used in notices to indicate when the notice was made compared to now.
1117 return _('about a day ago');
1118 } else if ($diff < 24 * 24 * 3600) {
1119 // XXX: should support plural.
1120 // TRANS: Used in notices to indicate when the notice was made compared to now.
1121 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1122 } else if ($diff < 46 * 24 * 3600) {
1123 // TRANS: Used in notices to indicate when the notice was made compared to now.
1124 return _('about a month ago');
1125 } else if ($diff < 330 * 24 * 3600) {
1126 // XXX: should support plural.
1127 // TRANS: Used in notices to indicate when the notice was made compared to now.
1128 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1129 } else if ($diff < 480 * 24 * 3600) {
1130 // TRANS: Used in notices to indicate when the notice was made compared to now.
1131 return _('about a year ago');
1133 return common_exact_date($dt);
1137 function common_exact_date($dt)
1143 $_utc = new DateTimeZone('UTC');
1144 $_siteTz = new DateTimeZone(common_timezone());
1147 $dateStr = date('d F Y H:i:s', strtotime($dt));
1148 $d = new DateTime($dateStr, $_utc);
1149 $d->setTimezone($_siteTz);
1150 return $d->format(DATE_RFC850);
1153 function common_date_w3dtf($dt)
1155 $dateStr = date('d F Y H:i:s', strtotime($dt));
1156 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1157 $d->setTimezone(new DateTimeZone(common_timezone()));
1158 return $d->format(DATE_W3C);
1161 function common_date_rfc2822($dt)
1163 $dateStr = date('d F Y H:i:s', strtotime($dt));
1164 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1165 $d->setTimezone(new DateTimeZone(common_timezone()));
1166 return $d->format('r');
1169 function common_date_iso8601($dt)
1171 $dateStr = date('d F Y H:i:s', strtotime($dt));
1172 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1173 $d->setTimezone(new DateTimeZone(common_timezone()));
1174 return $d->format('c');
1177 function common_sql_now()
1179 return common_sql_date(time());
1182 function common_sql_date($datetime)
1184 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1188 * Return an SQL fragment to calculate an age-based weight from a given
1189 * timestamp or datetime column.
1191 * @param string $column name of field we're comparing against current time
1192 * @param integer $dropoff divisor for age in seconds before exponentiation
1193 * @return string SQL fragment
1195 function common_sql_weight($column, $dropoff)
1197 if (common_config('db', 'type') == 'pgsql') {
1198 // PostgreSQL doesn't support timestampdiff function.
1199 // @fixme will this use the right time zone?
1200 // @fixme does this handle cross-year subtraction correctly?
1201 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1203 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1207 function common_redirect($url, $code=307)
1209 static $status = array(301 => "Moved Permanently",
1212 307 => "Temporary Redirect");
1214 header('HTTP/1.1 '.$code.' '.$status[$code]);
1215 header("Location: $url");
1217 $xo = new XMLOutputter();
1219 '-//W3C//DTD XHTML 1.0 Strict//EN',
1220 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1221 $xo->element('a', array('href' => $url), $url);
1226 function common_broadcast_notice($notice, $remote=false)
1231 // Stick the notice on the queue
1233 function common_enqueue_notice($notice)
1235 static $localTransports = array('omb',
1238 $transports = array();
1239 if (common_config('sms', 'enabled')) {
1240 $transports[] = 'sms';
1242 if (Event::hasHandler('HandleQueuedNotice')) {
1243 $transports[] = 'plugin';
1246 $xmpp = common_config('xmpp', 'enabled');
1249 $transports[] = 'jabber';
1252 // We can skip these for gatewayed notices.
1253 if ($notice->isLocal()) {
1254 $transports = array_merge($transports, $localTransports);
1256 $transports[] = 'public';
1260 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1262 $qm = QueueManager::get();
1264 foreach ($transports as $transport)
1266 $qm->enqueue($notice, $transport);
1269 Event::handle('EndEnqueueNotice', array($notice, $transports));
1276 * Broadcast profile updates to OMB and other remote subscribers.
1278 * Since this may be slow with a lot of subscribers or bad remote sites,
1279 * this is run through the background queues if possible.
1281 function common_broadcast_profile(Profile $profile)
1283 $qm = QueueManager::get();
1284 $qm->enqueue($profile, "profile");
1288 function common_profile_url($nickname)
1290 return common_local_url('showstream', array('nickname' => $nickname),
1294 // Should make up a reasonable root URL
1296 function common_root_url($ssl=false)
1298 $url = common_path('', $ssl, false);
1299 $i = strpos($url, '?');
1301 $url = substr($url, 0, $i);
1306 // returns $bytes bytes of random data as a hexadecimal string
1307 // "good" here is a goal and not a guarantee
1309 function common_good_rand($bytes)
1311 // XXX: use random.org...?
1312 if (@file_exists('/dev/urandom')) {
1313 return common_urandom($bytes);
1314 } else { // FIXME: this is probably not good enough
1315 return common_mtrand($bytes);
1319 function common_urandom($bytes)
1321 $h = fopen('/dev/urandom', 'rb');
1323 $src = fread($h, $bytes);
1326 for ($i = 0; $i < $bytes; $i++) {
1327 $enc .= sprintf("%02x", (ord($src[$i])));
1332 function common_mtrand($bytes)
1335 for ($i = 0; $i < $bytes; $i++) {
1336 $enc .= sprintf("%02x", mt_rand(0, 255));
1342 * Record the given URL as the return destination for a future
1343 * form submission, to be read by common_get_returnto().
1345 * @param string $url
1347 * @fixme as a session-global setting, this can allow multiple forms
1348 * to conflict and overwrite each others' returnto destinations if
1349 * the user has multiple tabs or windows open.
1351 * Should refactor to index with a token or otherwise only pass the
1352 * data along its intended path.
1354 function common_set_returnto($url)
1356 common_ensure_session();
1357 $_SESSION['returnto'] = $url;
1361 * Fetch a return-destination URL previously recorded by
1362 * common_set_returnto().
1364 * @return mixed URL string or null
1366 * @fixme as a session-global setting, this can allow multiple forms
1367 * to conflict and overwrite each others' returnto destinations if
1368 * the user has multiple tabs or windows open.
1370 * Should refactor to index with a token or otherwise only pass the
1371 * data along its intended path.
1373 function common_get_returnto()
1375 common_ensure_session();
1376 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1379 function common_timestamp()
1381 return date('YmdHis');
1384 function common_ensure_syslog()
1386 static $initialized = false;
1387 if (!$initialized) {
1388 openlog(common_config('syslog', 'appname'), 0,
1389 common_config('syslog', 'facility'));
1390 $initialized = true;
1394 function common_log_line($priority, $msg)
1396 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1397 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1398 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1401 function common_request_id()
1404 $server = common_config('site', 'server');
1405 if (php_sapi_name() == 'cli') {
1406 $script = basename($_SERVER['PHP_SELF']);
1407 return "$server:$script:$pid";
1409 static $req_id = null;
1410 if (!isset($req_id)) {
1411 $req_id = substr(md5(mt_rand()), 0, 8);
1413 if (isset($_SERVER['REQUEST_URI'])) {
1414 $url = $_SERVER['REQUEST_URI'];
1416 $method = $_SERVER['REQUEST_METHOD'];
1417 return "$server:$pid.$req_id $method $url";
1421 function common_log($priority, $msg, $filename=null)
1423 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1424 $msg = '[' . common_request_id() . '] ' . $msg;
1425 $logfile = common_config('site', 'logfile');
1427 $log = fopen($logfile, "a");
1429 $output = common_log_line($priority, $msg);
1430 fwrite($log, $output);
1434 common_ensure_syslog();
1435 syslog($priority, $msg);
1437 Event::handle('EndLog', array($priority, $msg, $filename));
1441 function common_debug($msg, $filename=null)
1444 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1446 common_log(LOG_DEBUG, $msg);
1450 function common_log_db_error(&$object, $verb, $filename=null)
1452 $objstr = common_log_objstring($object);
1453 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1454 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1457 function common_log_objstring(&$object)
1459 if (is_null($object)) {
1462 if (!($object instanceof DB_DataObject)) {
1465 $arr = $object->toArray();
1467 foreach ($arr as $k => $v) {
1468 if (is_object($v)) {
1469 $fields[] = "$k='".get_class($v)."'";
1471 $fields[] = "$k='$v'";
1474 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1478 function common_valid_http_url($url)
1480 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1483 function common_valid_tag($tag)
1485 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1486 return (Validate::email($matches[1]) ||
1487 preg_match('/^([\w-\.]+)$/', $matches[1]));
1493 * Determine if given domain or address literal is valid
1494 * eg for use in JIDs and URLs. Does not check if the domain
1497 * @param string $domain
1498 * @return boolean valid or not
1500 function common_valid_domain($domain)
1502 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1503 $ipv4 = "(?:$octet(?:\.$octet){3})";
1504 if (preg_match("/^$ipv4$/u", $domain)) return true;
1506 $group = "(?:[0-9a-f]{1,4})";
1507 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1509 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1510 $before = explode(":", $matches[1]);
1511 $zeroes = $matches[2];
1512 $after = explode(":", $matches[3]);
1520 $explicit = count($before) + count($after);
1521 if ($explicit < $min || $explicit > $max) {
1528 require_once "Net/IDNA.php";
1529 $idn = Net_IDNA::getInstance();
1530 $domain = $idn->encode($domain);
1531 } catch (Exception $e) {
1535 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1536 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1538 return preg_match("/^$fqdn$/ui", $domain);
1541 /* Following functions are copied from MediaWiki GlobalFunctions.php
1542 * and written by Evan Prodromou. */
1544 function common_accept_to_prefs($accept, $def = '*/*')
1546 // No arg means accept anything (per HTTP spec)
1548 return array($def => 1);
1553 $parts = explode(',', $accept);
1555 foreach($parts as $part) {
1556 // FIXME: doesn't deal with params like 'text/html; level=1'
1557 @list($value, $qpart) = explode(';', trim($part));
1559 if(!isset($qpart)) {
1561 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1562 $prefs[$value] = $match[1];
1569 function common_mime_type_match($type, $avail)
1571 if(array_key_exists($type, $avail)) {
1574 $parts = explode('/', $type);
1575 if(array_key_exists($parts[0] . '/*', $avail)) {
1576 return $parts[0] . '/*';
1577 } elseif(array_key_exists('*/*', $avail)) {
1585 function common_negotiate_type($cprefs, $sprefs)
1589 foreach(array_keys($sprefs) as $type) {
1590 $parts = explode('/', $type);
1591 if($parts[1] != '*') {
1592 $ckey = common_mime_type_match($type, $cprefs);
1594 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1599 foreach(array_keys($cprefs) as $type) {
1600 $parts = explode('/', $type);
1601 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1602 $skey = common_mime_type_match($type, $sprefs);
1604 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1610 $besttype = 'text/html';
1612 foreach(array_keys($combine) as $type) {
1613 if($combine[$type] > $bestq) {
1615 $bestq = $combine[$type];
1619 if ('text/html' === $besttype) {
1620 return "text/html; charset=utf-8";
1625 function common_config($main, $sub)
1628 return (array_key_exists($main, $config) &&
1629 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1632 function common_copy_args($from)
1635 $strip = get_magic_quotes_gpc();
1636 foreach ($from as $k => $v) {
1639 $to[$k] = common_copy_args($v);
1641 $to[$k] = stripslashes($v);
1651 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1652 * This is used before handing a request off to OAuthRequest::from_request.
1653 * @fixme Doesn't consider vars other than _POST and _GET?
1654 * @fixme Can't be undone and could corrupt data if run twice.
1656 function common_remove_magic_from_request()
1658 if(get_magic_quotes_gpc()) {
1659 $_POST=array_map('stripslashes',$_POST);
1660 $_GET=array_map('stripslashes',$_GET);
1664 function common_user_uri(&$user)
1666 return common_local_url('userbyid', array('id' => $user->id),
1670 function common_notice_uri(&$notice)
1672 return common_local_url('shownotice',
1673 array('notice' => $notice->id),
1677 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1679 function common_confirmation_code($bits)
1681 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1682 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1683 $chars = ceil($bits/5);
1685 for ($i = 0; $i < $chars; $i++) {
1686 // XXX: convert to string and back
1687 $num = hexdec(common_good_rand(1));
1688 // XXX: randomness is too precious to throw away almost
1689 // 40% of the bits we get!
1690 $code .= $codechars[$num%32];
1695 // convert markup to HTML
1697 function common_markup_to_html($c)
1699 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1700 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1701 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1702 return Markdown($c);
1705 function common_profile_uri($profile)
1710 $user = User::staticGet($profile->id);
1715 $remote = Remote_profile::staticGet($profile->id);
1717 return $remote->uri;
1719 // XXX: this is a very bad profile!
1723 function common_canonical_sms($sms)
1726 preg_replace('/\D/', '', $sms);
1730 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1735 case E_COMPILE_ERROR:
1739 case E_RECOVERABLE_ERROR:
1740 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1745 case E_COMPILE_WARNING:
1746 case E_CORE_WARNING:
1747 case E_USER_WARNING:
1748 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1753 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1758 case E_USER_DEPRECATED:
1759 // XXX: config variable to log this stuff, too
1763 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1768 // FIXME: show error page if we're on the Web
1769 /* Don't execute PHP internal error handler */
1773 function common_session_token()
1775 common_ensure_session();
1776 if (!array_key_exists('token', $_SESSION)) {
1777 $_SESSION['token'] = common_good_rand(64);
1779 return $_SESSION['token'];
1782 function common_cache_key($extra)
1784 return Cache::key($extra);
1787 function common_keyize($str)
1789 return Cache::keyize($str);
1792 function common_memcache()
1794 return Cache::instance();
1797 function common_license_terms($uri)
1799 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1800 return explode('-',$matches[1]);
1805 function common_compatible_license($from, $to)
1807 $from_terms = common_license_terms($from);
1808 // public domain and cc-by are compatible with everything
1809 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1812 $to_terms = common_license_terms($to);
1813 // sa is compatible across versions. IANAL
1814 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1815 return count(array_diff($from_terms, $to_terms)) == 0;
1817 // XXX: better compatibility check needed here!
1818 // Should at least normalise URIs
1819 return ($from == $to);
1823 * returns a quoted table name, if required according to config
1825 function common_database_tablename($tablename)
1828 if(common_config('db','quote_identifiers')) {
1829 $tablename = '"'. $tablename .'"';
1831 //table prefixes could be added here later
1836 * Shorten a URL with the current user's configured shortening service,
1837 * or ur1.ca if configured, or not at all if no shortening is set up.
1838 * Length is not considered.
1840 * @param string $long_url
1841 * @return string may return the original URL if shortening failed
1843 * @fixme provide a way to specify a particular shortener
1844 * @fixme provide a way to specify to use a given user's shortening preferences
1846 function common_shorten_url($long_url)
1848 $long_url = trim($long_url);
1849 $user = common_current_user();
1851 // common current user does not find a user when called from the XMPP daemon
1852 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1853 $shortenerName = 'ur1.ca';
1855 $shortenerName = $user->urlshorteningservice;
1858 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1859 //URL wasn't shortened, so return the long url
1862 //URL was shortened, so return the result
1863 return trim($shortenedUrl);
1868 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1869 * null if not a web request
1871 * @fixme X-Forwarded-For can be chained by multiple proxies;
1872 we should parse the list and provide a cleaner array
1873 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1874 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1875 * use function to get exact request headers from Apache if possible.
1877 function common_client_ip()
1879 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1883 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1884 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1885 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1887 $proxy = $_SERVER['REMOTE_ADDR'];
1889 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1892 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1893 $ip = $_SERVER['HTTP_CLIENT_IP'];
1895 $ip = $_SERVER['REMOTE_ADDR'];
1899 return array($proxy, $ip);
1902 function common_url_to_nickname($url)
1904 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1906 $parts = parse_url($url);
1908 # If any of these parts exist, this won't work
1910 foreach ($bad as $badpart) {
1911 if (array_key_exists($badpart, $parts)) {
1916 # We just have host and/or path
1918 # If it's just a host...
1919 if (array_key_exists('host', $parts) &&
1920 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1922 $hostparts = explode('.', $parts['host']);
1924 # Try to catch common idiom of nickname.service.tld
1926 if ((count($hostparts) > 2) &&
1927 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1928 (strcmp($hostparts[0], 'www') != 0))
1930 return common_nicknamize($hostparts[0]);
1932 # Do the whole hostname
1933 return common_nicknamize($parts['host']);
1936 if (array_key_exists('path', $parts)) {
1937 # Strip starting, ending slashes
1938 $path = preg_replace('@/$@', '', $parts['path']);
1939 $path = preg_replace('@^/@', '', $path);
1940 $path = basename($path);
1942 // Hack for MediaWiki user pages, in the form:
1943 // http://example.com/wiki/User:Myname
1944 // ('User' may be localized.)
1945 if (strpos($path, ':')) {
1946 $parts = array_filter(explode(':', $path));
1947 $path = $parts[count($parts) - 1];
1951 return common_nicknamize($path);
1959 function common_nicknamize($str)
1961 $str = preg_replace('/\W/', '', $str);
1962 return strtolower($str);