]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
add Connection: close when sending redirect
[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   // only alphanum
1100   $tag = preg_replace('/[^\pL\pN]/u', '', $tag);
1101   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1102   $tag = substr($tag, 0, 64);
1103   return $tag;
1104 }
1105
1106 function common_valid_profile_tag($str)
1107 {
1108     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1109 }
1110
1111 /**
1112  *
1113  * @param <type> $sender_id
1114  * @param <type> $nickname
1115  * @return <type>
1116  * @access private
1117  */
1118 function common_group_link($sender_id, $nickname)
1119 {
1120     $sender = Profile::staticGet($sender_id);
1121     $group = User_group::getForNickname($nickname, $sender);
1122     if ($sender && $group && $sender->isMember($group)) {
1123         $attrs = array('href' => $group->permalink(),
1124                        'class' => 'url');
1125         if (!empty($group->fullname)) {
1126             $attrs['title'] = $group->getFancyName();
1127         }
1128         $xs = new XMLStringer();
1129         $xs->elementStart('span', 'vcard');
1130         $xs->elementStart('a', $attrs);
1131         $xs->element('span', 'fn nickname', $nickname);
1132         $xs->elementEnd('a');
1133         $xs->elementEnd('span');
1134         return $xs->getString();
1135     } else {
1136         return $nickname;
1137     }
1138 }
1139
1140 /**
1141  * Resolve an ambiguous profile nickname reference, checking in following order:
1142  * - profiles that $sender subscribes to
1143  * - profiles that subscribe to $sender
1144  * - local user profiles
1145  *
1146  * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1147  * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1148  * ESCAPE SQL.
1149  *
1150  * @fixme validate input
1151  * @fixme escape SQL
1152  * @fixme fix or remove mystery third parameter
1153  * @fixme is $sender a User or Profile?
1154  *
1155  * @param <type> $sender the user or profile in whose context we're looking
1156  * @param string $nickname validated nickname of
1157  * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1158  *
1159  * @return Profile or null
1160  */
1161 function common_relative_profile($sender, $nickname, $dt=null)
1162 {
1163     // Will throw exception on invalid input.
1164     $nickname = Nickname::normalize($nickname);
1165
1166     // Try to find profiles this profile is subscribed to that have this nickname
1167     $recipient = new Profile();
1168     // XXX: use a join instead of a subquery
1169     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1170     $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1171     if ($recipient->find(true)) {
1172         // XXX: should probably differentiate between profiles with
1173         // the same name by date of most recent update
1174         return $recipient;
1175     }
1176     // Try to find profiles that listen to this profile and that have this nickname
1177     $recipient = new Profile();
1178     // XXX: use a join instead of a subquery
1179     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1180     $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1181     if ($recipient->find(true)) {
1182         // XXX: should probably differentiate between profiles with
1183         // the same name by date of most recent update
1184         return $recipient;
1185     }
1186     // If this is a local user, try to find a local user with that nickname.
1187     $sender = User::staticGet($sender->id);
1188     if ($sender) {
1189         $recipient_user = User::staticGet('nickname', $nickname);
1190         if ($recipient_user) {
1191             return $recipient_user->getProfile();
1192         }
1193     }
1194     // Otherwise, no links. @messages from local users to remote users,
1195     // or from remote users to other remote users, are just
1196     // outside our ability to make intelligent guesses about
1197     return null;
1198 }
1199
1200 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1201 {
1202     $r = Router::get();
1203     $path = $r->build($action, $args, $params, $fragment);
1204
1205     $ssl = common_is_sensitive($action);
1206
1207     if (common_config('site','fancy')) {
1208         $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1209     } else {
1210         if (mb_strpos($path, '/index.php') === 0) {
1211             $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1212         } else {
1213             $url = common_path('index.php'.$path, $ssl, $addSession);
1214         }
1215     }
1216     return $url;
1217 }
1218
1219 function common_is_sensitive($action)
1220 {
1221     static $sensitive = array(
1222         'login',
1223         'register',
1224         'passwordsettings',
1225         'api',
1226         'ApiOauthRequestToken',
1227         'ApiOauthAccessToken',
1228         'ApiOauthAuthorize',
1229         'ApiOauthPin',
1230         'showapplication'
1231     );
1232     $ssl = null;
1233
1234     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1235         $ssl = in_array($action, $sensitive);
1236     }
1237
1238     return $ssl;
1239 }
1240
1241 function common_path($relative, $ssl=false, $addSession=true)
1242 {
1243     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1244
1245     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1246         || common_config('site', 'ssl') === 'always') {
1247         $proto = 'https';
1248         if (is_string(common_config('site', 'sslserver')) &&
1249             mb_strlen(common_config('site', 'sslserver')) > 0) {
1250             $serverpart = common_config('site', 'sslserver');
1251         } else if (common_config('site', 'server')) {
1252             $serverpart = common_config('site', 'server');
1253         } else {
1254             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1255         }
1256     } else {
1257         $proto = 'http';
1258         if (common_config('site', 'server')) {
1259             $serverpart = common_config('site', 'server');
1260         } else {
1261             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1262         }
1263     }
1264
1265     if ($addSession) {
1266         $relative = common_inject_session($relative, $serverpart);
1267     }
1268
1269     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1270 }
1271
1272 function common_inject_session($url, $serverpart = null)
1273 {
1274     if (common_have_session()) {
1275
1276         if (empty($serverpart)) {
1277             $serverpart = parse_url($url, PHP_URL_HOST);
1278         }
1279
1280         $currentServer = $_SERVER['HTTP_HOST'];
1281
1282         // Are we pointing to another server (like an SSL server?)
1283
1284         if (!empty($currentServer) &&
1285             0 != strcasecmp($currentServer, $serverpart)) {
1286             // Pass the session ID as a GET parameter
1287             $sesspart = session_name() . '=' . session_id();
1288             $i = strpos($url, '?');
1289             if ($i === false) { // no GET params, just append
1290                 $url .= '?' . $sesspart;
1291             } else {
1292                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1293             }
1294         }
1295     }
1296
1297     return $url;
1298 }
1299
1300 function common_date_string($dt)
1301 {
1302     // XXX: do some sexy date formatting
1303     // return date(DATE_RFC822, $dt);
1304     $t = strtotime($dt);
1305     $now = time();
1306     $diff = $now - $t;
1307
1308     if ($now < $t) { // that shouldn't happen!
1309         return common_exact_date($dt);
1310     } else if ($diff < 60) {
1311         // TRANS: Used in notices to indicate when the notice was made compared to now.
1312         return _('a few seconds ago');
1313     } else if ($diff < 92) {
1314         // TRANS: Used in notices to indicate when the notice was made compared to now.
1315         return _('about a minute ago');
1316     } else if ($diff < 3300) {
1317         $minutes = round($diff/60);
1318         // TRANS: Used in notices to indicate when the notice was made compared to now.
1319         return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1320     } else if ($diff < 5400) {
1321         // TRANS: Used in notices to indicate when the notice was made compared to now.
1322         return _('about an hour ago');
1323     } else if ($diff < 22 * 3600) {
1324         $hours = round($diff/3600);
1325         // TRANS: Used in notices to indicate when the notice was made compared to now.
1326         return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1327     } else if ($diff < 37 * 3600) {
1328         // TRANS: Used in notices to indicate when the notice was made compared to now.
1329         return _('about a day ago');
1330     } else if ($diff < 24 * 24 * 3600) {
1331         $days = round($diff/(24*3600));
1332         // TRANS: Used in notices to indicate when the notice was made compared to now.
1333         return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1334     } else if ($diff < 46 * 24 * 3600) {
1335         // TRANS: Used in notices to indicate when the notice was made compared to now.
1336         return _('about a month ago');
1337     } else if ($diff < 330 * 24 * 3600) {
1338         $months = round($diff/(30*24*3600));
1339         // TRANS: Used in notices to indicate when the notice was made compared to now.
1340         return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1341     } else if ($diff < 480 * 24 * 3600) {
1342         // TRANS: Used in notices to indicate when the notice was made compared to now.
1343         return _('about a year ago');
1344     } else {
1345         return common_exact_date($dt);
1346     }
1347 }
1348
1349 function common_exact_date($dt)
1350 {
1351     static $_utc;
1352     static $_siteTz;
1353
1354     if (!$_utc) {
1355         $_utc = new DateTimeZone('UTC');
1356         $_siteTz = new DateTimeZone(common_timezone());
1357     }
1358
1359     $dateStr = date('d F Y H:i:s', strtotime($dt));
1360     $d = new DateTime($dateStr, $_utc);
1361     $d->setTimezone($_siteTz);
1362     return $d->format(DATE_RFC850);
1363 }
1364
1365 function common_date_w3dtf($dt)
1366 {
1367     $dateStr = date('d F Y H:i:s', strtotime($dt));
1368     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1369     $d->setTimezone(new DateTimeZone(common_timezone()));
1370     return $d->format(DATE_W3C);
1371 }
1372
1373 function common_date_rfc2822($dt)
1374 {
1375     $dateStr = date('d F Y H:i:s', strtotime($dt));
1376     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1377     $d->setTimezone(new DateTimeZone(common_timezone()));
1378     return $d->format('r');
1379 }
1380
1381 function common_date_iso8601($dt)
1382 {
1383     $dateStr = date('d F Y H:i:s', strtotime($dt));
1384     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1385     $d->setTimezone(new DateTimeZone(common_timezone()));
1386     return $d->format('c');
1387 }
1388
1389 function common_sql_now()
1390 {
1391     return common_sql_date(time());
1392 }
1393
1394 function common_sql_date($datetime)
1395 {
1396     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1397 }
1398
1399 /**
1400  * Return an SQL fragment to calculate an age-based weight from a given
1401  * timestamp or datetime column.
1402  *
1403  * @param string $column name of field we're comparing against current time
1404  * @param integer $dropoff divisor for age in seconds before exponentiation
1405  * @return string SQL fragment
1406  */
1407 function common_sql_weight($column, $dropoff)
1408 {
1409     if (common_config('db', 'type') == 'pgsql') {
1410         // PostgreSQL doesn't support timestampdiff function.
1411         // @fixme will this use the right time zone?
1412         // @fixme does this handle cross-year subtraction correctly?
1413         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1414     } else {
1415         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1416     }
1417 }
1418
1419 function common_redirect($url, $code=307)
1420 {
1421     static $status = array(301 => "Moved Permanently",
1422                            302 => "Found",
1423                            303 => "See Other",
1424                            307 => "Temporary Redirect");
1425
1426     header('HTTP/1.1 '.$code.' '.$status[$code]);
1427     header("Location: $url");
1428     header("Connection: close");
1429
1430     $xo = new XMLOutputter();
1431     $xo->startXML('a',
1432                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1433                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1434     $xo->element('a', array('href' => $url), $url);
1435     $xo->endXML();
1436     exit;
1437 }
1438
1439 function common_broadcast_notice($notice, $remote=false)
1440 {
1441     // DO NOTHING!
1442 }
1443
1444 /**
1445  * Stick the notice on the queue.
1446  */
1447 function common_enqueue_notice($notice)
1448 {
1449     static $localTransports = array('omb',
1450                                     'ping');
1451
1452     $transports = array();
1453     if (common_config('sms', 'enabled')) {
1454         $transports[] = 'sms';
1455     }
1456     if (Event::hasHandler('HandleQueuedNotice')) {
1457         $transports[] = 'plugin';
1458     }
1459
1460     $xmpp = common_config('xmpp', 'enabled');
1461
1462     if ($xmpp) {
1463         $transports[] = 'jabber';
1464     }
1465
1466     // We can skip these for gatewayed notices.
1467     if ($notice->isLocal()) {
1468         $transports = array_merge($transports, $localTransports);
1469         if ($xmpp) {
1470             $transports[] = 'public';
1471         }
1472     }
1473
1474     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1475
1476         $qm = QueueManager::get();
1477
1478         foreach ($transports as $transport)
1479         {
1480             $qm->enqueue($notice, $transport);
1481         }
1482
1483         Event::handle('EndEnqueueNotice', array($notice, $transports));
1484     }
1485
1486     return true;
1487 }
1488
1489 /**
1490  * Broadcast profile updates to OMB and other remote subscribers.
1491  *
1492  * Since this may be slow with a lot of subscribers or bad remote sites,
1493  * this is run through the background queues if possible.
1494  */
1495 function common_broadcast_profile(Profile $profile)
1496 {
1497     $qm = QueueManager::get();
1498     $qm->enqueue($profile, "profile");
1499     return true;
1500 }
1501
1502 function common_profile_url($nickname)
1503 {
1504     return common_local_url('showstream', array('nickname' => $nickname),
1505                             null, null, false);
1506 }
1507
1508 /**
1509  * Should make up a reasonable root URL
1510  */
1511 function common_root_url($ssl=false)
1512 {
1513     $url = common_path('', $ssl, false);
1514     $i = strpos($url, '?');
1515     if ($i !== false) {
1516         $url = substr($url, 0, $i);
1517     }
1518     return $url;
1519 }
1520
1521 /**
1522  * returns $bytes bytes of random data as a hexadecimal string
1523  * "good" here is a goal and not a guarantee
1524  */
1525 function common_good_rand($bytes)
1526 {
1527     // XXX: use random.org...?
1528     if (@file_exists('/dev/urandom')) {
1529         return common_urandom($bytes);
1530     } else { // FIXME: this is probably not good enough
1531         return common_mtrand($bytes);
1532     }
1533 }
1534
1535 function common_urandom($bytes)
1536 {
1537     $h = fopen('/dev/urandom', 'rb');
1538     // should not block
1539     $src = fread($h, $bytes);
1540     fclose($h);
1541     $enc = '';
1542     for ($i = 0; $i < $bytes; $i++) {
1543         $enc .= sprintf("%02x", (ord($src[$i])));
1544     }
1545     return $enc;
1546 }
1547
1548 function common_mtrand($bytes)
1549 {
1550     $enc = '';
1551     for ($i = 0; $i < $bytes; $i++) {
1552         $enc .= sprintf("%02x", mt_rand(0, 255));
1553     }
1554     return $enc;
1555 }
1556
1557 /**
1558  * Record the given URL as the return destination for a future
1559  * form submission, to be read by common_get_returnto().
1560  *
1561  * @param string $url
1562  *
1563  * @fixme as a session-global setting, this can allow multiple forms
1564  * to conflict and overwrite each others' returnto destinations if
1565  * the user has multiple tabs or windows open.
1566  *
1567  * Should refactor to index with a token or otherwise only pass the
1568  * data along its intended path.
1569  */
1570 function common_set_returnto($url)
1571 {
1572     common_ensure_session();
1573     $_SESSION['returnto'] = $url;
1574 }
1575
1576 /**
1577  * Fetch a return-destination URL previously recorded by
1578  * common_set_returnto().
1579  *
1580  * @return mixed URL string or null
1581  *
1582  * @fixme as a session-global setting, this can allow multiple forms
1583  * to conflict and overwrite each others' returnto destinations if
1584  * the user has multiple tabs or windows open.
1585  *
1586  * Should refactor to index with a token or otherwise only pass the
1587  * data along its intended path.
1588  */
1589 function common_get_returnto()
1590 {
1591     common_ensure_session();
1592     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1593 }
1594
1595 function common_timestamp()
1596 {
1597     return date('YmdHis');
1598 }
1599
1600 function common_ensure_syslog()
1601 {
1602     static $initialized = false;
1603     if (!$initialized) {
1604         openlog(common_config('syslog', 'appname'), 0,
1605             common_config('syslog', 'facility'));
1606         $initialized = true;
1607     }
1608 }
1609
1610 function common_log_line($priority, $msg)
1611 {
1612     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1613                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1614     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1615 }
1616
1617 function common_request_id()
1618 {
1619     $pid = getmypid();
1620     $server = common_config('site', 'server');
1621     if (php_sapi_name() == 'cli') {
1622         $script = basename($_SERVER['PHP_SELF']);
1623         return "$server:$script:$pid";
1624     } else {
1625         static $req_id = null;
1626         if (!isset($req_id)) {
1627             $req_id = substr(md5(mt_rand()), 0, 8);
1628         }
1629         if (isset($_SERVER['REQUEST_URI'])) {
1630             $url = $_SERVER['REQUEST_URI'];
1631         }
1632         $method = $_SERVER['REQUEST_METHOD'];
1633         return "$server:$pid.$req_id $method $url";
1634     }
1635 }
1636
1637 function common_log($priority, $msg, $filename=null)
1638 {
1639     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1640         $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1641         $msg = '[' . common_request_id() . '] ' . $msg;
1642         $logfile = common_config('site', 'logfile');
1643         if ($logfile) {
1644             $log = fopen($logfile, "a");
1645             if ($log) {
1646                 $output = common_log_line($priority, $msg);
1647                 fwrite($log, $output);
1648                 fclose($log);
1649             }
1650         } else {
1651             common_ensure_syslog();
1652             syslog($priority, $msg);
1653         }
1654         Event::handle('EndLog', array($priority, $msg, $filename));
1655     }
1656 }
1657
1658 function common_debug($msg, $filename=null)
1659 {
1660     if ($filename) {
1661         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1662     } else {
1663         common_log(LOG_DEBUG, $msg);
1664     }
1665 }
1666
1667 function common_log_db_error(&$object, $verb, $filename=null)
1668 {
1669     $objstr = common_log_objstring($object);
1670     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1671     if (is_object($last_error)) {
1672         $msg = $last_error->message;
1673     } else {
1674         $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1675     }
1676     common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1677 }
1678
1679 function common_log_objstring(&$object)
1680 {
1681     if (is_null($object)) {
1682         return "null";
1683     }
1684     if (!($object instanceof DB_DataObject)) {
1685         return "(unknown)";
1686     }
1687     $arr = $object->toArray();
1688     $fields = array();
1689     foreach ($arr as $k => $v) {
1690         if (is_object($v)) {
1691             $fields[] = "$k='".get_class($v)."'";
1692         } else {
1693             $fields[] = "$k='$v'";
1694         }
1695     }
1696     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1697     return $objstring;
1698 }
1699
1700 function common_valid_http_url($url)
1701 {
1702     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1703 }
1704
1705 function common_valid_tag($tag)
1706 {
1707     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1708         return (Validate::email($matches[1]) ||
1709                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1710     }
1711     return false;
1712 }
1713
1714 /**
1715  * Determine if given domain or address literal is valid
1716  * eg for use in JIDs and URLs. Does not check if the domain
1717  * exists!
1718  *
1719  * @param string $domain
1720  * @return boolean valid or not
1721  */
1722 function common_valid_domain($domain)
1723 {
1724     $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1725     $ipv4 = "(?:$octet(?:\.$octet){3})";
1726     if (preg_match("/^$ipv4$/u", $domain)) return true;
1727
1728     $group = "(?:[0-9a-f]{1,4})";
1729     $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1730
1731     if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1732         $before = explode(":", $matches[1]);
1733         $zeroes = $matches[2];
1734         $after = explode(":", $matches[3]);
1735         if ($zeroes) {
1736             $min = 0;
1737             $max = 7;
1738         } else {
1739             $min = 1;
1740             $max = 8;
1741         }
1742         $explicit = count($before) + count($after);
1743         if ($explicit < $min || $explicit > $max) {
1744             return false;
1745         }
1746         return true;
1747     }
1748
1749     try {
1750         require_once "Net/IDNA.php";
1751         $idn = Net_IDNA::getInstance();
1752         $domain = $idn->encode($domain);
1753     } catch (Exception $e) {
1754         return false;
1755     }
1756
1757     $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1758     $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1759
1760     return preg_match("/^$fqdn$/ui", $domain);
1761 }
1762
1763 /* Following functions are copied from MediaWiki GlobalFunctions.php
1764  * and written by Evan Prodromou. */
1765
1766 function common_accept_to_prefs($accept, $def = '*/*')
1767 {
1768     // No arg means accept anything (per HTTP spec)
1769     if(!$accept) {
1770         return array($def => 1);
1771     }
1772
1773     $prefs = array();
1774
1775     $parts = explode(',', $accept);
1776
1777     foreach($parts as $part) {
1778         // FIXME: doesn't deal with params like 'text/html; level=1'
1779         @list($value, $qpart) = explode(';', trim($part));
1780         $match = array();
1781         if(!isset($qpart)) {
1782             $prefs[$value] = 1;
1783         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1784             $prefs[$value] = $match[1];
1785         }
1786     }
1787
1788     return $prefs;
1789 }
1790
1791 function common_mime_type_match($type, $avail)
1792 {
1793     if(array_key_exists($type, $avail)) {
1794         return $type;
1795     } else {
1796         $parts = explode('/', $type);
1797         if(array_key_exists($parts[0] . '/*', $avail)) {
1798             return $parts[0] . '/*';
1799         } elseif(array_key_exists('*/*', $avail)) {
1800             return '*/*';
1801         } else {
1802             return null;
1803         }
1804     }
1805 }
1806
1807 function common_negotiate_type($cprefs, $sprefs)
1808 {
1809     $combine = array();
1810
1811     foreach(array_keys($sprefs) as $type) {
1812         $parts = explode('/', $type);
1813         if($parts[1] != '*') {
1814             $ckey = common_mime_type_match($type, $cprefs);
1815             if($ckey) {
1816                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1817             }
1818         }
1819     }
1820
1821     foreach(array_keys($cprefs) as $type) {
1822         $parts = explode('/', $type);
1823         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1824             $skey = common_mime_type_match($type, $sprefs);
1825             if($skey) {
1826                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1827             }
1828         }
1829     }
1830
1831     $bestq = 0;
1832     $besttype = 'text/html';
1833
1834     foreach(array_keys($combine) as $type) {
1835         if($combine[$type] > $bestq) {
1836             $besttype = $type;
1837             $bestq = $combine[$type];
1838         }
1839     }
1840
1841     if ('text/html' === $besttype) {
1842         return "text/html; charset=utf-8";
1843     }
1844     return $besttype;
1845 }
1846
1847 function common_config($main, $sub)
1848 {
1849     global $config;
1850     return (array_key_exists($main, $config) &&
1851             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1852 }
1853
1854 /**
1855  * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1856  * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1857  *
1858  * @param array $from
1859  * @return array
1860  */
1861 function common_copy_args($from)
1862 {
1863     $to = array();
1864     $strip = get_magic_quotes_gpc();
1865     foreach ($from as $k => $v) {
1866         if(is_array($v)) {
1867             $to[$k] = common_copy_args($v);
1868         } else {
1869             if ($strip) {
1870                 $v = stripslashes($v);
1871             }
1872             $to[$k] = strval(common_validate_utf8($v));
1873         }
1874     }
1875     return $to;
1876 }
1877
1878 /**
1879  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1880  * This is used before handing a request off to OAuthRequest::from_request.
1881  * @fixme Doesn't consider vars other than _POST and _GET?
1882  * @fixme Can't be undone and could corrupt data if run twice.
1883  */
1884 function common_remove_magic_from_request()
1885 {
1886     if(get_magic_quotes_gpc()) {
1887         $_POST=array_map('stripslashes',$_POST);
1888         $_GET=array_map('stripslashes',$_GET);
1889     }
1890 }
1891
1892 function common_user_uri(&$user)
1893 {
1894     return common_local_url('userbyid', array('id' => $user->id),
1895                             null, null, false);
1896 }
1897
1898 function common_notice_uri(&$notice)
1899 {
1900     return common_local_url('shownotice',
1901                             array('notice' => $notice->id),
1902                             null, null, false);
1903 }
1904
1905 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1906
1907 function common_confirmation_code($bits)
1908 {
1909     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1910     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1911     $chars = ceil($bits/5);
1912     $code = '';
1913     for ($i = 0; $i < $chars; $i++) {
1914         // XXX: convert to string and back
1915         $num = hexdec(common_good_rand(1));
1916         // XXX: randomness is too precious to throw away almost
1917         // 40% of the bits we get!
1918         $code .= $codechars[$num%32];
1919     }
1920     return $code;
1921 }
1922
1923 // convert markup to HTML
1924
1925 function common_markup_to_html($c)
1926 {
1927     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1928     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1929     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1930     return Markdown($c);
1931 }
1932
1933 function common_profile_uri($profile)
1934 {
1935     if (!$profile) {
1936         return null;
1937     }
1938     $user = User::staticGet($profile->id);
1939     if ($user) {
1940         return $user->uri;
1941     }
1942
1943     $remote = Remote_profile::staticGet($profile->id);
1944     if ($remote) {
1945         return $remote->uri;
1946     }
1947     // XXX: this is a very bad profile!
1948     return null;
1949 }
1950
1951 function common_canonical_sms($sms)
1952 {
1953     // strip non-digits
1954     preg_replace('/\D/', '', $sms);
1955     return $sms;
1956 }
1957
1958 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1959 {
1960     switch ($errno) {
1961
1962      case E_ERROR:
1963      case E_COMPILE_ERROR:
1964      case E_CORE_ERROR:
1965      case E_USER_ERROR:
1966      case E_PARSE:
1967      case E_RECOVERABLE_ERROR:
1968         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1969         die();
1970         break;
1971
1972      case E_WARNING:
1973      case E_COMPILE_WARNING:
1974      case E_CORE_WARNING:
1975      case E_USER_WARNING:
1976         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1977         break;
1978
1979      case E_NOTICE:
1980      case E_USER_NOTICE:
1981         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1982         break;
1983
1984      case E_STRICT:
1985      case E_DEPRECATED:
1986      case E_USER_DEPRECATED:
1987         // XXX: config variable to log this stuff, too
1988         break;
1989
1990      default:
1991         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1992         die();
1993         break;
1994     }
1995
1996     // FIXME: show error page if we're on the Web
1997     /* Don't execute PHP internal error handler */
1998     return true;
1999 }
2000
2001 function common_session_token()
2002 {
2003     common_ensure_session();
2004     if (!array_key_exists('token', $_SESSION)) {
2005         $_SESSION['token'] = common_good_rand(64);
2006     }
2007     return $_SESSION['token'];
2008 }
2009
2010 function common_cache_key($extra)
2011 {
2012     return Cache::key($extra);
2013 }
2014
2015 function common_keyize($str)
2016 {
2017     return Cache::keyize($str);
2018 }
2019
2020 function common_memcache()
2021 {
2022     return Cache::instance();
2023 }
2024
2025 function common_license_terms($uri)
2026 {
2027     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2028         return explode('-',$matches[1]);
2029     }
2030     return array($uri);
2031 }
2032
2033 function common_compatible_license($from, $to)
2034 {
2035     $from_terms = common_license_terms($from);
2036     // public domain and cc-by are compatible with everything
2037     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2038         return true;
2039     }
2040     $to_terms = common_license_terms($to);
2041     // sa is compatible across versions. IANAL
2042     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2043         return count(array_diff($from_terms, $to_terms)) == 0;
2044     }
2045     // XXX: better compatibility check needed here!
2046     // Should at least normalise URIs
2047     return ($from == $to);
2048 }
2049
2050 /**
2051  * returns a quoted table name, if required according to config
2052  */
2053 function common_database_tablename($tablename)
2054 {
2055   if(common_config('db','quote_identifiers')) {
2056       $tablename = '"'. $tablename .'"';
2057   }
2058   //table prefixes could be added here later
2059   return $tablename;
2060 }
2061
2062 /**
2063  * Shorten a URL with the current user's configured shortening service,
2064  * or ur1.ca if configured, or not at all if no shortening is set up.
2065  * Length is not considered.
2066  *
2067  * @param string $long_url
2068  * @param User $user to specify a particular user's options
2069  * @return string may return the original URL if shortening failed
2070  *
2071  * @fixme provide a way to specify a particular shortener
2072  */
2073 function common_shorten_url($long_url, User $user=null)
2074 {
2075     $long_url = trim($long_url);
2076     if (empty($user)) {
2077         // Current web session
2078         $user = common_current_user();
2079     }
2080     if (empty($user)) {
2081         // common current user does not find a user when called from the XMPP daemon
2082         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
2083         $shortenerName = 'ur1.ca';
2084     } else {
2085         $shortenerName = $user->urlshorteningservice;
2086     }
2087
2088     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
2089         //URL wasn't shortened, so return the long url
2090         return $long_url;
2091     }else{
2092         //URL was shortened, so return the result
2093         return trim($shortenedUrl);
2094     }
2095 }
2096
2097 /**
2098  * @return mixed array($proxy, $ip) for web requests; proxy may be null
2099  *               null if not a web request
2100  *
2101  * @fixme X-Forwarded-For can be chained by multiple proxies;
2102           we should parse the list and provide a cleaner array
2103  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2104  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2105  *        use function to get exact request headers from Apache if possible.
2106  */
2107 function common_client_ip()
2108 {
2109     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2110         return null;
2111     }
2112
2113     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2114         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2115             $proxy = $_SERVER['HTTP_CLIENT_IP'];
2116         } else {
2117             $proxy = $_SERVER['REMOTE_ADDR'];
2118         }
2119         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2120     } else {
2121         $proxy = null;
2122         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2123             $ip = $_SERVER['HTTP_CLIENT_IP'];
2124         } else {
2125             $ip = $_SERVER['REMOTE_ADDR'];
2126         }
2127     }
2128
2129     return array($proxy, $ip);
2130 }
2131
2132 function common_url_to_nickname($url)
2133 {
2134     static $bad = array('query', 'user', 'password', 'port', 'fragment');
2135
2136     $parts = parse_url($url);
2137
2138     # If any of these parts exist, this won't work
2139
2140     foreach ($bad as $badpart) {
2141         if (array_key_exists($badpart, $parts)) {
2142             return null;
2143         }
2144     }
2145
2146     # We just have host and/or path
2147
2148     # If it's just a host...
2149     if (array_key_exists('host', $parts) &&
2150         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2151     {
2152         $hostparts = explode('.', $parts['host']);
2153
2154         # Try to catch common idiom of nickname.service.tld
2155
2156         if ((count($hostparts) > 2) &&
2157             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2158             (strcmp($hostparts[0], 'www') != 0))
2159         {
2160             return common_nicknamize($hostparts[0]);
2161         } else {
2162             # Do the whole hostname
2163             return common_nicknamize($parts['host']);
2164         }
2165     } else {
2166         if (array_key_exists('path', $parts)) {
2167             # Strip starting, ending slashes
2168             $path = preg_replace('@/$@', '', $parts['path']);
2169             $path = preg_replace('@^/@', '', $path);
2170             $path = basename($path);
2171
2172             // Hack for MediaWiki user pages, in the form:
2173             // http://example.com/wiki/User:Myname
2174             // ('User' may be localized.)
2175             if (strpos($path, ':')) {
2176                 $parts = array_filter(explode(':', $path));
2177                 $path = $parts[count($parts) - 1];
2178             }
2179
2180             if ($path) {
2181                 return common_nicknamize($path);
2182             }
2183         }
2184     }
2185
2186     return null;
2187 }
2188
2189 function common_nicknamize($str)
2190 {
2191     $str = preg_replace('/\W/', '', $str);
2192     return strtolower($str);
2193 }
2194
2195 function common_perf_counter($key, $val=null)
2196 {
2197     global $_perfCounters;
2198     if (isset($_perfCounters)) {
2199         if (common_config('site', 'logperf')) {
2200             if (array_key_exists($key, $_perfCounters)) {
2201                 $_perfCounters[$key][] = $val;
2202             } else {
2203                 $_perfCounters[$key] = array($val);
2204             }
2205             if (common_config('site', 'logperf_detail')) {
2206                 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2207             }
2208         }
2209     }
2210 }
2211
2212 function common_log_perf_counters()
2213 {
2214     if (common_config('site', 'logperf')) {
2215         global $_startTime, $_perfCounters;
2216
2217         if (isset($_startTime)) {
2218             $endTime = microtime(true);
2219             $diff = round(($endTime - $_startTime) * 1000);
2220             common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2221         }
2222         $counters = $_perfCounters;
2223         ksort($counters);
2224         foreach ($counters as $key => $values) {
2225             $count = count($values);
2226             $unique = count(array_unique($values));
2227             common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
2228         }
2229     }
2230 }