]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
64af25f059f7ffdd9806305c57aa2238727a3b1d
[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, 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->getProfile()), $user->password)) {
249                 //internal checking passed
250                 $authenticatedUser = $user;
251             }
252         }
253     }
254     Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
255
256     return $authenticatedUser;
257 }
258
259 /**
260  * Is the current user logged in?
261  */
262 function common_logged_in()
263 {
264     return (!is_null(common_current_user()));
265 }
266
267 function common_have_session()
268 {
269     return (0 != strcmp(session_id(), ''));
270 }
271
272 function common_ensure_session()
273 {
274     $c = null;
275     if (array_key_exists(session_name(), $_COOKIE)) {
276         $c = $_COOKIE[session_name()];
277     }
278     if (!common_have_session()) {
279         if (common_config('sessions', 'handle')) {
280             Session::setSaveHandler();
281         }
282         if (array_key_exists(session_name(), $_GET)) {
283             $id = $_GET[session_name()];
284         } else if (array_key_exists(session_name(), $_COOKIE)) {
285             $id = $_COOKIE[session_name()];
286         }
287         if (isset($id)) {
288             session_id($id);
289         }
290         @session_start();
291         if (!isset($_SESSION['started'])) {
292             $_SESSION['started'] = time();
293             if (!empty($id)) {
294                 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
295                            ' is set but started value is null');
296             }
297         }
298     }
299 }
300
301 // Three kinds of arguments:
302 // 1) a user object
303 // 2) a nickname
304 // 3) null to clear
305
306 // Initialize to false; set to null if none found
307 $_cur = false;
308
309 function common_set_user($user)
310 {
311     global $_cur;
312
313     if (is_null($user) && common_have_session()) {
314         $_cur = null;
315         unset($_SESSION['userid']);
316         return true;
317     } else if (is_string($user)) {
318         $nickname = $user;
319         $user = User::getKV('nickname', $nickname);
320     } else if (!$user instanceof User) {
321         return false;
322     }
323
324     if ($user) {
325         if (Event::handle('StartSetUser', array(&$user))) {
326             if (!empty($user)) {
327                 if (!$user->hasRight(Right::WEBLOGIN)) {
328                     // TRANS: Authorisation exception thrown when a user a not allowed to login.
329                     throw new AuthorizationException(_('Not allowed to log in.'));
330                 }
331                 common_ensure_session();
332                 $_SESSION['userid'] = $user->id;
333                 $_cur = $user;
334                 Event::handle('EndSetUser', array($user));
335                 return $_cur;
336             }
337         }
338     }
339     return false;
340 }
341
342 function common_set_cookie($key, $value, $expiration=0)
343 {
344     $path = common_config('site', 'path');
345     $server = common_config('site', 'server');
346
347     if ($path && ($path != '/')) {
348         $cookiepath = '/' . $path . '/';
349     } else {
350         $cookiepath = '/';
351     }
352     return setcookie($key,
353                      $value,
354                      $expiration,
355                      $cookiepath,
356                      $server,
357                      GNUsocial::useHTTPS());
358 }
359
360 define('REMEMBERME', 'rememberme');
361 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
362
363 function common_rememberme($user=null)
364 {
365     if (!$user) {
366         $user = common_current_user();
367         if (!$user) {
368             return false;
369         }
370     }
371
372     $rm = new Remember_me();
373
374     $rm->code = common_random_hexstr(16);
375     $rm->user_id = $user->id;
376
377     // Wrap the insert in some good ol' fashioned transaction code
378
379     $rm->query('BEGIN');
380
381     $result = $rm->insert();
382
383     if (!$result) {
384         common_log_db_error($rm, 'INSERT', __FILE__);
385         $rm->query('ROLLBACK');
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 function common_purify($html)
579 {
580     require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
581
582     $cfg = HTMLPurifier_Config::createDefault();
583     $cfg->set('Attr.AllowedRel', ['bookmark', 'directory', 'enclosure', 'home', 'license', 'nofollow', 'payment', 'tag']);  // http://microformats.org/wiki/rel
584     $cfg->set('HTML.ForbiddenAttributes', array('style'));  // id, on* etc. are already filtered by default
585     $cfg->set('URI.AllowedSchemes', array_fill_keys(common_url_schemes(), true));
586
587     // Remove more elements than what the default filter removes, default in GNU social are remotely
588     // linked resources such as img, video, audio
589     $forbiddenElements = array();
590     foreach (common_config('htmlfilter') as $tag=>$filter) {
591         if ($filter === true) {
592             $forbiddenElements[] = $tag;
593         }
594     }
595     $cfg->set('HTML.ForbiddenElements', $forbiddenElements);
596
597     $html = common_remove_unicode_formatting($html);
598
599     $purifier = new HTMLPurifier($cfg);
600     $purified = $purifier->purify($html);
601     Event::handle('EndCommonPurify', array(&$purified, $html));
602     
603     return $purified;
604 }
605
606 function common_remove_unicode_formatting($text)
607 {
608     // Strip Unicode text formatting/direction codes
609     // this is pretty dangerous for visualisation of text and can be used for mischief
610     return preg_replace('/[\\x{200b}-\\x{200f}\\x{202a}-\\x{202e}]/u', '', $text);
611 }
612
613 /**
614  * Partial notice markup rendering step: build links to !group references.
615  *
616  * @param string    $text partially rendered HTML
617  * @param Profile   $author the Profile that is composing the current notice
618  * @param Notice    $parent the Notice this is sent in reply to, if any
619  * @return string partially rendered HTML
620  */
621 function common_render_content($text, Profile $author, Notice $parent=null)
622 {
623     $text = common_render_text($text);
624     $text = common_linkify_mentions($text, $author, $parent);
625     return $text;
626 }
627
628 /**
629  * Finds @-mentions within the partially-rendered text section and
630  * turns them into live links.
631  *
632  * Should generally not be called except from common_render_content().
633  *
634  * @param string    $text   partially-rendered HTML
635  * @param Profile   $author the Profile that is composing the current notice
636  * @param Notice    $parent the Notice this is sent in reply to, if any
637  * @return string partially-rendered HTML
638  */
639 function common_linkify_mentions($text, Profile $author, Notice $parent=null)
640 {
641     $mentions = common_find_mentions($text, $author, $parent);
642
643     // We need to go through in reverse order by position,
644     // so our positions stay valid despite our fudging with the
645     // string!
646
647     $points = array();
648
649     foreach ($mentions as $mention)
650     {
651         $points[$mention['position']] = $mention;
652     }
653
654     krsort($points);
655
656     foreach ($points as $position => $mention) {
657
658         $linkText = common_linkify_mention($mention);
659
660         $text = substr_replace($text, $linkText, $position, $mention['length']);
661     }
662
663     return $text;
664 }
665
666 function common_linkify_mention(array $mention)
667 {
668     $output = null;
669
670     if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
671
672         $xs = new XMLStringer(false);
673
674         $attrs = array('href' => $mention['url'],
675                        'class' => 'h-card '.$mention['type']);
676
677         if (!empty($mention['title'])) {
678             $attrs['title'] = $mention['title'];
679         }
680
681         $xs->element('a', $attrs, $mention['text']);
682
683         $output = $xs->getString();
684
685         Event::handle('EndLinkifyMention', array($mention, &$output));
686     }
687
688     return $output;
689 }
690
691 function common_get_attentions($text, Profile $sender, Notice $parent=null)
692 {
693     $mentions = common_find_mentions($text, $sender, $parent);
694     $atts = array();
695     foreach ($mentions as $mention) {
696         foreach ($mention['mentioned'] as $mentioned) {
697             $atts[$mentioned->getUri()] = $mentioned->getObjectType();
698         }
699     }
700     if ($parent instanceof Notice) {
701         $parentAuthor = $parent->getProfile();
702         // afaik groups can't be authors
703         $atts[$parentAuthor->getUri()] = ActivityObject::PERSON;
704     }
705     return $atts;
706 }
707
708 /**
709  * Find @-mentions in the given text, using the given notice object as context.
710  * References will be resolved with common_relative_profile() against the user
711  * who posted the notice.
712  *
713  * Note the return data format is internal, to be used for building links and
714  * such. Should not be used directly; rather, call common_linkify_mentions().
715  *
716  * @param string    $text
717  * @param Profile   $sender the Profile that is sending the current text
718  * @param Notice    $parent the Notice this text is in reply to, if any
719  *
720  * @return array
721  *
722  * @access private
723  */
724 function common_find_mentions($text, Profile $sender, Notice $parent=null)
725 {
726     $mentions = array();
727
728     if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
729         // Get the context of the original notice, if any
730         $origMentions = array();
731         // Does it have a parent notice for context?
732         if ($parent instanceof Notice) {
733             foreach ($parent->getAttentionProfiles() as $repliedTo) {
734                 if (!$repliedTo->isPerson()) {
735                     continue;
736                 }
737                 $origMentions[$repliedTo->id] = $repliedTo;
738             }
739         }
740
741         $matches = common_find_mentions_raw($text);
742
743         foreach ($matches as $match) {
744             try {
745                 $nickname = Nickname::normalize($match[0]);
746             } catch (NicknameException $e) {
747                 // Bogus match? Drop it.
748                 continue;
749             }
750
751                         // primarily mention the profiles mentioned in the parent
752             $mention_found_in_origMentions = false;
753             foreach($origMentions as $origMentionsId=>$origMention) {
754                 if($origMention->getNickname() == $nickname) {
755                     $mention_found_in_origMentions = $origMention;
756                     // don't mention same twice! the parent might have mentioned 
757                     // two users with same nickname on different instances
758                     unset($origMentions[$origMentionsId]);
759                     break;
760                 }
761             }
762
763             // Try to get a profile for this nickname.
764             // Start with parents mentions, then go to parents sender context
765             if ($mention_found_in_origMentions) {
766                 $mentioned = $mention_found_in_origMentions;            
767             } else if ($parent instanceof Notice && $parent->getProfile()->getNickname() === $nickname) {
768                 $mentioned = $parent->getProfile();
769             } else {
770                 // sets to null if no match
771                 $mentioned = common_relative_profile($sender, $nickname);
772             }
773
774             if ($mentioned instanceof Profile) {
775                 try {
776                     $url = $mentioned->getUri();    // prefer the URI as URL, if it is one.
777                     if (!common_valid_http_url($url)) {
778                         $url = $mentioned->getUrl();
779                     }
780                 } catch (InvalidUrlException $e) {
781                     $url = common_local_url('userbyid', array('id' => $mentioned->getID()));
782                 }
783
784                 $mention = array('mentioned' => array($mentioned),
785                                  'type' => 'mention',
786                                  'text' => $match[0],
787                                  'position' => $match[1],
788                                  'length' => mb_strlen($match[0]),
789                                  'title' => $mentioned->getFullname(),
790                                  'url' => $url);
791
792                 $mentions[] = $mention;
793             }
794         }
795
796         // @#tag => mention of all subscriptions tagged 'tag'
797
798         preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
799                        $text, $hmatches, PREG_OFFSET_CAPTURE);
800         foreach ($hmatches[1] as $hmatch) {
801             $tag = common_canonical_tag($hmatch[0]);
802             $plist = Profile_list::getByTaggerAndTag($sender->getID(), $tag);
803             if (!$plist instanceof Profile_list || $plist->private) {
804                 continue;
805             }
806             $tagged = $sender->getTaggedSubscribers($tag);
807
808             $url = common_local_url('showprofiletag',
809                                     array('nickname' => $sender->getNickname(),
810                                           'tag' => $tag));
811
812             $mentions[] = array('mentioned' => $tagged,
813                                 'type'      => 'list',
814                                 'text' => $hmatch[0],
815                                 'position' => $hmatch[1],
816                                 'length' => mb_strlen($hmatch[0]),
817                                 'url' => $url);
818         }
819
820         preg_match_all('/(?:^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/',
821                        $text, $hmatches, PREG_OFFSET_CAPTURE);
822         foreach ($hmatches[1] as $hmatch) {
823             $nickname = Nickname::normalize($hmatch[0]);
824             $group = User_group::getForNickname($nickname, $sender);
825
826             if (!$group instanceof User_group || !$sender->isMember($group)) {
827                 continue;
828             }
829
830             $profile = $group->getProfile();
831
832             $mentions[] = array('mentioned' => array($profile),
833                                 'type'      => 'group',
834                                 'text'      => $hmatch[0],
835                                 'position'  => $hmatch[1],
836                                 'length'    => mb_strlen($hmatch[0]),
837                                 'url'       => $group->permalink(),
838                                 'title'     => $group->getFancyName());
839         }
840
841         Event::handle('EndFindMentions', array($sender, $text, &$mentions));
842     }
843
844     return $mentions;
845 }
846
847 /**
848  * Does the actual regex pulls to find @-mentions in text.
849  * Should generally not be called directly; for use in common_find_mentions.
850  *
851  * @param string $text
852  * @return array of PCRE match arrays
853  */
854 function common_find_mentions_raw($text)
855 {
856     $tmatches = array();
857     preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
858                    $text,
859                    $tmatches,
860                    PREG_OFFSET_CAPTURE);
861
862     $atmatches = array();
863     // the regexp's "(?!\@)" makes sure it doesn't matches the single "@remote" in "@remote@server.com"
864     preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b(?!\@)/',
865                    $text,
866                    $atmatches,
867                    PREG_OFFSET_CAPTURE);
868
869     $matches = array_merge($tmatches[1], $atmatches[1]);
870     return $matches;
871 }
872
873 function common_render_text($text)
874 {
875     $text = common_remove_unicode_formatting($text);
876     $text = nl2br(htmlspecialchars($text));
877
878     $text = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $text);
879     $text = common_replace_urls_callback($text, 'common_linkify');
880     $text = preg_replace_callback('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/u',
881                 function ($m) { return "{$m[1]}#".common_tag_link($m[2]); }, $text);
882     // XXX: machine tags
883     return $text;
884 }
885
886 define('_URL_SCHEME_COLON_DOUBLE_SLASH', 1);
887 define('_URL_SCHEME_SINGLE_COLON', 2);
888 define('_URL_SCHEME_NO_DOMAIN', 4);
889 define('_URL_SCHEME_COLON_COORDINATES', 8);
890
891 function common_url_schemes($filter=null)
892 {
893     // TODO: move these to $config
894     $schemes = [
895                 'http'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
896                 'https'     => _URL_SCHEME_COLON_DOUBLE_SLASH,
897                 'ftp'       => _URL_SCHEME_COLON_DOUBLE_SLASH,
898                 'ftps'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
899                 'mms'       => _URL_SCHEME_COLON_DOUBLE_SLASH,
900                 'rtsp'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
901                 'gopher'    => _URL_SCHEME_COLON_DOUBLE_SLASH,
902                 'news'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
903                 'nntp'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
904                 'telnet'    => _URL_SCHEME_COLON_DOUBLE_SLASH,
905                 'wais'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
906                 'file'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
907                 'prospero'  => _URL_SCHEME_COLON_DOUBLE_SLASH,
908                 'webcal'    => _URL_SCHEME_COLON_DOUBLE_SLASH,
909                 'irc'       => _URL_SCHEME_COLON_DOUBLE_SLASH,
910                 'ircs'      => _URL_SCHEME_COLON_DOUBLE_SLASH,
911                 'aim'       => _URL_SCHEME_SINGLE_COLON,
912                 'bitcoin'   => _URL_SCHEME_SINGLE_COLON,
913                 'fax'       => _URL_SCHEME_SINGLE_COLON,
914                 'jabber'    => _URL_SCHEME_SINGLE_COLON,
915                 'mailto'    => _URL_SCHEME_SINGLE_COLON,
916                 'tel'       => _URL_SCHEME_SINGLE_COLON,
917                 'xmpp'      => _URL_SCHEME_SINGLE_COLON,
918                 'magnet'    => _URL_SCHEME_NO_DOMAIN,
919                 'geo'       => _URL_SCHEME_COLON_COORDINATES,
920                 ];
921
922     return array_keys(
923             array_filter($schemes,
924                 function ($scheme) use ($filter) {
925                     return is_null($filter) || ($scheme & $filter);
926                 })
927             );
928 }
929
930 /**
931  * Find links in the given text and pass them to the given callback function.
932  *
933  * @param string $text
934  * @param function($text, $arg) $callback: return replacement text
935  * @param mixed $arg: optional argument will be passed on to the callback
936  */
937 function common_replace_urls_callback($text, $callback, $arg = null) {
938     $geouri_labeltext_regex = '\pN\pL\-';
939     $geouri_mark_regex = '\-\_\.\!\~\*\\\'\(\)';    // the \\\' is really pretty
940     $geouri_unreserved_regex = '\pN\pL' . $geouri_mark_regex;
941     $geouri_punreserved_regex = '\[\]\:\&\+\$';
942     $geouri_pctencoded_regex = '(?:\%[0-9a-fA-F][0-9a-fA-F])';
943     $geouri_paramchar_regex = $geouri_unreserved_regex . $geouri_punreserved_regex; //FIXME: add $geouri_pctencoded_regex here so it works
944
945     // Start off with a regex
946     $regex = '#'.
947     '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
948     '('.
949         '(?:'.
950             '(?:'. //Known protocols
951                 '(?:'.
952                     '(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)'.
953                     '|'.
954                     '(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_SINGLE_COLON)) . '):)'.
955                 ')'.
956                 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
957                 '(?:'.
958                     '(?:'.
959                         '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
960                     ')|(?:'.
961                         '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
962                     ')'.
963                 ')'.
964             ')'.
965             '|(?:'.
966                 '(?:' . implode('|', common_url_schemes(_URL_SCHEME_COLON_COORDINATES)) . '):'.
967                 // There's an order that must be followed here too, if ;crs= is used, it must precede ;u=
968                 // Also 'crsp' (;crs=$crsp) must match $geouri_labeltext_regex
969                 // Also 'uval' (;u=$uval) must be a pnum: \-?[0-9]+
970                 '(?:'.
971                     '(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})'.    // 1(.23)?(,4(.56)){1,2}
972                     '(?:\;(?:['.$geouri_labeltext_regex.']+)(?:\=['.$geouri_paramchar_regex.']+)*)*'.
973                 ')'.
974             ')'.
975             // URLs without domain name, like magnet:?xt=...
976             '|(?:(?:' . implode('|', common_url_schemes(_URL_SCHEME_NO_DOMAIN)) . '):(?=\?))'.  // zero-length lookahead requires ? after :
977             (common_config('linkify', 'bare_ipv4')   // Convert IPv4 addresses to hyperlinks
978                 ? '|(?:(?: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]?)'
979                 : '').
980             (common_config('linkify', 'bare_ipv6')   // Convert IPv6 addresses to hyperlinks
981                 ? '|(?:'. //IPv6
982                     '\[?(?:(?:(?:[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})))\]?(?<!:)'.
983                     ')'
984                 : '').
985             (common_config('linkify', 'bare_domains')
986                 ? '|(?:'. //DNS
987                     '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
988                     '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
989                     //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
990                     '(?: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|ZONE|ZW|local|loc|onion)'.
991             ')(?![\pN\pL\-\_])'
992                 : '') . // if common_config('linkify', 'bare_domains') is false, don't add anything here
993         ')'.
994         '(?:'.
995             '(?:\:\d+)?'. //:port
996             '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
997             '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
998             '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
999         ')(?<![\?\.\,\#\,])'.
1000     ')'.
1001     '#ixu';
1002     //preg_match_all($regex,$text,$matches);
1003     //print_r($matches);
1004     return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
1005 }
1006
1007 /**
1008  * Intermediate callback for common_replace_links(), helps resolve some
1009  * ambiguous link forms before passing on to the final callback.
1010  *
1011  * @param array $matches
1012  * @param callable $callback
1013  * @param mixed $arg optional argument to pass on as second param to callback
1014  * @return string
1015  *
1016  * @access private
1017  */
1018 function callback_helper($matches, $callback, $arg=null) {
1019     $url=$matches[1];
1020     $left = strpos($matches[0],$url);
1021     $right = $left+strlen($url);
1022
1023     $groupSymbolSets=array(
1024         array(
1025             'left'=>'(',
1026             'right'=>')'
1027         ),
1028         array(
1029             'left'=>'[',
1030             'right'=>']'
1031         ),
1032         array(
1033             'left'=>'{',
1034             'right'=>'}'
1035         ),
1036         array(
1037             'left'=>'<',
1038             'right'=>'>'
1039         )
1040     );
1041     $cannotEndWith=array('.','?',',','#');
1042     $original_url=$url;
1043     do{
1044         $original_url=$url;
1045         foreach($groupSymbolSets as $groupSymbolSet){
1046             if(substr($url,-1)==$groupSymbolSet['right']){
1047                 $group_left_count = substr_count($url,$groupSymbolSet['left']);
1048                 $group_right_count = substr_count($url,$groupSymbolSet['right']);
1049                 if($group_left_count<$group_right_count){
1050                     $right-=1;
1051                     $url=substr($url,0,-1);
1052                 }
1053             }
1054         }
1055         if(in_array(substr($url,-1),$cannotEndWith)){
1056             $right-=1;
1057             $url=substr($url,0,-1);
1058         }
1059     }while($original_url!=$url);
1060
1061     $result = call_user_func_array($callback, array($url, $arg));
1062     return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
1063 }
1064
1065 require_once INSTALLDIR . "/lib/curry.php";
1066
1067 function common_linkify($url) {
1068     // It comes in special'd, so we unspecial it before passing to the stringifying
1069     // functions
1070     $url = htmlspecialchars_decode($url);
1071
1072     if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
1073         //url is an email address without the mailto: protocol
1074         $canon = "mailto:$url";
1075         $longurl = "mailto:$url";
1076     } else {
1077         $canon = File_redirection::_canonUrl($url);
1078         $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
1079         
1080         if(isset($longurl_data->redir_url)) {
1081                         $longurl = $longurl_data->redir_url;
1082         } else {
1083             // e.g. local files
1084                 $longurl = $longurl_data->url;
1085         }
1086     }
1087     
1088     $attrs = array('href' => $longurl, 'title' => $longurl);
1089
1090     $is_attachment = false;
1091     $attachment_id = null;
1092     $has_thumb = false;
1093
1094     // Check to see whether this is a known "attachment" URL.
1095
1096     try {
1097         $f = File::getByUrl($longurl);
1098     } catch (NoResultException $e) {
1099         if (common_config('attachments', 'process_links')) {
1100             // XXX: this writes to the database. :<
1101             try {
1102                 $f = File::processNew($longurl);
1103             } catch (ServerException $e) {
1104                 $f = null;
1105             }
1106         }
1107     }
1108
1109     if ($f instanceof File) {
1110         try {
1111             $enclosure = $f->getEnclosure();
1112             $is_attachment = true;
1113             $attachment_id = $f->id;
1114
1115             $thumb = File_thumbnail::getKV('file_id', $f->id);
1116             $has_thumb = ($thumb instanceof File_thumbnail);
1117         } catch (ServerException $e) {
1118             // There was not enough metadata available
1119         }
1120     }
1121
1122     // Add clippy
1123     if ($is_attachment) {
1124         $attrs['class'] = 'attachment';
1125         if ($has_thumb) {
1126             $attrs['class'] = 'attachment thumbnail';
1127         }
1128         $attrs['id'] = "attachment-{$attachment_id}";
1129     }
1130
1131     // Whether to nofollow
1132
1133     $nf = common_config('nofollow', 'external');
1134
1135     if ($nf == 'never') {
1136         $attrs['rel'] = 'external';
1137     } else {
1138         $attrs['rel'] = 'nofollow external';
1139     }
1140
1141     return XMLStringer::estring('a', $attrs, $url);
1142 }
1143
1144 /**
1145  * Find and shorten links in a given chunk of text if it's longer than the
1146  * configured notice content limit (or unconditionally).
1147  *
1148  * Side effects: may save file and file_redirection records for referenced URLs.
1149  *
1150  * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1151  * user's options are used; otherwise the current web session user's setitngs
1152  * will be used or ur1.ca if there is no active web login.
1153  *
1154  * @param string $text
1155  * @param boolean $always (optional)
1156  * @param User $user (optional)
1157  *
1158  * @return string
1159  */
1160 function common_shorten_links($text, $always = false, User $user=null)
1161 {
1162     if ($user === null) {
1163         $user = common_current_user();
1164     }
1165
1166     $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
1167
1168     if ($always || ($maxLength != -1 && mb_strlen($text) > $maxLength)) {
1169         return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
1170     } else {
1171         return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1172     }
1173 }
1174
1175 /**
1176  * Very basic stripping of invalid UTF-8 input text.
1177  *
1178  * @param string $str
1179  * @return mixed string or null if invalid input
1180  *
1181  * @todo ideally we should drop bad chars, and maybe do some of the checks
1182  *       from common_xml_safe_str. But we can't strip newlines, etc.
1183  * @todo Unicode normalization might also be useful, but not needed now.
1184  */
1185 function common_validate_utf8($str)
1186 {
1187     // preg_replace will return NULL on invalid UTF-8 input.
1188     //
1189     // Note: empty regex //u also caused NULL return on some
1190     // production machines, but none of our test machines.
1191     //
1192     // This should be replaced with a more reliable check.
1193     return preg_replace('/\x00/u', '', $str);
1194 }
1195
1196 /**
1197  * Make sure an arbitrary string is safe for output in XML as a single line.
1198  *
1199  * @param string $str
1200  * @return string
1201  */
1202 function common_xml_safe_str($str)
1203 {
1204     // Replace common eol and extra whitespace input chars
1205     $unWelcome = array(
1206         "\t",  // tab
1207         "\n",  // newline
1208         "\r",  // cr
1209         "\0",  // null byte eos
1210         "\x0B" // vertical tab
1211     );
1212
1213     $replacement = array(
1214         ' ', // single space
1215         ' ',
1216         '',  // nothing
1217         '',
1218         ' '
1219     );
1220
1221     $str = str_replace($unWelcome, $replacement, $str);
1222
1223     // Neutralize any additional control codes and UTF-16 surrogates
1224     // (Twitter uses '*')
1225     return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1226 }
1227
1228 function common_slugify($str)
1229 {
1230     // php5-intl is highly recommended...
1231     if (!function_exists('transliterator_transliterate')) {
1232         $str = preg_replace('/[^\pL\pN]/u', '', $str);
1233         $str = mb_convert_case($str, MB_CASE_LOWER, 'UTF-8');
1234         $str = substr($str, 0, 64);
1235         return $str;
1236     }
1237     $str = transliterator_transliterate(
1238                         'Any-Latin;' .      // any charset to latin compatible
1239                             'NFD;' .        // decompose
1240                             '[:Nonspacing Mark:] Remove;' . // remove nonspacing marks (accents etc.)
1241                             'NFC;' .        // composite again
1242                             '[:Punctuation:] Remove;' . // remove punctuation (.,¿? etc.)
1243                             'Lower();' .    // turn into lowercase
1244                             'Latin-ASCII;',  // get ASCII equivalents (ð to d for example)
1245                         $str);
1246     return preg_replace('/[^\pL\pN]/', '', $str);
1247 }
1248
1249 function common_tag_link($tag)
1250 {
1251     $canonical = common_canonical_tag($tag);
1252     if (common_config('singleuser', 'enabled')) {
1253         // regular TagAction isn't set up in 1user mode
1254         $nickname = User::singleUserNickname();
1255         $url = common_local_url('showstream',
1256                                 array('nickname' => $nickname,
1257                                       'tag' => $canonical));
1258     } else {
1259         $url = common_local_url('tag', array('tag' => $canonical));
1260     }
1261     $xs = new XMLStringer();
1262     $xs->elementStart('span', 'tag');
1263     $xs->element('a', array('href' => $url,
1264                             'rel' => 'tag'),
1265                  $tag);
1266     $xs->elementEnd('span');
1267     return $xs->getString();
1268 }
1269
1270 function common_canonical_tag($tag)
1271 {
1272     $tag = common_slugify($tag);
1273     $tag = substr($tag, 0, 64);
1274     return $tag;
1275 }
1276
1277 function common_valid_profile_tag($str)
1278 {
1279     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1280 }
1281
1282 /**
1283  * Resolve an ambiguous profile nickname reference, checking in following order:
1284  * - profiles that $sender subscribes to
1285  * - profiles that subscribe to $sender
1286  * - local user profiles
1287  *
1288  * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1289  * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1290  * ESCAPE SQL.
1291  *
1292  * @fixme validate input
1293  * @fixme escape SQL
1294  * @fixme fix or remove mystery third parameter
1295  * @fixme is $sender a User or Profile?
1296  *
1297  * @param <type> $sender the user or profile in whose context we're looking
1298  * @param string $nickname validated nickname of
1299  * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1300  *
1301  * @return Profile or null
1302  */
1303 function common_relative_profile($sender, $nickname, $dt=null)
1304 {
1305     // Will throw exception on invalid input.
1306     $nickname = Nickname::normalize($nickname);
1307
1308     // Try to find profiles this profile is subscribed to that have this nickname
1309     $recipient = new Profile();
1310     // XXX: use a join instead of a subquery
1311     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1312     $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1313     if ($recipient->find(true)) {
1314         // XXX: should probably differentiate between profiles with
1315         // the same name by date of most recent update
1316         return $recipient;
1317     }
1318     // Try to find profiles that listen to this profile and that have this nickname
1319     $recipient = new Profile();
1320     // XXX: use a join instead of a subquery
1321     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1322     $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1323     if ($recipient->find(true)) {
1324         // XXX: should probably differentiate between profiles with
1325         // the same name by date of most recent update
1326         return $recipient;
1327     }
1328     // If this is a local user, try to find a local user with that nickname.
1329     $sender = User::getKV('id', $sender->id);
1330     if ($sender instanceof User) {
1331         $recipient_user = User::getKV('nickname', $nickname);
1332         if ($recipient_user instanceof User) {
1333             return $recipient_user->getProfile();
1334         }
1335     }
1336     // Otherwise, no links. @messages from local users to remote users,
1337     // or from remote users to other remote users, are just
1338     // outside our ability to make intelligent guesses about
1339     return null;
1340 }
1341
1342 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1343 {
1344     if (Event::handle('StartLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url))) {
1345         $r = Router::get();
1346         $path = $r->build($action, $args, $params, $fragment);
1347
1348         $ssl = GNUsocial::useHTTPS();
1349
1350         if (common_config('site','fancy')) {
1351             $url = common_path($path, $ssl, $addSession);
1352         } else {
1353             if (mb_strpos($path, '/index.php') === 0) {
1354                 $url = common_path($path, $ssl, $addSession);
1355             } else {
1356                 $url = common_path('index.php/'.$path, $ssl, $addSession);
1357             }
1358         }
1359         Event::handle('EndLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url));
1360     }
1361     return $url;
1362 }
1363
1364 function common_path($relative, $ssl=false, $addSession=true)
1365 {
1366     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1367
1368     if ($ssl && GNUsocial::useHTTPS()) {
1369         $proto = 'https';
1370         if (is_string(common_config('site', 'sslserver')) &&
1371             mb_strlen(common_config('site', 'sslserver')) > 0) {
1372             $serverpart = common_config('site', 'sslserver');
1373         } else if (common_config('site', 'server')) {
1374             $serverpart = common_config('site', 'server');
1375         } else {
1376             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1377         }
1378     } else {
1379         $proto = 'http';
1380         if (common_config('site', 'server')) {
1381             $serverpart = common_config('site', 'server');
1382         } else {
1383             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1384         }
1385     }
1386
1387     if ($addSession) {
1388         $relative = common_inject_session($relative, $serverpart);
1389     }
1390
1391     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1392 }
1393
1394 // FIXME: Maybe this should also be able to handle non-fancy URLs with index.php?p=...
1395 function common_fake_local_fancy_url($url)
1396 {
1397     /**
1398      * This is a hacky fix to make URIs generated with "index.php/" match against
1399      * locally stored URIs without that. So for example if the remote site is looking
1400      * up the webfinger for some user and for some reason knows about https://some.example/user/1
1401      * but we locally store and report only https://some.example/index.php/user/1 then they would
1402      * dismiss the profile for not having an identified alias.
1403      *
1404      * There are various live instances where these issues occur, for various reasons.
1405      * Most of them being users fiddling with configuration while already having
1406      * started federating (distributing the URI to other servers) or maybe manually
1407      * editing the local database.
1408      */
1409     if (!preg_match(
1410                 // [1] protocol part, we can only rewrite http/https anyway.
1411                 '/^(https?:\/\/)' .
1412                 // [2] site name.
1413                 // FIXME: Dunno how this acts if we're aliasing ourselves with a .onion domain etc.
1414                 '('.preg_quote(common_config('site', 'server'), '/').')' .
1415                 // [3] site path, or if that is empty just '/' (to retain the /)
1416                 '('.preg_quote(common_config('site', 'path') ?: '/', '/').')' .
1417                 // [4] + [5] extract index.php (+ possible leading double /) and the rest of the URL separately.
1418                 '(\/?index\.php\/)(.*)$/', $url, $matches)) {
1419         // if preg_match failed to match
1420         throw new Exception('No known change could be made to the URL.');
1421     }
1422
1423     // now reconstruct the URL with everything except the "index.php/" part
1424     $fancy_url = '';
1425     foreach ([1,2,3,5] as $idx) {
1426         $fancy_url .= $matches[$idx];
1427     }
1428     return $fancy_url;
1429 }
1430
1431 function common_inject_session($url, $serverpart = null)
1432 {
1433     if (!common_have_session()) {
1434         return $url;
1435     }
1436
1437     if (empty($serverpart)) {
1438         $serverpart = parse_url($url, PHP_URL_HOST);
1439     }
1440
1441     $currentServer = (array_key_exists('HTTP_HOST', $_SERVER)) ? $_SERVER['HTTP_HOST'] : null;
1442
1443     // Are we pointing to another server (like an SSL server?)
1444
1445     if (!empty($currentServer) && 0 != strcasecmp($currentServer, $serverpart)) {
1446         // Pass the session ID as a GET parameter
1447         $sesspart = session_name() . '=' . session_id();
1448         $i = strpos($url, '?');
1449         if ($i === false) { // no GET params, just append
1450             $url .= '?' . $sesspart;
1451         } else {
1452             $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1453         }
1454     }
1455
1456     return $url;
1457 }
1458
1459 function common_date_string($dt)
1460 {
1461     // XXX: do some sexy date formatting
1462     // return date(DATE_RFC822, $dt);
1463     $t = strtotime($dt);
1464     $now = time();
1465     $diff = $now - $t;
1466
1467     if ($now < $t) { // that shouldn't happen!
1468         return common_exact_date($dt);
1469     } else if ($diff < 60) {
1470         // TRANS: Used in notices to indicate when the notice was made compared to now.
1471         return _('a few seconds ago');
1472     } else if ($diff < 92) {
1473         // TRANS: Used in notices to indicate when the notice was made compared to now.
1474         return _('about a minute ago');
1475     } else if ($diff < 3300) {
1476         $minutes = round($diff/60);
1477         // TRANS: Used in notices to indicate when the notice was made compared to now.
1478         return sprintf( _m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1479     } else if ($diff < 5400) {
1480         // TRANS: Used in notices to indicate when the notice was made compared to now.
1481         return _('about an hour ago');
1482     } else if ($diff < 22 * 3600) {
1483         $hours = round($diff/3600);
1484         // TRANS: Used in notices to indicate when the notice was made compared to now.
1485         return sprintf( _m('about one hour ago', 'about %d hours ago', $hours), $hours);
1486     } else if ($diff < 37 * 3600) {
1487         // TRANS: Used in notices to indicate when the notice was made compared to now.
1488         return _('about a day ago');
1489     } else if ($diff < 24 * 24 * 3600) {
1490         $days = round($diff/(24*3600));
1491         // TRANS: Used in notices to indicate when the notice was made compared to now.
1492         return sprintf( _m('about one day ago', 'about %d days ago', $days), $days);
1493     } else if ($diff < 46 * 24 * 3600) {
1494         // TRANS: Used in notices to indicate when the notice was made compared to now.
1495         return _('about a month ago');
1496     } else if ($diff < 330 * 24 * 3600) {
1497         $months = round($diff/(30*24*3600));
1498         // TRANS: Used in notices to indicate when the notice was made compared to now.
1499         return sprintf( _m('about one month ago', 'about %d months ago',$months), $months);
1500     } else if ($diff < 480 * 24 * 3600) {
1501         // TRANS: Used in notices to indicate when the notice was made compared to now.
1502         return _('about a year ago');
1503     } else {
1504         return common_exact_date($dt);
1505     }
1506 }
1507
1508 function common_exact_date($dt)
1509 {
1510     static $_utc;
1511     static $_siteTz;
1512
1513     if (!$_utc) {
1514         $_utc = new DateTimeZone('UTC');
1515         $_siteTz = new DateTimeZone(common_timezone());
1516     }
1517
1518     $dateStr = date('d F Y H:i:s', strtotime($dt));
1519     $d = new DateTime($dateStr, $_utc);
1520     $d->setTimezone($_siteTz);
1521     // TRANS: Human-readable full date-time specification (formatting on http://php.net/date)
1522     return $d->format(_('l, d-M-Y H:i:s T'));
1523 }
1524
1525 function common_date_w3dtf($dt)
1526 {
1527     $dateStr = date('d F Y H:i:s', strtotime($dt));
1528     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1529     $d->setTimezone(new DateTimeZone(common_timezone()));
1530     return $d->format(DATE_W3C);
1531 }
1532
1533 function common_date_rfc2822($dt)
1534 {
1535     $dateStr = date('d F Y H:i:s', strtotime($dt));
1536     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1537     $d->setTimezone(new DateTimeZone(common_timezone()));
1538     return $d->format('r');
1539 }
1540
1541 function common_date_iso8601($dt)
1542 {
1543     $dateStr = date('d F Y H:i:s', strtotime($dt));
1544     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1545     $d->setTimezone(new DateTimeZone(common_timezone()));
1546     return $d->format('c');
1547 }
1548
1549 function common_sql_now()
1550 {
1551     return common_sql_date(time());
1552 }
1553
1554 function common_sql_date($datetime)
1555 {
1556     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1557 }
1558
1559 /**
1560  * Return an SQL fragment to calculate an age-based weight from a given
1561  * timestamp or datetime column.
1562  *
1563  * @param string $column name of field we're comparing against current time
1564  * @param integer $dropoff divisor for age in seconds before exponentiation
1565  * @return string SQL fragment
1566  */
1567 function common_sql_weight($column, $dropoff)
1568 {
1569     if (common_config('db', 'type') == 'pgsql') {
1570         // PostgreSQL doesn't support timestampdiff function.
1571         // @fixme will this use the right time zone?
1572         // @fixme does this handle cross-year subtraction correctly?
1573         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1574     } else {
1575         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1576     }
1577 }
1578
1579 function common_redirect($url, $code=307)
1580 {
1581     static $status = array(301 => "Moved Permanently",
1582                            302 => "Found",
1583                            303 => "See Other",
1584                            307 => "Temporary Redirect");
1585
1586     header('HTTP/1.1 '.$code.' '.$status[$code]);
1587     header("Location: $url");
1588     header("Connection: close");
1589
1590     $xo = new XMLOutputter();
1591     $xo->startXML('a',
1592                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1593                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1594     $xo->element('a', array('href' => $url), $url);
1595     $xo->endXML();
1596     exit;
1597 }
1598
1599 // Stick the notice on the queue
1600
1601 function common_enqueue_notice($notice)
1602 {
1603     static $localTransports = array('ping');
1604
1605     $transports = array();
1606     if (common_config('sms', 'enabled')) {
1607         $transports[] = 'sms';
1608     }
1609     if (Event::hasHandler('HandleQueuedNotice')) {
1610         $transports[] = 'plugin';
1611     }
1612
1613     // We can skip these for gatewayed notices.
1614     if ($notice->isLocal()) {
1615         $transports = array_merge($transports, $localTransports);
1616     }
1617
1618     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1619
1620         $qm = QueueManager::get();
1621
1622         foreach ($transports as $transport)
1623         {
1624             $qm->enqueue($notice, $transport);
1625         }
1626
1627         Event::handle('EndEnqueueNotice', array($notice, $transports));
1628     }
1629
1630     return true;
1631 }
1632
1633 function common_profile_url($nickname)
1634 {
1635     return common_local_url('showstream', array('nickname' => $nickname),
1636                             null, null, false);
1637 }
1638
1639 /**
1640  * Should make up a reasonable root URL
1641  */
1642 function common_root_url($ssl=false)
1643 {
1644     $url = common_path('', $ssl, false);
1645     $i = strpos($url, '?');
1646     if ($i !== false) {
1647         $url = substr($url, 0, $i);
1648     }
1649     return $url;
1650 }
1651
1652 /**
1653  * returns $bytes bytes of raw random data
1654  */
1655 function common_random_rawstr($bytes)
1656 {
1657     $rawstr = @file_exists('/dev/urandom')
1658             ? common_urandom($bytes)
1659             : common_mtrand($bytes);
1660
1661     return $rawstr;
1662 }
1663
1664 /**
1665  * returns $bytes bytes of random data as a hexadecimal string
1666  */
1667 function common_random_hexstr($bytes)
1668 {
1669     $str = common_random_rawstr($bytes);
1670
1671     $hexstr = '';
1672     for ($i = 0; $i < $bytes; $i++) {
1673         $hexstr .= sprintf("%02x", ord($str[$i]));
1674     }
1675     return $hexstr;
1676 }
1677
1678 function common_urandom($bytes)
1679 {
1680     $h = fopen('/dev/urandom', 'rb');
1681     // should not block
1682     $src = fread($h, $bytes);
1683     fclose($h);
1684     return $src;
1685 }
1686
1687 function common_mtrand($bytes)
1688 {
1689     $str = '';
1690     for ($i = 0; $i < $bytes; $i++) {
1691         $str .= chr(mt_rand(0, 255));
1692     }
1693     return $str;
1694 }
1695
1696 /**
1697  * Record the given URL as the return destination for a future
1698  * form submission, to be read by common_get_returnto().
1699  *
1700  * @param string $url
1701  *
1702  * @fixme as a session-global setting, this can allow multiple forms
1703  * to conflict and overwrite each others' returnto destinations if
1704  * the user has multiple tabs or windows open.
1705  *
1706  * Should refactor to index with a token or otherwise only pass the
1707  * data along its intended path.
1708  */
1709 function common_set_returnto($url)
1710 {
1711     common_ensure_session();
1712     $_SESSION['returnto'] = $url;
1713 }
1714
1715 /**
1716  * Fetch a return-destination URL previously recorded by
1717  * common_set_returnto().
1718  *
1719  * @return mixed URL string or null
1720  *
1721  * @fixme as a session-global setting, this can allow multiple forms
1722  * to conflict and overwrite each others' returnto destinations if
1723  * the user has multiple tabs or windows open.
1724  *
1725  * Should refactor to index with a token or otherwise only pass the
1726  * data along its intended path.
1727  */
1728 function common_get_returnto()
1729 {
1730     common_ensure_session();
1731     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1732 }
1733
1734 function common_timestamp()
1735 {
1736     return date('YmdHis');
1737 }
1738
1739 function common_ensure_syslog()
1740 {
1741     static $initialized = false;
1742     if (!$initialized) {
1743         openlog(common_config('syslog', 'appname'), 0,
1744             common_config('syslog', 'facility'));
1745         $initialized = true;
1746     }
1747 }
1748
1749 function common_log_line($priority, $msg)
1750 {
1751     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1752                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1753     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1754 }
1755
1756 function common_request_id()
1757 {
1758     $pid = getmypid();
1759     $server = common_config('site', 'server');
1760     if (php_sapi_name() == 'cli') {
1761         $script = basename($_SERVER['PHP_SELF']);
1762         return "$server:$script:$pid";
1763     } else {
1764         static $req_id = null;
1765         if (!isset($req_id)) {
1766             $req_id = substr(md5(mt_rand()), 0, 8);
1767         }
1768         if (isset($_SERVER['REQUEST_URI'])) {
1769             $url = $_SERVER['REQUEST_URI'];
1770         }
1771         $method = $_SERVER['REQUEST_METHOD'];
1772         return "$server:$pid.$req_id $method $url";
1773     }
1774 }
1775
1776 function common_log($priority, $msg, $filename=null)
1777 {
1778     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1779         $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1780         $msg = '[' . common_request_id() . '] ' . $msg;
1781         $logfile = common_config('site', 'logfile');
1782         if ($logfile) {
1783             $log = fopen($logfile, "a");
1784             if ($log) {
1785                 $output = common_log_line($priority, $msg);
1786                 fwrite($log, $output);
1787                 fclose($log);
1788             }
1789         } else {
1790             common_ensure_syslog();
1791             syslog($priority, $msg);
1792         }
1793         Event::handle('EndLog', array($priority, $msg, $filename));
1794     }
1795 }
1796
1797 function common_debug($msg, $filename=null)
1798 {
1799     if ($filename) {
1800         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1801     } else {
1802         common_log(LOG_DEBUG, $msg);
1803     }
1804 }
1805
1806 function common_log_db_error(&$object, $verb, $filename=null)
1807 {
1808     global $_PEAR;
1809
1810     $objstr = common_log_objstring($object);
1811     $last_error = &$_PEAR->getStaticProperty('DB_DataObject','lastError');
1812     if (is_object($last_error)) {
1813         $msg = $last_error->message;
1814     } else {
1815         $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1816     }
1817     common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1818 }
1819
1820 function common_log_objstring(&$object)
1821 {
1822     if (is_null($object)) {
1823         return "null";
1824     }
1825     if (!($object instanceof DB_DataObject)) {
1826         return "(unknown)";
1827     }
1828     $arr = $object->toArray();
1829     $fields = array();
1830     foreach ($arr as $k => $v) {
1831         if (is_object($v)) {
1832             $fields[] = "$k='".get_class($v)."'";
1833         } else {
1834             $fields[] = "$k='$v'";
1835         }
1836     }
1837     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1838     return $objstring;
1839 }
1840
1841 function common_valid_http_url($url, $secure=false)
1842 {
1843     // If $secure is true, only allow https URLs to pass
1844     // (if false, we use '?' in 'https?' to say the 's' is optional)
1845     $regex = $secure ? '/^https$/' : '/^https?$/';
1846     return filter_var($url, FILTER_VALIDATE_URL)
1847             && preg_match($regex, parse_url($url, PHP_URL_SCHEME));
1848 }
1849
1850 function common_valid_tag($tag)
1851 {
1852     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1853         return (Validate::email($matches[1]) ||
1854                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1855     }
1856     return false;
1857 }
1858
1859 /**
1860  * Determine if given domain or address literal is valid
1861  * eg for use in JIDs and URLs. Does not check if the domain
1862  * exists!
1863  *
1864  * @param string $domain
1865  * @return boolean valid or not
1866  */
1867 function common_valid_domain($domain)
1868 {
1869     $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1870     $ipv4 = "(?:$octet(?:\.$octet){3})";
1871     if (preg_match("/^$ipv4$/u", $domain)) return true;
1872
1873     $group = "(?:[0-9a-f]{1,4})";
1874     $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1875
1876     if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1877         $before = explode(":", $matches[1]);
1878         $zeroes = $matches[2];
1879         $after = explode(":", $matches[3]);
1880         if ($zeroes) {
1881             $min = 0;
1882             $max = 7;
1883         } else {
1884             $min = 1;
1885             $max = 8;
1886         }
1887         $explicit = count($before) + count($after);
1888         if ($explicit < $min || $explicit > $max) {
1889             return false;
1890         }
1891         return true;
1892     }
1893
1894     try {
1895         require_once "Net/IDNA.php";
1896         $idn = Net_IDNA::getInstance();
1897         $domain = $idn->encode($domain);
1898     } catch (Exception $e) {
1899         return false;
1900     }
1901
1902     $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1903     $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1904
1905     return preg_match("/^$fqdn$/ui", $domain);
1906 }
1907
1908 /* Following functions are copied from MediaWiki GlobalFunctions.php
1909  * and written by Evan Prodromou. */
1910
1911 function common_accept_to_prefs($accept, $def = '*/*')
1912 {
1913     // No arg means accept anything (per HTTP spec)
1914     if(!$accept) {
1915         return array($def => 1);
1916     }
1917
1918     $prefs = array();
1919
1920     $parts = explode(',', $accept);
1921
1922     foreach($parts as $part) {
1923         // FIXME: doesn't deal with params like 'text/html; level=1'
1924         @list($value, $qpart) = explode(';', trim($part));
1925         $match = array();
1926         if(!isset($qpart)) {
1927             $prefs[$value] = 1;
1928         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1929             $prefs[$value] = $match[1];
1930         }
1931     }
1932
1933     return $prefs;
1934 }
1935
1936 // Match by our supported file extensions
1937 function common_supported_ext_to_mime($fileext)
1938 {
1939     // Accept a filename and take out the extension
1940     if (strpos($fileext, '.') !== false) {
1941         $fileext = substr(strrchr($fileext, '.'), 1);
1942     }
1943
1944     $supported = common_config('attachments', 'supported');
1945     if ($supported === true) {
1946         throw new ServerException('Supported extension but unknown mimetype relation.');
1947     }
1948     foreach($supported as $type => $ext) {
1949         if ($ext === $fileext) {
1950             return $type;
1951         }
1952     }
1953
1954     throw new ServerException('Unsupported file extension');
1955 }
1956
1957 // Match by our supported mime types
1958 function common_supported_mime_to_ext($mimetype)
1959 {
1960     $supported = common_config('attachments', 'supported');
1961     if ($supported === true) {
1962         throw new ServerException('Supported mimetype but unknown extension relation.');
1963     }
1964     foreach($supported as $type => $ext) {
1965         if ($mimetype === $type) {
1966             return $ext;
1967         }
1968     }
1969
1970     throw new ServerException('Unsupported MIME type');
1971 }
1972
1973 // The MIME "media" is the part before the slash (video in video/webm)
1974 function common_get_mime_media($type)
1975 {
1976     $tmp = explode('/', $type);
1977     return strtolower($tmp[0]);
1978 }
1979
1980 // Get only the mimetype and not additional info (separated from bare mime with semi-colon)
1981 function common_bare_mime($mimetype)
1982 {
1983     $mimetype = mb_strtolower($mimetype);
1984     if ($semicolon = mb_strpos($mimetype, ';')) {
1985         $mimetype = mb_substr($mimetype, 0, $semicolon);
1986     }
1987     return $mimetype;
1988 }
1989
1990 function common_mime_type_match($type, $avail)
1991 {
1992     if(array_key_exists($type, $avail)) {
1993         return $type;
1994     } else {
1995         $parts = explode('/', $type);
1996         if(array_key_exists($parts[0] . '/*', $avail)) {
1997             return $parts[0] . '/*';
1998         } elseif(array_key_exists('*/*', $avail)) {
1999             return '*/*';
2000         } else {
2001             return null;
2002         }
2003     }
2004 }
2005
2006 function common_negotiate_type($cprefs, $sprefs)
2007 {
2008     $combine = array();
2009
2010     foreach(array_keys($sprefs) as $type) {
2011         $parts = explode('/', $type);
2012         if($parts[1] != '*') {
2013             $ckey = common_mime_type_match($type, $cprefs);
2014             if($ckey) {
2015                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2016             }
2017         }
2018     }
2019
2020     foreach(array_keys($cprefs) as $type) {
2021         $parts = explode('/', $type);
2022         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
2023             $skey = common_mime_type_match($type, $sprefs);
2024             if($skey) {
2025                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2026             }
2027         }
2028     }
2029
2030     $bestq = 0;
2031     $besttype = 'text/html';
2032
2033     foreach(array_keys($combine) as $type) {
2034         if($combine[$type] > $bestq) {
2035             $besttype = $type;
2036             $bestq = $combine[$type];
2037         }
2038     }
2039
2040     if ('text/html' === $besttype) {
2041         return "text/html; charset=utf-8";
2042     }
2043     return $besttype;
2044 }
2045
2046 function common_config($main, $sub=null)
2047 {
2048     global $config;
2049     if (is_null($sub)) {
2050         // Return the config category array
2051         return array_key_exists($main, $config) ? $config[$main] : array();
2052     }
2053     // Return the config value
2054     return (array_key_exists($main, $config) &&
2055             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
2056 }
2057
2058 function common_config_set($main, $sub, $value)
2059 {
2060     global $config;
2061     if (!array_key_exists($main, $config)) {
2062         $config[$main] = array();
2063     }
2064     $config[$main][$sub] = $value;
2065 }
2066
2067 function common_config_append($main, $sub, $value)
2068 {
2069     global $config;
2070     if (!array_key_exists($main, $config)) {
2071         $config[$main] = array();
2072     }
2073     if (!array_key_exists($sub, $config[$main])) {
2074         $config[$main][$sub] = array();
2075     }
2076     if (!is_array($config[$main][$sub])) {
2077         $config[$main][$sub] = array($config[$main][$sub]);
2078     }
2079     array_push($config[$main][$sub], $value);
2080 }
2081
2082 /**
2083  * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
2084  * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
2085  *
2086  * @param array $from
2087  * @return array
2088  */
2089 function common_copy_args($from)
2090 {
2091     $to = array();
2092     $strip = get_magic_quotes_gpc();
2093     foreach ($from as $k => $v) {
2094         if(is_array($v)) {
2095             $to[$k] = common_copy_args($v);
2096         } else {
2097             if ($strip) {
2098                 $v = stripslashes($v);
2099             }
2100             $to[$k] = strval(common_validate_utf8($v));
2101         }
2102     }
2103     return $to;
2104 }
2105
2106 /**
2107  * Neutralise the evil effects of magic_quotes_gpc in the current request.
2108  * This is used before handing a request off to OAuthRequest::from_request.
2109  * @fixme Doesn't consider vars other than _POST and _GET?
2110  * @fixme Can't be undone and could corrupt data if run twice.
2111  */
2112 function common_remove_magic_from_request()
2113 {
2114     if(get_magic_quotes_gpc()) {
2115         $_POST=array_map('stripslashes',$_POST);
2116         $_GET=array_map('stripslashes',$_GET);
2117     }
2118 }
2119
2120 function common_user_uri(&$user)
2121 {
2122     return common_local_url('userbyid', array('id' => $user->id),
2123                             null, null, false);
2124 }
2125
2126 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
2127
2128 function common_confirmation_code($bits)
2129 {
2130     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
2131     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
2132     $chars = ceil($bits/5);
2133     $code = '';
2134     for ($i = 0; $i < $chars; $i++) {
2135         // XXX: convert to string and back
2136         $num = hexdec(common_random_hexstr(1));
2137         // XXX: randomness is too precious to throw away almost
2138         // 40% of the bits we get!
2139         $code .= $codechars[$num%32];
2140     }
2141     return $code;
2142 }
2143
2144 // convert markup to HTML
2145 function common_markup_to_html($c, $args=null)
2146 {
2147     if ($c === null) {
2148         return '';
2149     }
2150
2151     if (is_null($args)) {
2152         $args = array();
2153     }
2154
2155     // XXX: not very efficient
2156
2157     foreach ($args as $name => $value) {
2158         $c = preg_replace('/%%arg.'.$name.'%%/', $value, $c);
2159     }
2160
2161     $c = preg_replace_callback('/%%user.(\w+)%%/', function ($m) { return common_user_property($m[1]); }, $c);
2162     $c = preg_replace_callback('/%%action.(\w+)%%/', function ($m) { return common_local_url($m[1]); }, $c);
2163     $c = preg_replace_callback('/%%doc.(\w+)%%/', function ($m) { return common_local_url('doc', array('title'=>$m[1])); }, $c);
2164     $c = preg_replace_callback('/%%(\w+).(\w+)%%/', function ($m) { return common_config($m[1], $m[2]); }, $c);
2165
2166     return \Michelf\Markdown::defaultTransform($c);
2167 }
2168
2169 function common_user_property($property)
2170 {
2171     $profile = Profile::current();
2172
2173     if (empty($profile)) {
2174         return null;
2175     }
2176
2177     switch ($property) {
2178     case 'profileurl':
2179     case 'nickname':
2180     case 'fullname':
2181     case 'location':
2182     case 'bio':
2183         return $profile->$property;
2184         break;
2185     case 'avatar':
2186         try {
2187             return $profile->getAvatar(AVATAR_STREAM_SIZE);
2188         } catch (Exception $e) {
2189             return null;
2190         }
2191         break;
2192     case 'bestname':
2193         return $profile->getBestName();
2194         break;
2195     default:
2196         return null;
2197     }
2198 }
2199
2200 function common_profile_uri($profile)
2201 {
2202     $uri = null;
2203
2204     if (!empty($profile)) {
2205         if (Event::handle('StartCommonProfileURI', array($profile, &$uri))) {
2206             $user = User::getKV('id', $profile->id);
2207             if ($user instanceof User) {
2208                 $uri = $user->getUri();
2209             }
2210             Event::handle('EndCommonProfileURI', array($profile, &$uri));
2211         }
2212     }
2213
2214     // XXX: this is a very bad profile!
2215     return $uri;
2216 }
2217
2218 function common_canonical_sms($sms)
2219 {
2220     // strip non-digits
2221     preg_replace('/\D/', '', $sms);
2222     return $sms;
2223 }
2224
2225 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
2226 {
2227     switch ($errno) {
2228
2229      case E_ERROR:
2230      case E_COMPILE_ERROR:
2231      case E_CORE_ERROR:
2232      case E_USER_ERROR:
2233      case E_PARSE:
2234      case E_RECOVERABLE_ERROR:
2235         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
2236         die();
2237         break;
2238
2239      case E_WARNING:
2240      case E_COMPILE_WARNING:
2241      case E_CORE_WARNING:
2242      case E_USER_WARNING:
2243         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
2244         break;
2245
2246      case E_NOTICE:
2247      case E_USER_NOTICE:
2248         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
2249         break;
2250
2251      case E_STRICT:
2252      case E_DEPRECATED:
2253      case E_USER_DEPRECATED:
2254         // XXX: config variable to log this stuff, too
2255         break;
2256
2257      default:
2258         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
2259         die();
2260         break;
2261     }
2262
2263     // FIXME: show error page if we're on the Web
2264     /* Don't execute PHP internal error handler */
2265     return true;
2266 }
2267
2268 function common_session_token()
2269 {
2270     common_ensure_session();
2271     if (!array_key_exists('token', $_SESSION)) {
2272         $_SESSION['token'] = common_random_hexstr(64);
2273     }
2274     return $_SESSION['token'];
2275 }
2276
2277 function common_license_terms($uri)
2278 {
2279     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2280         return explode('-',$matches[1]);
2281     }
2282     return array($uri);
2283 }
2284
2285 function common_compatible_license($from, $to)
2286 {
2287     $from_terms = common_license_terms($from);
2288     // public domain and cc-by are compatible with everything
2289     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2290         return true;
2291     }
2292     $to_terms = common_license_terms($to);
2293     // sa is compatible across versions. IANAL
2294     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2295         return count(array_diff($from_terms, $to_terms)) == 0;
2296     }
2297     // XXX: better compatibility check needed here!
2298     // Should at least normalise URIs
2299     return ($from == $to);
2300 }
2301
2302 /**
2303  * returns a quoted table name, if required according to config
2304  */
2305 function common_database_tablename($tablename)
2306 {
2307   if(common_config('db','quote_identifiers')) {
2308       $tablename = '"'. $tablename .'"';
2309   }
2310   //table prefixes could be added here later
2311   return $tablename;
2312 }
2313
2314 /**
2315  * Shorten a URL with the current user's configured shortening service,
2316  * or ur1.ca if configured, or not at all if no shortening is set up.
2317  *
2318  * @param string  $long_url original URL
2319  * @param User $user to specify a particular user's options
2320  * @param boolean $force    Force shortening (used when notice is too long)
2321  * @return string may return the original URL if shortening failed
2322  *
2323  * @fixme provide a way to specify a particular shortener
2324  */
2325 function common_shorten_url($long_url, User $user=null, $force = false)
2326 {
2327     $long_url = trim($long_url);
2328
2329     $user = common_current_user();
2330
2331     $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
2332
2333     // $force forces shortening even if it's not strictly needed
2334     // I doubt URL shortening is ever 'strictly' needed. - ESP
2335
2336     if (($maxUrlLength == -1 || mb_strlen($long_url) < $maxUrlLength) && !$force) {
2337         return $long_url;
2338     }
2339
2340     $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
2341
2342     if (Event::handle('StartShortenUrl',
2343                       array($long_url, $shortenerName, &$shortenedUrl))) {
2344         if ($shortenerName == 'internal') {
2345             try {
2346                 $f = File::processNew($long_url);
2347                 $shortenedUrl = common_local_url('redirecturl', array('id' => $f->id));
2348                 if ((mb_strlen($shortenedUrl) < mb_strlen($long_url)) || $force) {
2349                     return $shortenedUrl;
2350                 } else {
2351                     return $long_url;
2352                 }
2353             } catch (ServerException $e) {
2354                 return $long_url;
2355             }
2356         } else {
2357             return $long_url;
2358         }
2359     } else {
2360         //URL was shortened, so return the result
2361         return trim($shortenedUrl);
2362     }
2363 }
2364
2365 /**
2366  * @return mixed array($proxy, $ip) for web requests; proxy may be null
2367  *               null if not a web request
2368  *
2369  * @fixme X-Forwarded-For can be chained by multiple proxies;
2370           we should parse the list and provide a cleaner array
2371  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2372  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2373  *        use function to get exact request headers from Apache if possible.
2374  */
2375 function common_client_ip()
2376 {
2377     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2378         return null;
2379     }
2380
2381     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2382         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2383             $proxy = $_SERVER['HTTP_CLIENT_IP'];
2384         } else {
2385             $proxy = $_SERVER['REMOTE_ADDR'];
2386         }
2387         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2388     } else {
2389         $proxy = null;
2390         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2391             $ip = $_SERVER['HTTP_CLIENT_IP'];
2392         } else {
2393             $ip = $_SERVER['REMOTE_ADDR'];
2394         }
2395     }
2396
2397     return array($proxy, $ip);
2398 }
2399
2400 function common_url_to_nickname($url)
2401 {
2402     static $bad = array('query', 'user', 'password', 'port', 'fragment');
2403
2404     $parts = parse_url($url);
2405
2406     // If any of these parts exist, this won't work
2407
2408     foreach ($bad as $badpart) {
2409         if (array_key_exists($badpart, $parts)) {
2410             return null;
2411         }
2412     }
2413
2414     // We just have host and/or path
2415
2416     // If it's just a host...
2417     if (array_key_exists('host', $parts) &&
2418         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2419     {
2420         $hostparts = explode('.', $parts['host']);
2421
2422         // Try to catch common idiom of nickname.service.tld
2423
2424         if ((count($hostparts) > 2) &&
2425             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2426             (strcmp($hostparts[0], 'www') != 0))
2427         {
2428             return common_nicknamize($hostparts[0]);
2429         } else {
2430             // Do the whole hostname
2431             return common_nicknamize($parts['host']);
2432         }
2433     } else {
2434         if (array_key_exists('path', $parts)) {
2435             // Strip starting, ending slashes
2436             $path = preg_replace('@/$@', '', $parts['path']);
2437             $path = preg_replace('@^/@', '', $path);
2438             $path = basename($path);
2439
2440             // Hack for MediaWiki user pages, in the form:
2441             // http://example.com/wiki/User:Myname
2442             // ('User' may be localized.)
2443             if (strpos($path, ':')) {
2444                 $parts = array_filter(explode(':', $path));
2445                 $path = $parts[count($parts) - 1];
2446             }
2447
2448             if ($path) {
2449                 return common_nicknamize($path);
2450             }
2451         }
2452     }
2453
2454     return null;
2455 }
2456
2457 function common_nicknamize($str)
2458 {
2459     try {
2460         return Nickname::normalize($str);
2461     } catch (NicknameException $e) {
2462         return null;
2463     }
2464 }
2465
2466 function common_perf_counter($key, $val=null)
2467 {
2468     global $_perfCounters;
2469     if (isset($_perfCounters)) {
2470         if (common_config('site', 'logperf')) {
2471             if (array_key_exists($key, $_perfCounters)) {
2472                 $_perfCounters[$key][] = $val;
2473             } else {
2474                 $_perfCounters[$key] = array($val);
2475             }
2476             if (common_config('site', 'logperf_detail')) {
2477                 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2478             }
2479         }
2480     }
2481 }
2482
2483 function common_log_perf_counters()
2484 {
2485     if (common_config('site', 'logperf')) {
2486         global $_startTime, $_perfCounters;
2487
2488         if (isset($_startTime)) {
2489             $endTime = microtime(true);
2490             $diff = round(($endTime - $_startTime) * 1000);
2491             common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2492         }
2493         $counters = $_perfCounters;
2494         ksort($counters);
2495         foreach ($counters as $key => $values) {
2496             $count = count($values);
2497             $unique = count(array_unique($values));
2498             common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
2499         }
2500     }
2501 }
2502
2503 function common_is_email($str)
2504 {
2505     return (strpos($str, '@') !== false);
2506 }
2507
2508 function common_init_stats()
2509 {
2510     global $_mem, $_ts;
2511
2512     $_mem = memory_get_usage(true);
2513     $_ts  = microtime(true);
2514 }
2515
2516 function common_log_delta($comment=null)
2517 {
2518     global $_mem, $_ts;
2519
2520     $mold = $_mem;
2521     $told = $_ts;
2522
2523     $_mem = memory_get_usage(true);
2524     $_ts  = microtime(true);
2525
2526     $mtotal = $_mem - $mold;
2527     $ttotal = $_ts - $told;
2528
2529     if (empty($comment)) {
2530         $comment = 'Delta';
2531     }
2532
2533     common_debug(sprintf("%s: %d %d", $comment, $mtotal, round($ttotal * 1000000)));
2534 }
2535
2536 function common_strip_html($html, $trim=true, $save_whitespace=false)
2537 {
2538     if (!$save_whitespace) {
2539         $html = preg_replace('/\s+/', ' ', $html);
2540     }
2541     $text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
2542     return $trim ? trim($text) : $text;
2543 }
2544
2545 function html_sprintf()
2546 {
2547     $args = func_get_args();
2548     for ($i=1; $i<count($args); $i++) {
2549         $args[$i] = htmlspecialchars($args[$i]);
2550     }
2551     return call_user_func_array('sprintf', $args);
2552 }
2553
2554 function _ve($var)
2555 {
2556     return var_export($var, true);
2557 }