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