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