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