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