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