]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
allow user properties in documentation files
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, user, files) */
21
22 /**
23  * Show a server error.
24  */
25 function common_server_error($msg, $code=500)
26 {
27     $err = new ServerErrorAction($msg, $code);
28     $err->showPage();
29 }
30
31 /**
32  * Show a user error.
33  */
34 function common_user_error($msg, $code=400)
35 {
36     $err = new ClientErrorAction($msg, $code);
37     $err->showPage();
38 }
39
40 /**
41  * This should only be used at setup; processes switching languages
42  * to send text to other users should use common_switch_locale().
43  *
44  * @param string $language Locale language code (optional; empty uses
45  *                         current user's preference or site default)
46  * @return mixed success
47  */
48 function common_init_locale($language=null)
49 {
50     if(!$language) {
51         $language = common_language();
52     }
53     putenv('LANGUAGE='.$language);
54     putenv('LANG='.$language);
55     $ok =  setlocale(LC_ALL, $language . ".utf8",
56                      $language . ".UTF8",
57                      $language . ".utf-8",
58                      $language . ".UTF-8",
59                      $language);
60
61     return $ok;
62 }
63
64 /**
65  * Initialize locale and charset settings and gettext with our message catalog,
66  * using the current user's language preference or the site default.
67  *
68  * This should generally only be run at framework initialization; code switching
69  * languages at runtime should call common_switch_language().
70  *
71  * @access private
72  */
73 function common_init_language()
74 {
75     mb_internal_encoding('UTF-8');
76
77     // Note that this setlocale() call may "fail" but this is harmless;
78     // gettext will still select the right language.
79     $language = common_language();
80     $locale_set = common_init_locale($language);
81
82     if (!$locale_set) {
83         // The requested locale doesn't exist on the system.
84         //
85         // gettext seems very picky... We first need to setlocale()
86         // to a locale which _does_ exist on the system, and _then_
87         // we can set in another locale that may not be set up
88         // (say, ga_ES for Galego/Galician) it seems to take it.
89         //
90         // For some reason C and POSIX which are guaranteed to work
91         // don't do the job. en_US.UTF-8 should be there most of the
92         // time, but not guaranteed.
93         $ok = common_init_locale("en_US");
94         if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95             // Try to find a complete, working locale on Unix/Linux...
96             // @fixme shelling out feels awfully inefficient
97             // but I don't think there's a more standard way.
98             $all = `locale -a`;
99             foreach (explode("\n", $all) as $locale) {
100                 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101                     $ok = setlocale(LC_ALL, $locale);
102                     if ($ok) {
103                         break;
104                     }
105                 }
106             }
107         }
108         if (!$ok) {
109             common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
110         }
111         $locale_set = common_init_locale($language);
112     }
113
114     common_init_gettext();
115 }
116
117 /**
118  * @access private
119  */
120 function common_init_gettext()
121 {
122     setlocale(LC_CTYPE, 'C');
123     // So we do not have to make people install the gettext locales
124     $path = common_config('site','locale_path');
125     bindtextdomain("statusnet", $path);
126     bind_textdomain_codeset("statusnet", "UTF-8");
127     textdomain("statusnet");
128 }
129
130 /**
131  * Switch locale during runtime, and poke gettext until it cries uncle.
132  * Otherwise, sometimes it doesn't actually switch away from the old language.
133  *
134  * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
135  */
136 function common_switch_locale($language=null)
137 {
138     common_init_locale($language);
139
140     setlocale(LC_CTYPE, 'C');
141     // So we do not have to make people install the gettext locales
142     $path = common_config('site','locale_path');
143     bindtextdomain("statusnet", $path);
144     bind_textdomain_codeset("statusnet", "UTF-8");
145     textdomain("statusnet");
146 }
147
148 function common_timezone()
149 {
150     if (common_logged_in()) {
151         $user = common_current_user();
152         if ($user->timezone) {
153             return $user->timezone;
154         }
155     }
156
157     return common_config('site', 'timezone');
158 }
159
160 function common_valid_language($lang)
161 {
162     if ($lang) {
163         // Validate -- we don't want to end up with a bogus code
164         // left over from some old junk.
165         foreach (common_config('site', 'languages') as $code => $info) {
166             if ($info['lang'] == $lang) {
167                 return true;
168             }
169         }
170     }
171     return false;
172 }
173
174 function common_language()
175 {
176     // Allow ?uselang=xx override, very useful for debugging
177     // and helping translators check usage and context.
178     if (isset($_GET['uselang'])) {
179         $uselang = strval($_GET['uselang']);
180         if (common_valid_language($uselang)) {
181             return $uselang;
182         }
183     }
184
185     // If there is a user logged in and they've set a language preference
186     // then return that one...
187     if (_have_config() && common_logged_in()) {
188         $user = common_current_user();
189
190         if (common_valid_language($user->language)) {
191             return $user->language;
192         }
193     }
194
195     // Otherwise, find the best match for the languages requested by the
196     // user's browser...
197     if (common_config('site', 'langdetect')) {
198         $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
199         if (!empty($httplang)) {
200             $language = client_prefered_language($httplang);
201             if ($language)
202               return $language;
203         }
204     }
205
206     // Finally, if none of the above worked, use the site's default...
207     return common_config('site', 'language');
208 }
209
210 /**
211  * Salted, hashed passwords are stored in the DB.
212  */
213 function common_munge_password($password, $id)
214 {
215     if (is_object($id) || is_object($password)) {
216         $e = new Exception();
217         common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
218                    str_replace("\n", " ", $e->getTraceAsString()));
219     }
220     return md5($password . $id);
221 }
222
223 /**
224  * Check if a username exists and has matching password.
225  */
226 function common_check_user($nickname, $password)
227 {
228     // empty nickname always unacceptable
229     if (empty($nickname)) {
230         return false;
231     }
232
233     $authenticatedUser = false;
234
235     if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
236         $user = User::staticGet('nickname', common_canonical_nickname($nickname));
237         if (!empty($user)) {
238             if (!empty($password)) { // never allow login with blank password
239                 if (0 == strcmp(common_munge_password($password, $user->id),
240                                 $user->password)) {
241                     //internal checking passed
242                     $authenticatedUser = $user;
243                 }
244             }
245         }
246         Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
247     }
248
249     return $authenticatedUser;
250 }
251
252 /**
253  * Is the current user logged in?
254  */
255 function common_logged_in()
256 {
257     return (!is_null(common_current_user()));
258 }
259
260 function common_have_session()
261 {
262     return (0 != strcmp(session_id(), ''));
263 }
264
265 function common_ensure_session()
266 {
267     $c = null;
268     if (array_key_exists(session_name(), $_COOKIE)) {
269         $c = $_COOKIE[session_name()];
270     }
271     if (!common_have_session()) {
272         if (common_config('sessions', 'handle')) {
273             Session::setSaveHandler();
274         }
275         if (array_key_exists(session_name(), $_GET)) {
276             $id = $_GET[session_name()];
277         } else if (array_key_exists(session_name(), $_COOKIE)) {
278             $id = $_COOKIE[session_name()];
279         }
280         if (isset($id)) {
281             session_id($id);
282         }
283         @session_start();
284         if (!isset($_SESSION['started'])) {
285             $_SESSION['started'] = time();
286             if (!empty($id)) {
287                 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
288                            ' is set but started value is null');
289             }
290         }
291     }
292 }
293
294 // Three kinds of arguments:
295 // 1) a user object
296 // 2) a nickname
297 // 3) null to clear
298
299 // Initialize to false; set to null if none found
300 $_cur = false;
301
302 function common_set_user($user)
303 {
304     global $_cur;
305
306     if (is_null($user) && common_have_session()) {
307         $_cur = null;
308         unset($_SESSION['userid']);
309         return true;
310     } else if (is_string($user)) {
311         $nickname = $user;
312         $user = User::staticGet('nickname', $nickname);
313     } else if (!($user instanceof User)) {
314         return false;
315     }
316
317     if ($user) {
318         if (Event::handle('StartSetUser', array(&$user))) {
319             if (!empty($user)) {
320                 if (!$user->hasRight(Right::WEBLOGIN)) {
321                     // TRANS: Authorisation exception thrown when a user a not allowed to login.
322                     throw new AuthorizationException(_('Not allowed to log in.'));
323                 }
324                 common_ensure_session();
325                 $_SESSION['userid'] = $user->id;
326                 $_cur = $user;
327                 Event::handle('EndSetUser', array($user));
328                 return $_cur;
329             }
330         }
331     }
332     return false;
333 }
334
335 function common_set_cookie($key, $value, $expiration=0)
336 {
337     $path = common_config('site', 'path');
338     $server = common_config('site', 'server');
339
340     if ($path && ($path != '/')) {
341         $cookiepath = '/' . $path . '/';
342     } else {
343         $cookiepath = '/';
344     }
345     return setcookie($key,
346                      $value,
347                      $expiration,
348                      $cookiepath,
349                      $server,
350                      common_config('site', 'ssl')=='always');
351 }
352
353 define('REMEMBERME', 'rememberme');
354 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
355
356 function common_rememberme($user=null)
357 {
358     if (!$user) {
359         $user = common_current_user();
360         if (!$user) {
361             return false;
362         }
363     }
364
365     $rm = new Remember_me();
366
367     $rm->code = common_good_rand(16);
368     $rm->user_id = $user->id;
369
370     // Wrap the insert in some good ol' fashioned transaction code
371
372     $rm->query('BEGIN');
373
374     $result = $rm->insert();
375
376     if (!$result) {
377         common_log_db_error($rm, 'INSERT', __FILE__);
378         return false;
379     }
380
381     $rm->query('COMMIT');
382
383     $cookieval = $rm->user_id . ':' . $rm->code;
384
385     common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
386
387     common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
388
389     return true;
390 }
391
392 function common_remembered_user()
393 {
394     $user = null;
395
396     $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
397
398     if (!$packed) {
399         return null;
400     }
401
402     list($id, $code) = explode(':', $packed);
403
404     if (!$id || !$code) {
405         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
406         common_forgetme();
407         return null;
408     }
409
410     $rm = Remember_me::staticGet($code);
411
412     if (!$rm) {
413         common_log(LOG_WARNING, 'No such remember code: ' . $code);
414         common_forgetme();
415         return null;
416     }
417
418     if ($rm->user_id != $id) {
419         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
420         common_forgetme();
421         return null;
422     }
423
424     $user = User::staticGet($rm->user_id);
425
426     if (!$user) {
427         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
428         common_forgetme();
429         return null;
430     }
431
432     // successful!
433     $result = $rm->delete();
434
435     if (!$result) {
436         common_log_db_error($rm, 'DELETE', __FILE__);
437         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
438         common_forgetme();
439         return null;
440     }
441
442     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
443
444     common_set_user($user);
445     common_real_login(false);
446
447     // We issue a new cookie, so they can log in
448     // automatically again after this session
449
450     common_rememberme($user);
451
452     return $user;
453 }
454
455 /**
456  * must be called with a valid user!
457  */
458 function common_forgetme()
459 {
460     common_set_cookie(REMEMBERME, '', 0);
461 }
462
463 /**
464  * Who is the current user?
465  */
466 function common_current_user()
467 {
468     global $_cur;
469
470     if (!_have_config()) {
471         return null;
472     }
473
474     if ($_cur === false) {
475
476         if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
477             || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
478             common_ensure_session();
479             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
480             if ($id) {
481                 $user = User::staticGet($id);
482                 if ($user) {
483                         $_cur = $user;
484                         return $_cur;
485                 }
486             }
487         }
488
489         // that didn't work; try to remember; will init $_cur to null on failure
490         $_cur = common_remembered_user();
491
492         if ($_cur) {
493             // XXX: Is this necessary?
494             $_SESSION['userid'] = $_cur->id;
495         }
496     }
497
498     return $_cur;
499 }
500
501 /**
502  * Logins that are 'remembered' aren't 'real' -- they're subject to
503  * cookie-stealing. So, we don't let them do certain things. New reg,
504  * OpenID, and password logins _are_ real.
505  */
506 function common_real_login($real=true)
507 {
508     common_ensure_session();
509     $_SESSION['real_login'] = $real;
510 }
511
512 function common_is_real_login()
513 {
514     return common_logged_in() && $_SESSION['real_login'];
515 }
516
517 /**
518  * Get a hash portion for HTTP caching Etags and such including
519  * info on the current user's session. If login/logout state changes,
520  * or we've changed accounts, or we've renamed the current user,
521  * we'll get a new hash value.
522  *
523  * This should not be considered secure information.
524  *
525  * @param User $user (optional; uses common_current_user() if left out)
526  * @return string
527  */
528 function common_user_cache_hash($user=false)
529 {
530     if ($user === false) {
531         $user = common_current_user();
532     }
533     if ($user) {
534         return crc32($user->id . ':' . $user->nickname);
535     } else {
536         return '0';
537     }
538 }
539
540 /**
541  * get canonical version of nickname for comparison
542  *
543  * @param string $nickname
544  * @return string
545  *
546  * @throws NicknameException on invalid input
547  * @deprecated call Nickname::normalize() directly.
548  */
549 function common_canonical_nickname($nickname)
550 {
551     return Nickname::normalize($nickname);
552 }
553
554 /**
555  * get canonical version of email for comparison
556  *
557  * @fixme actually normalize
558  * @fixme reject invalid input
559  *
560  * @param string $email
561  * @return string
562  */
563 function common_canonical_email($email)
564 {
565     // XXX: canonicalize UTF-8
566     // XXX: lcase the domain part
567     return $email;
568 }
569
570 /**
571  * Partial notice markup rendering step: build links to !group references.
572  *
573  * @param string $text partially rendered HTML
574  * @param Notice $notice in whose context we're working
575  * @return string partially rendered HTML
576  */
577 function common_render_content($text, $notice)
578 {
579     $r = common_render_text($text);
580     $id = $notice->profile_id;
581     $r = common_linkify_mentions($r, $notice);
582     $r = preg_replace('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/e',
583                       "'\\1!'.common_group_link($id, '\\2')", $r);
584     return $r;
585 }
586
587 /**
588  * Finds @-mentions within the partially-rendered text section and
589  * turns them into live links.
590  *
591  * Should generally not be called except from common_render_content().
592  *
593  * @param string $text partially-rendered HTML
594  * @param Notice $notice in-progress or complete Notice object for context
595  * @return string partially-rendered HTML
596  */
597 function common_linkify_mentions($text, $notice)
598 {
599     $mentions = common_find_mentions($text, $notice);
600
601     // We need to go through in reverse order by position,
602     // so our positions stay valid despite our fudging with the
603     // string!
604
605     $points = array();
606
607     foreach ($mentions as $mention)
608     {
609         $points[$mention['position']] = $mention;
610     }
611
612     krsort($points);
613
614     foreach ($points as $position => $mention) {
615
616         $linkText = common_linkify_mention($mention);
617
618         $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
619     }
620
621     return $text;
622 }
623
624 function common_linkify_mention($mention)
625 {
626     $output = null;
627
628     if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
629
630         $xs = new XMLStringer(false);
631
632         $attrs = array('href' => $mention['url'],
633                        'class' => 'url');
634
635         if (!empty($mention['title'])) {
636             $attrs['title'] = $mention['title'];
637         }
638
639         $xs->elementStart('span', 'vcard');
640         $xs->elementStart('a', $attrs);
641         $xs->element('span', 'fn nickname mention', $mention['text']);
642         $xs->elementEnd('a');
643         $xs->elementEnd('span');
644
645         $output = $xs->getString();
646
647         Event::handle('EndLinkifyMention', array($mention, &$output));
648     }
649
650     return $output;
651 }
652
653 /**
654  * Find @-mentions in the given text, using the given notice object as context.
655  * References will be resolved with common_relative_profile() against the user
656  * who posted the notice.
657  *
658  * Note the return data format is internal, to be used for building links and
659  * such. Should not be used directly; rather, call common_linkify_mentions().
660  *
661  * @param string $text
662  * @param Notice $notice notice in whose context we're building links
663  *
664  * @return array
665  *
666  * @access private
667  */
668 function common_find_mentions($text, $notice)
669 {
670     $mentions = array();
671
672     $sender = Profile::staticGet('id', $notice->profile_id);
673
674     if (empty($sender)) {
675         return $mentions;
676     }
677
678     if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
679         // Get the context of the original notice, if any
680         $originalAuthor   = null;
681         $originalNotice   = null;
682         $originalMentions = array();
683
684         // Is it a reply?
685
686         if (!empty($notice) && !empty($notice->reply_to)) {
687             $originalNotice = Notice::staticGet('id', $notice->reply_to);
688             if (!empty($originalNotice)) {
689                 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
690
691                 $ids = $originalNotice->getReplies();
692
693                 foreach ($ids as $id) {
694                     $repliedTo = Profile::staticGet('id', $id);
695                     if (!empty($repliedTo)) {
696                         $originalMentions[$repliedTo->nickname] = $repliedTo;
697                     }
698                 }
699             }
700         }
701
702         $matches = common_find_mentions_raw($text);
703
704         foreach ($matches as $match) {
705             try {
706                 $nickname = Nickname::normalize($match[0]);
707             } catch (NicknameException $e) {
708                 // Bogus match? Drop it.
709                 continue;
710             }
711
712             // Try to get a profile for this nickname.
713             // Start with conversation context, then go to
714             // sender context.
715
716             if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
717                 $mentioned = $originalAuthor;
718             } else if (!empty($originalMentions) &&
719                        array_key_exists($nickname, $originalMentions)) {
720                 $mentioned = $originalMentions[$nickname];
721             } else {
722                 $mentioned = common_relative_profile($sender, $nickname);
723             }
724
725             if (!empty($mentioned)) {
726                 $user = User::staticGet('id', $mentioned->id);
727
728                 if ($user) {
729                     $url = common_local_url('userbyid', array('id' => $user->id));
730                 } else {
731                     $url = $mentioned->profileurl;
732                 }
733
734                 $mention = array('mentioned' => array($mentioned),
735                                  'text' => $match[0],
736                                  'position' => $match[1],
737                                  'url' => $url);
738
739                 if (!empty($mentioned->fullname)) {
740                     $mention['title'] = $mentioned->fullname;
741                 }
742
743                 $mentions[] = $mention;
744             }
745         }
746
747         // @#tag => mention of all subscriptions tagged 'tag'
748
749         preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
750                        $text,
751                        $hmatches,
752                        PREG_OFFSET_CAPTURE);
753
754         foreach ($hmatches[1] as $hmatch) {
755
756             $tag = common_canonical_tag($hmatch[0]);
757             $plist = Profile_list::getByTaggerAndTag($sender->id, $tag);
758             if (!empty($plist) && !$plist->private) {
759                 $tagged = $sender->getTaggedSubscribers($tag);
760
761                 $url = common_local_url('showprofiletag',
762                                         array('tagger' => $sender->nickname,
763                                               'tag' => $tag));
764
765                 $mentions[] = array('mentioned' => $tagged,
766                                     'text' => $hmatch[0],
767                                     'position' => $hmatch[1],
768                                     'url' => $url);
769             }
770         }
771
772         Event::handle('EndFindMentions', array($sender, $text, &$mentions));
773     }
774
775     return $mentions;
776 }
777
778 /**
779  * Does the actual regex pulls to find @-mentions in text.
780  * Should generally not be called directly; for use in common_find_mentions.
781  *
782  * @param string $text
783  * @return array of PCRE match arrays
784  */
785 function common_find_mentions_raw($text)
786 {
787     $tmatches = array();
788     preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
789                    $text,
790                    $tmatches,
791                    PREG_OFFSET_CAPTURE);
792
793     $atmatches = array();
794     preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
795                    $text,
796                    $atmatches,
797                    PREG_OFFSET_CAPTURE);
798
799     $matches = array_merge($tmatches[1], $atmatches[1]);
800     return $matches;
801 }
802
803 function common_render_text($text)
804 {
805     $r = htmlspecialchars($text);
806
807     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
808     $r = common_replace_urls_callback($r, 'common_linkify');
809     $r = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/ue', "'\\1#'.common_tag_link('\\2')", $r);
810     // XXX: machine tags
811     return $r;
812 }
813
814 /**
815  * Find links in the given text and pass them to the given callback function.
816  *
817  * @param string $text
818  * @param function($text, $arg) $callback: return replacement text
819  * @param mixed $arg: optional argument will be passed on to the callback
820  */
821 function common_replace_urls_callback($text, $callback, $arg = null) {
822     // Start off with a regex
823     $regex = '#'.
824     '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
825     '('.
826         '(?:'.
827             '(?:'. //Known protocols
828                 '(?:'.
829                     '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
830                     '|'.
831                     '(?:(?:mailto|aim|tel|xmpp):)'.
832                 ')'.
833                 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
834                 '(?:'.
835                     '(?:'.
836                         '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
837                     ')|(?:'.
838                         '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
839                     ')'.
840                 ')'.
841             ')'.
842             '|(?:(?: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
843             '|(?:'. //IPv6
844                 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
845             ')|(?:'. //DNS
846                 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
847                 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
848                 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
849                 '(?: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)'.
850             ')(?![\pN\pL\-\_])'.
851         ')'.
852         '(?:'.
853             '(?:\:\d+)?'. //:port
854             '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
855             '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
856             '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
857         ')(?<![\?\.\,\#\,])'.
858     ')'.
859     '#ixu';
860     //preg_match_all($regex,$text,$matches);
861     //print_r($matches);
862     return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
863 }
864
865 /**
866  * Intermediate callback for common_replace_links(), helps resolve some
867  * ambiguous link forms before passing on to the final callback.
868  *
869  * @param array $matches
870  * @param callable $callback
871  * @param mixed $arg optional argument to pass on as second param to callback
872  * @return string
873  *
874  * @access private
875  */
876 function callback_helper($matches, $callback, $arg=null) {
877     $url=$matches[1];
878     $left = strpos($matches[0],$url);
879     $right = $left+strlen($url);
880
881     $groupSymbolSets=array(
882         array(
883             'left'=>'(',
884             'right'=>')'
885         ),
886         array(
887             'left'=>'[',
888             'right'=>']'
889         ),
890         array(
891             'left'=>'{',
892             'right'=>'}'
893         ),
894         array(
895             'left'=>'<',
896             'right'=>'>'
897         )
898     );
899     $cannotEndWith=array('.','?',',','#');
900     $original_url=$url;
901     do{
902         $original_url=$url;
903         foreach($groupSymbolSets as $groupSymbolSet){
904             if(substr($url,-1)==$groupSymbolSet['right']){
905                 $group_left_count = substr_count($url,$groupSymbolSet['left']);
906                 $group_right_count = substr_count($url,$groupSymbolSet['right']);
907                 if($group_left_count<$group_right_count){
908                     $right-=1;
909                     $url=substr($url,0,-1);
910                 }
911             }
912         }
913         if(in_array(substr($url,-1),$cannotEndWith)){
914             $right-=1;
915             $url=substr($url,0,-1);
916         }
917     }while($original_url!=$url);
918
919     $result = call_user_func_array($callback, array($url, $arg));
920     return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
921 }
922
923 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
924     // lambda implementation in a separate file; PHP 5.2 won't parse it.
925     require_once INSTALLDIR . "/lib/curry.php";
926 } else {
927     function curry($fn) {
928         $args = func_get_args();
929         array_shift($args);
930         $id = uniqid('_partial');
931         $GLOBALS[$id] = array($fn, $args);
932         return create_function('',
933                                '$args = func_get_args(); '.
934                                'return call_user_func_array('.
935                                '$GLOBALS["'.$id.'"][0],'.
936                                'array_merge('.
937                                '$args,'.
938                                '$GLOBALS["'.$id.'"][1]));');
939     }
940 }
941
942 function common_linkify($url) {
943     // It comes in special'd, so we unspecial it before passing to the stringifying
944     // functions
945     $url = htmlspecialchars_decode($url);
946
947     if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
948         //url is an email address without the mailto: protocol
949         $canon = "mailto:$url";
950         $longurl = "mailto:$url";
951     } else {
952
953         $canon = File_redirection::_canonUrl($url);
954
955         $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
956         if (is_array($longurl_data)) {
957             $longurl = $longurl_data['url'];
958         } elseif (is_string($longurl_data)) {
959             $longurl = $longurl_data;
960         } else {
961             // Unable to reach the server to verify contents, etc
962             // Just pass the link on through for now.
963             common_log(LOG_ERR, "Can't linkify url '$url'");
964             $longurl = $url;
965         }
966     }
967
968     $attrs = array('href' => $canon, 'title' => $longurl);
969
970     $is_attachment = false;
971     $attachment_id = null;
972     $has_thumb = false;
973
974     // Check to see whether this is a known "attachment" URL.
975
976     $f = File::staticGet('url', $longurl);
977
978     if (empty($f)) {
979         if (common_config('attachments', 'process_links')) {
980             // XXX: this writes to the database. :<
981             $f = File::processNew($longurl);
982         }
983     }
984
985     if (!empty($f)) {
986         if ($f->getEnclosure()) {
987             $is_attachment = true;
988             $attachment_id = $f->id;
989
990             $thumb = File_thumbnail::staticGet('file_id', $f->id);
991             if (!empty($thumb)) {
992                 $has_thumb = true;
993             }
994         }
995     }
996
997     // Add clippy
998     if ($is_attachment) {
999         $attrs['class'] = 'attachment';
1000         if ($has_thumb) {
1001             $attrs['class'] = 'attachment thumbnail';
1002         }
1003         $attrs['id'] = "attachment-{$attachment_id}";
1004     }
1005
1006     // Whether to nofollow
1007
1008     $nf = common_config('nofollow', 'external');
1009
1010     if ($nf == 'never') {
1011         $attrs['rel'] = 'external';
1012     } else {
1013         $attrs['rel'] = 'nofollow external';
1014     }
1015
1016     return XMLStringer::estring('a', $attrs, $url);
1017 }
1018
1019 /**
1020  * Find and shorten links in a given chunk of text if it's longer than the
1021  * configured notice content limit (or unconditionally).
1022  *
1023  * Side effects: may save file and file_redirection records for referenced URLs.
1024  *
1025  * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1026  * user's options are used; otherwise the current web session user's setitngs
1027  * will be used or ur1.ca if there is no active web login.
1028  *
1029  * @param string $text
1030  * @param boolean $always (optional)
1031  * @param User $user (optional)
1032  *
1033  * @return string
1034  */
1035 function common_shorten_links($text, $always = false, User $user=null)
1036 {
1037     $user = common_current_user();
1038
1039     $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
1040
1041     if ($always || mb_strlen($text) > $maxLength) {
1042         return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
1043     } else {
1044         return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1045     }
1046 }
1047
1048 /**
1049  * Very basic stripping of invalid UTF-8 input text.
1050  *
1051  * @param string $str
1052  * @return mixed string or null if invalid input
1053  *
1054  * @todo ideally we should drop bad chars, and maybe do some of the checks
1055  *       from common_xml_safe_str. But we can't strip newlines, etc.
1056  * @todo Unicode normalization might also be useful, but not needed now.
1057  */
1058 function common_validate_utf8($str)
1059 {
1060     // preg_replace will return NULL on invalid UTF-8 input.
1061     //
1062     // Note: empty regex //u also caused NULL return on some
1063     // production machines, but none of our test machines.
1064     //
1065     // This should be replaced with a more reliable check.
1066     return preg_replace('/\x00/u', '', $str);
1067 }
1068
1069 /**
1070  * Make sure an arbitrary string is safe for output in XML as a single line.
1071  *
1072  * @param string $str
1073  * @return string
1074  */
1075 function common_xml_safe_str($str)
1076 {
1077     // Replace common eol and extra whitespace input chars
1078     $unWelcome = array(
1079         "\t",  // tab
1080         "\n",  // newline
1081         "\r",  // cr
1082         "\0",  // null byte eos
1083         "\x0B" // vertical tab
1084     );
1085
1086     $replacement = array(
1087         ' ', // single space
1088         ' ',
1089         '',  // nothing
1090         '',
1091         ' '
1092     );
1093
1094     $str = str_replace($unWelcome, $replacement, $str);
1095
1096     // Neutralize any additional control codes and UTF-16 surrogates
1097     // (Twitter uses '*')
1098     return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1099 }
1100
1101 function common_tag_link($tag)
1102 {
1103     $canonical = common_canonical_tag($tag);
1104     if (common_config('singleuser', 'enabled')) {
1105         // regular TagAction isn't set up in 1user mode
1106         $nickname = User::singleUserNickname();
1107         $url = common_local_url('showstream',
1108                                 array('nickname' => $nickname,
1109                                       'tag' => $canonical));
1110     } else {
1111         $url = common_local_url('tag', array('tag' => $canonical));
1112     }
1113     $xs = new XMLStringer();
1114     $xs->elementStart('span', 'tag');
1115     $xs->element('a', array('href' => $url,
1116                             'rel' => 'tag'),
1117                  $tag);
1118     $xs->elementEnd('span');
1119     return $xs->getString();
1120 }
1121
1122 function common_canonical_tag($tag)
1123 {
1124   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1125   return str_replace(array('-', '_', '.'), '', $tag);
1126 }
1127
1128 function common_valid_profile_tag($str)
1129 {
1130     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1131 }
1132
1133 /**
1134  *
1135  * @param <type> $sender_id
1136  * @param <type> $nickname
1137  * @return <type>
1138  * @access private
1139  */
1140 function common_group_link($sender_id, $nickname)
1141 {
1142     $sender = Profile::staticGet($sender_id);
1143     $group = User_group::getForNickname($nickname, $sender);
1144     if ($sender && $group && $sender->isMember($group)) {
1145         $attrs = array('href' => $group->permalink(),
1146                        'class' => 'url');
1147         if (!empty($group->fullname)) {
1148             $attrs['title'] = $group->getFancyName();
1149         }
1150         $xs = new XMLStringer();
1151         $xs->elementStart('span', 'vcard');
1152         $xs->elementStart('a', $attrs);
1153         $xs->element('span', 'fn nickname group', $nickname);
1154         $xs->elementEnd('a');
1155         $xs->elementEnd('span');
1156         return $xs->getString();
1157     } else {
1158         return $nickname;
1159     }
1160 }
1161
1162 /**
1163  * Resolve an ambiguous profile nickname reference, checking in following order:
1164  * - profiles that $sender subscribes to
1165  * - profiles that subscribe to $sender
1166  * - local user profiles
1167  *
1168  * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1169  * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1170  * ESCAPE SQL.
1171  *
1172  * @fixme validate input
1173  * @fixme escape SQL
1174  * @fixme fix or remove mystery third parameter
1175  * @fixme is $sender a User or Profile?
1176  *
1177  * @param <type> $sender the user or profile in whose context we're looking
1178  * @param string $nickname validated nickname of
1179  * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1180  *
1181  * @return Profile or null
1182  */
1183 function common_relative_profile($sender, $nickname, $dt=null)
1184 {
1185     // Will throw exception on invalid input.
1186     $nickname = Nickname::normalize($nickname);
1187
1188     // Try to find profiles this profile is subscribed to that have this nickname
1189     $recipient = new Profile();
1190     // XXX: use a join instead of a subquery
1191     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1192     $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1193     if ($recipient->find(true)) {
1194         // XXX: should probably differentiate between profiles with
1195         // the same name by date of most recent update
1196         return $recipient;
1197     }
1198     // Try to find profiles that listen to this profile and that have this nickname
1199     $recipient = new Profile();
1200     // XXX: use a join instead of a subquery
1201     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1202     $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1203     if ($recipient->find(true)) {
1204         // XXX: should probably differentiate between profiles with
1205         // the same name by date of most recent update
1206         return $recipient;
1207     }
1208     // If this is a local user, try to find a local user with that nickname.
1209     $sender = User::staticGet($sender->id);
1210     if ($sender) {
1211         $recipient_user = User::staticGet('nickname', $nickname);
1212         if ($recipient_user) {
1213             return $recipient_user->getProfile();
1214         }
1215     }
1216     // Otherwise, no links. @messages from local users to remote users,
1217     // or from remote users to other remote users, are just
1218     // outside our ability to make intelligent guesses about
1219     return null;
1220 }
1221
1222 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1223 {
1224     if (Event::handle('StartLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url))) {
1225         $r = Router::get();
1226         $path = $r->build($action, $args, $params, $fragment);
1227
1228         $ssl = common_is_sensitive($action);
1229
1230         if (common_config('site','fancy')) {
1231             $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1232         } else {
1233             if (mb_strpos($path, '/index.php') === 0) {
1234                 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1235             } else {
1236                 $url = common_path('index.php'.$path, $ssl, $addSession);
1237             }
1238         }
1239         Event::handle('EndLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url));
1240     }
1241     return $url;
1242 }
1243
1244 function common_is_sensitive($action)
1245 {
1246     static $sensitive = array(
1247         'login',
1248         'register',
1249         'passwordsettings',
1250         'api',
1251         'ApiOauthRequestToken',
1252         'ApiOauthAccessToken',
1253         'ApiOauthAuthorize',
1254         'ApiOauthPin',
1255         'showapplication'
1256     );
1257     $ssl = null;
1258
1259     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1260         $ssl = in_array($action, $sensitive);
1261     }
1262
1263     return $ssl;
1264 }
1265
1266 function common_path($relative, $ssl=false, $addSession=true)
1267 {
1268     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1269
1270     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1271         || common_config('site', 'ssl') === 'always') {
1272         $proto = 'https';
1273         if (is_string(common_config('site', 'sslserver')) &&
1274             mb_strlen(common_config('site', 'sslserver')) > 0) {
1275             $serverpart = common_config('site', 'sslserver');
1276         } else if (common_config('site', 'server')) {
1277             $serverpart = common_config('site', 'server');
1278         } else {
1279             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1280         }
1281     } else {
1282         $proto = 'http';
1283         if (common_config('site', 'server')) {
1284             $serverpart = common_config('site', 'server');
1285         } else {
1286             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1287         }
1288     }
1289
1290     if ($addSession) {
1291         $relative = common_inject_session($relative, $serverpart);
1292     }
1293
1294     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1295 }
1296
1297 function common_inject_session($url, $serverpart = null)
1298 {
1299     if (common_have_session()) {
1300
1301         if (empty($serverpart)) {
1302             $serverpart = parse_url($url, PHP_URL_HOST);
1303         }
1304
1305         $currentServer = $_SERVER['HTTP_HOST'];
1306
1307         // Are we pointing to another server (like an SSL server?)
1308
1309         if (!empty($currentServer) &&
1310             0 != strcasecmp($currentServer, $serverpart)) {
1311             // Pass the session ID as a GET parameter
1312             $sesspart = session_name() . '=' . session_id();
1313             $i = strpos($url, '?');
1314             if ($i === false) { // no GET params, just append
1315                 $url .= '?' . $sesspart;
1316             } else {
1317                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1318             }
1319         }
1320     }
1321
1322     return $url;
1323 }
1324
1325 function common_date_string($dt)
1326 {
1327     // XXX: do some sexy date formatting
1328     // return date(DATE_RFC822, $dt);
1329     $t = strtotime($dt);
1330     $now = time();
1331     $diff = $now - $t;
1332
1333     if ($now < $t) { // that shouldn't happen!
1334         return common_exact_date($dt);
1335     } else if ($diff < 60) {
1336         // TRANS: Used in notices to indicate when the notice was made compared to now.
1337         return _('a few seconds ago');
1338     } else if ($diff < 92) {
1339         // TRANS: Used in notices to indicate when the notice was made compared to now.
1340         return _('about a minute ago');
1341     } else if ($diff < 3300) {
1342         $minutes = round($diff/60);
1343         // TRANS: Used in notices to indicate when the notice was made compared to now.
1344         return sprintf( _m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1345     } else if ($diff < 5400) {
1346         // TRANS: Used in notices to indicate when the notice was made compared to now.
1347         return _('about an hour ago');
1348     } else if ($diff < 22 * 3600) {
1349         $hours = round($diff/3600);
1350         // TRANS: Used in notices to indicate when the notice was made compared to now.
1351         return sprintf( _m('about one hour ago', 'about %d hours ago', $hours), $hours);
1352     } else if ($diff < 37 * 3600) {
1353         // TRANS: Used in notices to indicate when the notice was made compared to now.
1354         return _('about a day ago');
1355     } else if ($diff < 24 * 24 * 3600) {
1356         $days = round($diff/(24*3600));
1357         // TRANS: Used in notices to indicate when the notice was made compared to now.
1358         return sprintf( _m('about one day ago', 'about %d days ago', $days), $days);
1359     } else if ($diff < 46 * 24 * 3600) {
1360         // TRANS: Used in notices to indicate when the notice was made compared to now.
1361         return _('about a month ago');
1362     } else if ($diff < 330 * 24 * 3600) {
1363         $months = round($diff/(30*24*3600));
1364         // TRANS: Used in notices to indicate when the notice was made compared to now.
1365         return sprintf( _m('about one month ago', 'about %d months ago',$months), $months);
1366     } else if ($diff < 480 * 24 * 3600) {
1367         // TRANS: Used in notices to indicate when the notice was made compared to now.
1368         return _('about a year ago');
1369     } else {
1370         return common_exact_date($dt);
1371     }
1372 }
1373
1374 function common_exact_date($dt)
1375 {
1376     static $_utc;
1377     static $_siteTz;
1378
1379     if (!$_utc) {
1380         $_utc = new DateTimeZone('UTC');
1381         $_siteTz = new DateTimeZone(common_timezone());
1382     }
1383
1384     $dateStr = date('d F Y H:i:s', strtotime($dt));
1385     $d = new DateTime($dateStr, $_utc);
1386     $d->setTimezone($_siteTz);
1387     return $d->format(DATE_RFC850);
1388 }
1389
1390 function common_date_w3dtf($dt)
1391 {
1392     $dateStr = date('d F Y H:i:s', strtotime($dt));
1393     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1394     $d->setTimezone(new DateTimeZone(common_timezone()));
1395     return $d->format(DATE_W3C);
1396 }
1397
1398 function common_date_rfc2822($dt)
1399 {
1400     $dateStr = date('d F Y H:i:s', strtotime($dt));
1401     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1402     $d->setTimezone(new DateTimeZone(common_timezone()));
1403     return $d->format('r');
1404 }
1405
1406 function common_date_iso8601($dt)
1407 {
1408     $dateStr = date('d F Y H:i:s', strtotime($dt));
1409     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1410     $d->setTimezone(new DateTimeZone(common_timezone()));
1411     return $d->format('c');
1412 }
1413
1414 function common_sql_now()
1415 {
1416     return common_sql_date(time());
1417 }
1418
1419 function common_sql_date($datetime)
1420 {
1421     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1422 }
1423
1424 /**
1425  * Return an SQL fragment to calculate an age-based weight from a given
1426  * timestamp or datetime column.
1427  *
1428  * @param string $column name of field we're comparing against current time
1429  * @param integer $dropoff divisor for age in seconds before exponentiation
1430  * @return string SQL fragment
1431  */
1432 function common_sql_weight($column, $dropoff)
1433 {
1434     if (common_config('db', 'type') == 'pgsql') {
1435         // PostgreSQL doesn't support timestampdiff function.
1436         // @fixme will this use the right time zone?
1437         // @fixme does this handle cross-year subtraction correctly?
1438         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1439     } else {
1440         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1441     }
1442 }
1443
1444 function common_redirect($url, $code=307)
1445 {
1446     static $status = array(301 => "Moved Permanently",
1447                            302 => "Found",
1448                            303 => "See Other",
1449                            307 => "Temporary Redirect");
1450
1451     header('HTTP/1.1 '.$code.' '.$status[$code]);
1452     header("Location: $url");
1453
1454     $xo = new XMLOutputter();
1455     $xo->startXML('a',
1456                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1457                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1458     $xo->element('a', array('href' => $url), $url);
1459     $xo->endXML();
1460     exit;
1461 }
1462
1463 // Stick the notice on the queue
1464
1465 function common_enqueue_notice($notice)
1466 {
1467     static $localTransports = array('omb',
1468                                     'ping');
1469
1470     $transports = array();
1471     if (common_config('sms', 'enabled')) {
1472         $transports[] = 'sms';
1473     }
1474     if (Event::hasHandler('HandleQueuedNotice')) {
1475         $transports[] = 'plugin';
1476     }
1477
1478     // We can skip these for gatewayed notices.
1479     if ($notice->isLocal()) {
1480         $transports = array_merge($transports, $localTransports);
1481     }
1482
1483     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1484
1485         $qm = QueueManager::get();
1486
1487         foreach ($transports as $transport)
1488         {
1489             $qm->enqueue($notice, $transport);
1490         }
1491
1492         Event::handle('EndEnqueueNotice', array($notice, $transports));
1493     }
1494
1495     return true;
1496 }
1497
1498 /**
1499  * Broadcast profile updates to OMB and other remote subscribers.
1500  *
1501  * Since this may be slow with a lot of subscribers or bad remote sites,
1502  * this is run through the background queues if possible.
1503  */
1504 function common_broadcast_profile(Profile $profile)
1505 {
1506     $qm = QueueManager::get();
1507     $qm->enqueue($profile, "profile");
1508     return true;
1509 }
1510
1511 function common_profile_url($nickname)
1512 {
1513     return common_local_url('showstream', array('nickname' => $nickname),
1514                             null, null, false);
1515 }
1516
1517 /**
1518  * Should make up a reasonable root URL
1519  */
1520 function common_root_url($ssl=false)
1521 {
1522     $url = common_path('', $ssl, false);
1523     $i = strpos($url, '?');
1524     if ($i !== false) {
1525         $url = substr($url, 0, $i);
1526     }
1527     return $url;
1528 }
1529
1530 /**
1531  * returns $bytes bytes of random data as a hexadecimal string
1532  * "good" here is a goal and not a guarantee
1533  */
1534 function common_good_rand($bytes)
1535 {
1536     // XXX: use random.org...?
1537     if (@file_exists('/dev/urandom')) {
1538         return common_urandom($bytes);
1539     } else { // FIXME: this is probably not good enough
1540         return common_mtrand($bytes);
1541     }
1542 }
1543
1544 function common_urandom($bytes)
1545 {
1546     $h = fopen('/dev/urandom', 'rb');
1547     // should not block
1548     $src = fread($h, $bytes);
1549     fclose($h);
1550     $enc = '';
1551     for ($i = 0; $i < $bytes; $i++) {
1552         $enc .= sprintf("%02x", (ord($src[$i])));
1553     }
1554     return $enc;
1555 }
1556
1557 function common_mtrand($bytes)
1558 {
1559     $enc = '';
1560     for ($i = 0; $i < $bytes; $i++) {
1561         $enc .= sprintf("%02x", mt_rand(0, 255));
1562     }
1563     return $enc;
1564 }
1565
1566 /**
1567  * Record the given URL as the return destination for a future
1568  * form submission, to be read by common_get_returnto().
1569  *
1570  * @param string $url
1571  *
1572  * @fixme as a session-global setting, this can allow multiple forms
1573  * to conflict and overwrite each others' returnto destinations if
1574  * the user has multiple tabs or windows open.
1575  *
1576  * Should refactor to index with a token or otherwise only pass the
1577  * data along its intended path.
1578  */
1579 function common_set_returnto($url)
1580 {
1581     common_ensure_session();
1582     $_SESSION['returnto'] = $url;
1583 }
1584
1585 /**
1586  * Fetch a return-destination URL previously recorded by
1587  * common_set_returnto().
1588  *
1589  * @return mixed URL string or null
1590  *
1591  * @fixme as a session-global setting, this can allow multiple forms
1592  * to conflict and overwrite each others' returnto destinations if
1593  * the user has multiple tabs or windows open.
1594  *
1595  * Should refactor to index with a token or otherwise only pass the
1596  * data along its intended path.
1597  */
1598 function common_get_returnto()
1599 {
1600     common_ensure_session();
1601     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1602 }
1603
1604 function common_timestamp()
1605 {
1606     return date('YmdHis');
1607 }
1608
1609 function common_ensure_syslog()
1610 {
1611     static $initialized = false;
1612     if (!$initialized) {
1613         openlog(common_config('syslog', 'appname'), 0,
1614             common_config('syslog', 'facility'));
1615         $initialized = true;
1616     }
1617 }
1618
1619 function common_log_line($priority, $msg)
1620 {
1621     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1622                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1623     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1624 }
1625
1626 function common_request_id()
1627 {
1628     $pid = getmypid();
1629     $server = common_config('site', 'server');
1630     if (php_sapi_name() == 'cli') {
1631         $script = basename($_SERVER['PHP_SELF']);
1632         return "$server:$script:$pid";
1633     } else {
1634         static $req_id = null;
1635         if (!isset($req_id)) {
1636             $req_id = substr(md5(mt_rand()), 0, 8);
1637         }
1638         if (isset($_SERVER['REQUEST_URI'])) {
1639             $url = $_SERVER['REQUEST_URI'];
1640         }
1641         $method = $_SERVER['REQUEST_METHOD'];
1642         return "$server:$pid.$req_id $method $url";
1643     }
1644 }
1645
1646 function common_log($priority, $msg, $filename=null)
1647 {
1648     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1649         $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1650         $msg = '[' . common_request_id() . '] ' . $msg;
1651         $logfile = common_config('site', 'logfile');
1652         if ($logfile) {
1653             $log = fopen($logfile, "a");
1654             if ($log) {
1655                 $output = common_log_line($priority, $msg);
1656                 fwrite($log, $output);
1657                 fclose($log);
1658             }
1659         } else {
1660             common_ensure_syslog();
1661             syslog($priority, $msg);
1662         }
1663         Event::handle('EndLog', array($priority, $msg, $filename));
1664     }
1665 }
1666
1667 function common_debug($msg, $filename=null)
1668 {
1669     if ($filename) {
1670         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1671     } else {
1672         common_log(LOG_DEBUG, $msg);
1673     }
1674 }
1675
1676 function common_log_db_error(&$object, $verb, $filename=null)
1677 {
1678     $objstr = common_log_objstring($object);
1679     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1680     if (is_object($last_error)) {
1681         $msg = $last_error->message;
1682     } else {
1683         $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1684     }
1685     common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1686 }
1687
1688 function common_log_objstring(&$object)
1689 {
1690     if (is_null($object)) {
1691         return "null";
1692     }
1693     if (!($object instanceof DB_DataObject)) {
1694         return "(unknown)";
1695     }
1696     $arr = $object->toArray();
1697     $fields = array();
1698     foreach ($arr as $k => $v) {
1699         if (is_object($v)) {
1700             $fields[] = "$k='".get_class($v)."'";
1701         } else {
1702             $fields[] = "$k='$v'";
1703         }
1704     }
1705     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1706     return $objstring;
1707 }
1708
1709 function common_valid_http_url($url)
1710 {
1711     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1712 }
1713
1714 function common_valid_tag($tag)
1715 {
1716     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1717         return (Validate::email($matches[1]) ||
1718                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1719     }
1720     return false;
1721 }
1722
1723 /**
1724  * Determine if given domain or address literal is valid
1725  * eg for use in JIDs and URLs. Does not check if the domain
1726  * exists!
1727  *
1728  * @param string $domain
1729  * @return boolean valid or not
1730  */
1731 function common_valid_domain($domain)
1732 {
1733     $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1734     $ipv4 = "(?:$octet(?:\.$octet){3})";
1735     if (preg_match("/^$ipv4$/u", $domain)) return true;
1736
1737     $group = "(?:[0-9a-f]{1,4})";
1738     $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1739
1740     if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1741         $before = explode(":", $matches[1]);
1742         $zeroes = $matches[2];
1743         $after = explode(":", $matches[3]);
1744         if ($zeroes) {
1745             $min = 0;
1746             $max = 7;
1747         } else {
1748             $min = 1;
1749             $max = 8;
1750         }
1751         $explicit = count($before) + count($after);
1752         if ($explicit < $min || $explicit > $max) {
1753             return false;
1754         }
1755         return true;
1756     }
1757
1758     try {
1759         require_once "Net/IDNA.php";
1760         $idn = Net_IDNA::getInstance();
1761         $domain = $idn->encode($domain);
1762     } catch (Exception $e) {
1763         return false;
1764     }
1765
1766     $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1767     $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1768
1769     return preg_match("/^$fqdn$/ui", $domain);
1770 }
1771
1772 /* Following functions are copied from MediaWiki GlobalFunctions.php
1773  * and written by Evan Prodromou. */
1774
1775 function common_accept_to_prefs($accept, $def = '*/*')
1776 {
1777     // No arg means accept anything (per HTTP spec)
1778     if(!$accept) {
1779         return array($def => 1);
1780     }
1781
1782     $prefs = array();
1783
1784     $parts = explode(',', $accept);
1785
1786     foreach($parts as $part) {
1787         // FIXME: doesn't deal with params like 'text/html; level=1'
1788         @list($value, $qpart) = explode(';', trim($part));
1789         $match = array();
1790         if(!isset($qpart)) {
1791             $prefs[$value] = 1;
1792         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1793             $prefs[$value] = $match[1];
1794         }
1795     }
1796
1797     return $prefs;
1798 }
1799
1800 function common_mime_type_match($type, $avail)
1801 {
1802     if(array_key_exists($type, $avail)) {
1803         return $type;
1804     } else {
1805         $parts = explode('/', $type);
1806         if(array_key_exists($parts[0] . '/*', $avail)) {
1807             return $parts[0] . '/*';
1808         } elseif(array_key_exists('*/*', $avail)) {
1809             return '*/*';
1810         } else {
1811             return null;
1812         }
1813     }
1814 }
1815
1816 function common_negotiate_type($cprefs, $sprefs)
1817 {
1818     $combine = array();
1819
1820     foreach(array_keys($sprefs) as $type) {
1821         $parts = explode('/', $type);
1822         if($parts[1] != '*') {
1823             $ckey = common_mime_type_match($type, $cprefs);
1824             if($ckey) {
1825                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1826             }
1827         }
1828     }
1829
1830     foreach(array_keys($cprefs) as $type) {
1831         $parts = explode('/', $type);
1832         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1833             $skey = common_mime_type_match($type, $sprefs);
1834             if($skey) {
1835                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1836             }
1837         }
1838     }
1839
1840     $bestq = 0;
1841     $besttype = 'text/html';
1842
1843     foreach(array_keys($combine) as $type) {
1844         if($combine[$type] > $bestq) {
1845             $besttype = $type;
1846             $bestq = $combine[$type];
1847         }
1848     }
1849
1850     if ('text/html' === $besttype) {
1851         return "text/html; charset=utf-8";
1852     }
1853     return $besttype;
1854 }
1855
1856 function common_config($main, $sub)
1857 {
1858     global $config;
1859     return (array_key_exists($main, $config) &&
1860             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1861 }
1862
1863 /**
1864  * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1865  * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1866  *
1867  * @param array $from
1868  * @return array
1869  */
1870 function common_copy_args($from)
1871 {
1872     $to = array();
1873     $strip = get_magic_quotes_gpc();
1874     foreach ($from as $k => $v) {
1875         if(is_array($v)) {
1876             $to[$k] = common_copy_args($v);
1877         } else {
1878             if ($strip) {
1879                 $v = stripslashes($v);
1880             }
1881             $to[$k] = strval(common_validate_utf8($v));
1882         }
1883     }
1884     return $to;
1885 }
1886
1887 /**
1888  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1889  * This is used before handing a request off to OAuthRequest::from_request.
1890  * @fixme Doesn't consider vars other than _POST and _GET?
1891  * @fixme Can't be undone and could corrupt data if run twice.
1892  */
1893 function common_remove_magic_from_request()
1894 {
1895     if(get_magic_quotes_gpc()) {
1896         $_POST=array_map('stripslashes',$_POST);
1897         $_GET=array_map('stripslashes',$_GET);
1898     }
1899 }
1900
1901 function common_user_uri(&$user)
1902 {
1903     return common_local_url('userbyid', array('id' => $user->id),
1904                             null, null, false);
1905 }
1906
1907 function common_notice_uri(&$notice)
1908 {
1909     return common_local_url('shownotice',
1910                             array('notice' => $notice->id),
1911                             null, null, false);
1912 }
1913
1914 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1915
1916 function common_confirmation_code($bits)
1917 {
1918     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1919     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1920     $chars = ceil($bits/5);
1921     $code = '';
1922     for ($i = 0; $i < $chars; $i++) {
1923         // XXX: convert to string and back
1924         $num = hexdec(common_good_rand(1));
1925         // XXX: randomness is too precious to throw away almost
1926         // 40% of the bits we get!
1927         $code .= $codechars[$num%32];
1928     }
1929     return $code;
1930 }
1931
1932 // convert markup to HTML
1933
1934 function common_markup_to_html($c)
1935 {
1936     $c = preg_replace('/%%user.(\w+)%%/e', "common_user_property('\\1')", $c);
1937     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1938     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1939     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1940     return Markdown($c);
1941 }
1942
1943 function common_user_property($property)
1944 {
1945     $profile = Profile::current();
1946
1947     if (empty($profile)) {
1948         return null;
1949     }
1950
1951     switch ($property) {
1952     case 'profileurl':
1953     case 'nickname':
1954     case 'fullname':
1955     case 'location':
1956     case 'bio':
1957         return $profile->$property;
1958         break;
1959     case 'avatar':
1960         return $profile->getAvatar(AVATAR_STREAM_SIZE);
1961         break;
1962     case 'bestname':
1963         return $profile->getBestName();
1964         break;
1965     default:
1966         return null;
1967     }
1968 }
1969
1970 function common_profile_uri($profile)
1971 {
1972     if (!$profile) {
1973         return null;
1974     }
1975     $user = User::staticGet($profile->id);
1976     if ($user) {
1977         return $user->uri;
1978     }
1979
1980     $remote = Remote_profile::staticGet($profile->id);
1981     if ($remote) {
1982         return $remote->uri;
1983     }
1984     // XXX: this is a very bad profile!
1985     return null;
1986 }
1987
1988 function common_canonical_sms($sms)
1989 {
1990     // strip non-digits
1991     preg_replace('/\D/', '', $sms);
1992     return $sms;
1993 }
1994
1995 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1996 {
1997     switch ($errno) {
1998
1999      case E_ERROR:
2000      case E_COMPILE_ERROR:
2001      case E_CORE_ERROR:
2002      case E_USER_ERROR:
2003      case E_PARSE:
2004      case E_RECOVERABLE_ERROR:
2005         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
2006         die();
2007         break;
2008
2009      case E_WARNING:
2010      case E_COMPILE_WARNING:
2011      case E_CORE_WARNING:
2012      case E_USER_WARNING:
2013         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
2014         break;
2015
2016      case E_NOTICE:
2017      case E_USER_NOTICE:
2018         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
2019         break;
2020
2021      case E_STRICT:
2022      case E_DEPRECATED:
2023      case E_USER_DEPRECATED:
2024         // XXX: config variable to log this stuff, too
2025         break;
2026
2027      default:
2028         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
2029         die();
2030         break;
2031     }
2032
2033     // FIXME: show error page if we're on the Web
2034     /* Don't execute PHP internal error handler */
2035     return true;
2036 }
2037
2038 function common_session_token()
2039 {
2040     common_ensure_session();
2041     if (!array_key_exists('token', $_SESSION)) {
2042         $_SESSION['token'] = common_good_rand(64);
2043     }
2044     return $_SESSION['token'];
2045 }
2046
2047 function common_license_terms($uri)
2048 {
2049     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2050         return explode('-',$matches[1]);
2051     }
2052     return array($uri);
2053 }
2054
2055 function common_compatible_license($from, $to)
2056 {
2057     $from_terms = common_license_terms($from);
2058     // public domain and cc-by are compatible with everything
2059     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2060         return true;
2061     }
2062     $to_terms = common_license_terms($to);
2063     // sa is compatible across versions. IANAL
2064     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2065         return count(array_diff($from_terms, $to_terms)) == 0;
2066     }
2067     // XXX: better compatibility check needed here!
2068     // Should at least normalise URIs
2069     return ($from == $to);
2070 }
2071
2072 /**
2073  * returns a quoted table name, if required according to config
2074  */
2075 function common_database_tablename($tablename)
2076 {
2077   if(common_config('db','quote_identifiers')) {
2078       $tablename = '"'. $tablename .'"';
2079   }
2080   //table prefixes could be added here later
2081   return $tablename;
2082 }
2083
2084 /**
2085  * Shorten a URL with the current user's configured shortening service,
2086  * or ur1.ca if configured, or not at all if no shortening is set up.
2087  *
2088  * @param string  $long_url original URL
2089  * @param User $user to specify a particular user's options
2090  * @param boolean $force    Force shortening (used when notice is too long)
2091  * @return string may return the original URL if shortening failed
2092  *
2093  * @fixme provide a way to specify a particular shortener
2094  */
2095 function common_shorten_url($long_url, User $user=null, $force = false)
2096 {
2097     $long_url = trim($long_url);
2098
2099     $user = common_current_user();
2100
2101     $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
2102
2103     // $force forces shortening even if it's not strictly needed
2104     // I doubt URL shortening is ever 'strictly' needed. - ESP
2105
2106     if (mb_strlen($long_url) < $maxUrlLength && !$force) {
2107         return $long_url;
2108     }
2109
2110     $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
2111
2112     if (Event::handle('StartShortenUrl',
2113                       array($long_url, $shortenerName, &$shortenedUrl))) {
2114         if ($shortenerName == 'internal') {
2115             $f = File::processNew($long_url);
2116             if (empty($f)) {
2117                 return $long_url;
2118             } else {
2119                 $shortenedUrl = common_local_url('redirecturl',
2120                                                  array('id' => $f->id));
2121                 return $shortenedUrl;
2122             }
2123         } else {
2124             return $long_url;
2125         }
2126     } else {
2127         //URL was shortened, so return the result
2128         return trim($shortenedUrl);
2129     }
2130 }
2131
2132 /**
2133  * @return mixed array($proxy, $ip) for web requests; proxy may be null
2134  *               null if not a web request
2135  *
2136  * @fixme X-Forwarded-For can be chained by multiple proxies;
2137           we should parse the list and provide a cleaner array
2138  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2139  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2140  *        use function to get exact request headers from Apache if possible.
2141  */
2142 function common_client_ip()
2143 {
2144     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2145         return null;
2146     }
2147
2148     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2149         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2150             $proxy = $_SERVER['HTTP_CLIENT_IP'];
2151         } else {
2152             $proxy = $_SERVER['REMOTE_ADDR'];
2153         }
2154         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2155     } else {
2156         $proxy = null;
2157         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2158             $ip = $_SERVER['HTTP_CLIENT_IP'];
2159         } else {
2160             $ip = $_SERVER['REMOTE_ADDR'];
2161         }
2162     }
2163
2164     return array($proxy, $ip);
2165 }
2166
2167 function common_url_to_nickname($url)
2168 {
2169     static $bad = array('query', 'user', 'password', 'port', 'fragment');
2170
2171     $parts = parse_url($url);
2172
2173     // If any of these parts exist, this won't work
2174
2175     foreach ($bad as $badpart) {
2176         if (array_key_exists($badpart, $parts)) {
2177             return null;
2178         }
2179     }
2180
2181     // We just have host and/or path
2182
2183     // If it's just a host...
2184     if (array_key_exists('host', $parts) &&
2185         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2186     {
2187         $hostparts = explode('.', $parts['host']);
2188
2189         // Try to catch common idiom of nickname.service.tld
2190
2191         if ((count($hostparts) > 2) &&
2192             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2193             (strcmp($hostparts[0], 'www') != 0))
2194         {
2195             return common_nicknamize($hostparts[0]);
2196         } else {
2197             // Do the whole hostname
2198             return common_nicknamize($parts['host']);
2199         }
2200     } else {
2201         if (array_key_exists('path', $parts)) {
2202             // Strip starting, ending slashes
2203             $path = preg_replace('@/$@', '', $parts['path']);
2204             $path = preg_replace('@^/@', '', $path);
2205             $path = basename($path);
2206
2207             // Hack for MediaWiki user pages, in the form:
2208             // http://example.com/wiki/User:Myname
2209             // ('User' may be localized.)
2210             if (strpos($path, ':')) {
2211                 $parts = array_filter(explode(':', $path));
2212                 $path = $parts[count($parts) - 1];
2213             }
2214
2215             if ($path) {
2216                 return common_nicknamize($path);
2217             }
2218         }
2219     }
2220
2221     return null;
2222 }
2223
2224 function common_nicknamize($str)
2225 {
2226     $str = preg_replace('/\W/', '', $str);
2227     return strtolower($str);
2228 }
2229
2230 function common_perf_counter($key, $val=null)
2231 {
2232     global $_perfCounters;
2233     if (isset($_perfCounters)) {
2234         if (common_config('site', 'logperf')) {
2235             if (array_key_exists($key, $_perfCounters)) {
2236                 $_perfCounters[$key][] = $val;
2237             } else {
2238                 $_perfCounters[$key] = array($val);
2239             }
2240             if (common_config('site', 'logperf_detail')) {
2241                 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2242             }
2243         }
2244     }
2245 }
2246
2247 function common_log_perf_counters()
2248 {
2249     if (common_config('site', 'logperf')) {
2250         global $_startTime, $_perfCounters;
2251
2252         if (isset($_startTime)) {
2253             $endTime = microtime(true);
2254             $diff = round(($endTime - $_startTime) * 1000);
2255             common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2256         }
2257         $counters = $_perfCounters;
2258         ksort($counters);
2259         foreach ($counters as $key => $values) {
2260             $count = count($values);
2261             $unique = count(array_unique($values));
2262             common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
2263         }
2264     }
2265 }