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