]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch '0.9.x' into 1.0.x
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, user, files) */
21
22 /**
23  * Show a server error.
24  */
25 function common_server_error($msg, $code=500)
26 {
27     $err = new ServerErrorAction($msg, $code);
28     $err->showPage();
29 }
30
31 /**
32  * Show a user error.
33  */
34 function common_user_error($msg, $code=400)
35 {
36     $err = new ClientErrorAction($msg, $code);
37     $err->showPage();
38 }
39
40 /**
41  * This should only be used at setup; processes switching languages
42  * to send text to other users should use common_switch_locale().
43  *
44  * @param string $language Locale language code (optional; empty uses
45  *                         current user's preference or site default)
46  * @return mixed success
47  */
48 function common_init_locale($language=null)
49 {
50     if(!$language) {
51         $language = common_language();
52     }
53     putenv('LANGUAGE='.$language);
54     putenv('LANG='.$language);
55     $ok =  setlocale(LC_ALL, $language . ".utf8",
56                      $language . ".UTF8",
57                      $language . ".utf-8",
58                      $language . ".UTF-8",
59                      $language);
60
61     return $ok;
62 }
63
64 /**
65  * Initialize locale and charset settings and gettext with our message catalog,
66  * using the current user's language preference or the site default.
67  *
68  * This should generally only be run at framework initialization; code switching
69  * languages at runtime should call common_switch_language().
70  *
71  * @access private
72  */
73 function common_init_language()
74 {
75     mb_internal_encoding('UTF-8');
76
77     // Note that this setlocale() call may "fail" but this is harmless;
78     // gettext will still select the right language.
79     $language = common_language();
80     $locale_set = common_init_locale($language);
81
82     if (!$locale_set) {
83         // The requested locale doesn't exist on the system.
84         //
85         // gettext seems very picky... We first need to setlocale()
86         // to a locale which _does_ exist on the system, and _then_
87         // we can set in another locale that may not be set up
88         // (say, ga_ES for Galego/Galician) it seems to take it.
89         //
90         // For some reason C and POSIX which are guaranteed to work
91         // don't do the job. en_US.UTF-8 should be there most of the
92         // time, but not guaranteed.
93         $ok = common_init_locale("en_US");
94         if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95             // Try to find a complete, working locale on Unix/Linux...
96             // @fixme shelling out feels awfully inefficient
97             // but I don't think there's a more standard way.
98             $all = `locale -a`;
99             foreach (explode("\n", $all) as $locale) {
100                 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101                     $ok = setlocale(LC_ALL, $locale);
102                     if ($ok) {
103                         break;
104                     }
105                 }
106             }
107         }
108         if (!$ok) {
109             common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
110         }
111         $locale_set = common_init_locale($language);
112     }
113
114     common_init_gettext();
115 }
116
117 /**
118  * @access private
119  */
120 function common_init_gettext()
121 {
122     setlocale(LC_CTYPE, 'C');
123     // So we do not have to make people install the gettext locales
124     $path = common_config('site','locale_path');
125     bindtextdomain("statusnet", $path);
126     bind_textdomain_codeset("statusnet", "UTF-8");
127     textdomain("statusnet");
128 }
129
130 /**
131  * Switch locale during runtime, and poke gettext until it cries uncle.
132  * Otherwise, sometimes it doesn't actually switch away from the old language.
133  *
134  * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
135  */
136 function common_switch_locale($language=null)
137 {
138     common_init_locale($language);
139
140     setlocale(LC_CTYPE, 'C');
141     // So we do not have to make people install the gettext locales
142     $path = common_config('site','locale_path');
143     bindtextdomain("statusnet", $path);
144     bind_textdomain_codeset("statusnet", "UTF-8");
145     textdomain("statusnet");
146 }
147
148 function common_timezone()
149 {
150     if (common_logged_in()) {
151         $user = common_current_user();
152         if ($user->timezone) {
153             return $user->timezone;
154         }
155     }
156
157     return common_config('site', 'timezone');
158 }
159
160 function common_valid_language($lang)
161 {
162     if ($lang) {
163         // Validate -- we don't want to end up with a bogus code
164         // left over from some old junk.
165         foreach (common_config('site', 'languages') as $code => $info) {
166             if ($info['lang'] == $lang) {
167                 return true;
168             }
169         }
170     }
171     return false;
172 }
173
174 function common_language()
175 {
176     // Allow ?uselang=xx override, very useful for debugging
177     // and helping translators check usage and context.
178     if (isset($_GET['uselang'])) {
179         $uselang = strval($_GET['uselang']);
180         if (common_valid_language($uselang)) {
181             return $uselang;
182         }
183     }
184
185     // If there is a user logged in and they've set a language preference
186     // then return that one...
187     if (_have_config() && common_logged_in()) {
188         $user = common_current_user();
189
190         if (common_valid_language($user->language)) {
191             return $user->language;
192         }
193     }
194
195     // Otherwise, find the best match for the languages requested by the
196     // user's browser...
197     if (common_config('site', 'langdetect')) {
198         $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
199         if (!empty($httplang)) {
200             $language = client_prefered_language($httplang);
201             if ($language)
202               return $language;
203         }
204     }
205
206     // Finally, if none of the above worked, use the site's default...
207     return common_config('site', 'language');
208 }
209
210 /**
211  * Salted, hashed passwords are stored in the DB.
212  */
213 function common_munge_password($password, $id)
214 {
215     if (is_object($id) || is_object($password)) {
216         $e = new Exception();
217         common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
218                    str_replace("\n", " ", $e->getTraceAsString()));
219     }
220     return md5($password . $id);
221 }
222
223 /**
224  * Check if a username exists and has matching password.
225  */
226 function common_check_user($nickname, $password)
227 {
228     // empty nickname always unacceptable
229     if (empty($nickname)) {
230         return false;
231     }
232
233     $authenticatedUser = false;
234
235     if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
236         $user = User::staticGet('nickname', common_canonical_nickname($nickname));
237         if (!empty($user)) {
238             if (!empty($password)) { // never allow login with blank password
239                 if (0 == strcmp(common_munge_password($password, $user->id),
240                                 $user->password)) {
241                     //internal checking passed
242                     $authenticatedUser = $user;
243                 }
244             }
245         }
246         Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
247     }
248
249     return $authenticatedUser;
250 }
251
252 /**
253  * Is the current user logged in?
254  */
255 function common_logged_in()
256 {
257     return (!is_null(common_current_user()));
258 }
259
260 function common_have_session()
261 {
262     return (0 != strcmp(session_id(), ''));
263 }
264
265 function common_ensure_session()
266 {
267     $c = null;
268     if (array_key_exists(session_name(), $_COOKIE)) {
269         $c = $_COOKIE[session_name()];
270     }
271     if (!common_have_session()) {
272         if (common_config('sessions', 'handle')) {
273             Session::setSaveHandler();
274         }
275         if (array_key_exists(session_name(), $_GET)) {
276             $id = $_GET[session_name()];
277         } else if (array_key_exists(session_name(), $_COOKIE)) {
278             $id = $_COOKIE[session_name()];
279         }
280         if (isset($id)) {
281             session_id($id);
282         }
283         @session_start();
284         if (!isset($_SESSION['started'])) {
285             $_SESSION['started'] = time();
286             if (!empty($id)) {
287                 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
288                            ' is set but started value is null');
289             }
290         }
291     }
292 }
293
294 // Three kinds of arguments:
295 // 1) a user object
296 // 2) a nickname
297 // 3) null to clear
298
299 // Initialize to false; set to null if none found
300 $_cur = false;
301
302 function common_set_user($user)
303 {
304     global $_cur;
305
306     if (is_null($user) && common_have_session()) {
307         $_cur = null;
308         unset($_SESSION['userid']);
309         return true;
310     } else if (is_string($user)) {
311         $nickname = $user;
312         $user = User::staticGet('nickname', $nickname);
313     } else if (!($user instanceof User)) {
314         return false;
315     }
316
317     if ($user) {
318         if (Event::handle('StartSetUser', array(&$user))) {
319             if($user){
320                 common_ensure_session();
321                 $_SESSION['userid'] = $user->id;
322                 $_cur = $user;
323                 Event::handle('EndSetUser', array($user));
324                 return $_cur;
325             }
326         }
327     }
328     return false;
329 }
330
331 function common_set_cookie($key, $value, $expiration=0)
332 {
333     $path = common_config('site', 'path');
334     $server = common_config('site', 'server');
335
336     if ($path && ($path != '/')) {
337         $cookiepath = '/' . $path . '/';
338     } else {
339         $cookiepath = '/';
340     }
341     return setcookie($key,
342                      $value,
343                      $expiration,
344                      $cookiepath,
345                      $server,
346                      common_config('site', 'ssl')=='always');
347 }
348
349 define('REMEMBERME', 'rememberme');
350 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
351
352 function common_rememberme($user=null)
353 {
354     if (!$user) {
355         $user = common_current_user();
356         if (!$user) {
357             return false;
358         }
359     }
360
361     $rm = new Remember_me();
362
363     $rm->code = common_good_rand(16);
364     $rm->user_id = $user->id;
365
366     // Wrap the insert in some good ol' fashioned transaction code
367
368     $rm->query('BEGIN');
369
370     $result = $rm->insert();
371
372     if (!$result) {
373         common_log_db_error($rm, 'INSERT', __FILE__);
374         return false;
375     }
376
377     $rm->query('COMMIT');
378
379     $cookieval = $rm->user_id . ':' . $rm->code;
380
381     common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
382
383     common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
384
385     return true;
386 }
387
388 function common_remembered_user()
389 {
390     $user = null;
391
392     $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
393
394     if (!$packed) {
395         return null;
396     }
397
398     list($id, $code) = explode(':', $packed);
399
400     if (!$id || !$code) {
401         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
402         common_forgetme();
403         return null;
404     }
405
406     $rm = Remember_me::staticGet($code);
407
408     if (!$rm) {
409         common_log(LOG_WARNING, 'No such remember code: ' . $code);
410         common_forgetme();
411         return null;
412     }
413
414     if ($rm->user_id != $id) {
415         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
416         common_forgetme();
417         return null;
418     }
419
420     $user = User::staticGet($rm->user_id);
421
422     if (!$user) {
423         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
424         common_forgetme();
425         return null;
426     }
427
428     // successful!
429     $result = $rm->delete();
430
431     if (!$result) {
432         common_log_db_error($rm, 'DELETE', __FILE__);
433         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
434         common_forgetme();
435         return null;
436     }
437
438     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
439
440     common_set_user($user);
441     common_real_login(false);
442
443     // We issue a new cookie, so they can log in
444     // automatically again after this session
445
446     common_rememberme($user);
447
448     return $user;
449 }
450
451 /**
452  * must be called with a valid user!
453  */
454 function common_forgetme()
455 {
456     common_set_cookie(REMEMBERME, '', 0);
457 }
458
459 /**
460  * Who is the current user?
461  */
462 function common_current_user()
463 {
464     global $_cur;
465
466     if (!_have_config()) {
467         return null;
468     }
469
470     if ($_cur === false) {
471
472         if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
473             || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
474             common_ensure_session();
475             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
476             if ($id) {
477                 $user = User::staticGet($id);
478                 if ($user) {
479                         $_cur = $user;
480                         return $_cur;
481                 }
482             }
483         }
484
485         // that didn't work; try to remember; will init $_cur to null on failure
486         $_cur = common_remembered_user();
487
488         if ($_cur) {
489             // XXX: Is this necessary?
490             $_SESSION['userid'] = $_cur->id;
491         }
492     }
493
494     return $_cur;
495 }
496
497 /**
498  * Logins that are 'remembered' aren't 'real' -- they're subject to
499  * cookie-stealing. So, we don't let them do certain things. New reg,
500  * OpenID, and password logins _are_ real.
501  */
502 function common_real_login($real=true)
503 {
504     common_ensure_session();
505     $_SESSION['real_login'] = $real;
506 }
507
508 function common_is_real_login()
509 {
510     return common_logged_in() && $_SESSION['real_login'];
511 }
512
513 /**
514  * Get a hash portion for HTTP caching Etags and such including
515  * info on the current user's session. If login/logout state changes,
516  * or we've changed accounts, or we've renamed the current user,
517  * we'll get a new hash value.
518  *
519  * This should not be considered secure information.
520  *
521  * @param User $user (optional; uses common_current_user() if left out)
522  * @return string
523  */
524 function common_user_cache_hash($user=false)
525 {
526     if ($user === false) {
527         $user = common_current_user();
528     }
529     if ($user) {
530         return crc32($user->id . ':' . $user->nickname);
531     } else {
532         return '0';
533     }
534 }
535
536 // get canonical version of nickname for comparison
537 function common_canonical_nickname($nickname)
538 {
539     // XXX: UTF-8 canonicalization (like combining chars)
540     return strtolower($nickname);
541 }
542
543 // get canonical version of email for comparison
544 function common_canonical_email($email)
545 {
546     // XXX: canonicalize UTF-8
547     // XXX: lcase the domain part
548     return $email;
549 }
550
551 function common_render_content($text, $notice)
552 {
553     $r = common_render_text($text);
554     $id = $notice->profile_id;
555     $r = common_linkify_mentions($r, $notice);
556     $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
557     return $r;
558 }
559
560 function common_linkify_mentions($text, $notice)
561 {
562     $mentions = common_find_mentions($text, $notice);
563
564     // We need to go through in reverse order by position,
565     // so our positions stay valid despite our fudging with the
566     // string!
567
568     $points = array();
569
570     foreach ($mentions as $mention)
571     {
572         $points[$mention['position']] = $mention;
573     }
574
575     krsort($points);
576
577     foreach ($points as $position => $mention) {
578
579         $linkText = common_linkify_mention($mention);
580
581         $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
582     }
583
584     return $text;
585 }
586
587 function common_linkify_mention($mention)
588 {
589     $output = null;
590
591     if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
592
593         $xs = new XMLStringer(false);
594
595         $attrs = array('href' => $mention['url'],
596                        'class' => 'url');
597
598         if (!empty($mention['title'])) {
599             $attrs['title'] = $mention['title'];
600         }
601
602         $xs->elementStart('span', 'vcard');
603         $xs->elementStart('a', $attrs);
604         $xs->element('span', 'fn nickname', $mention['text']);
605         $xs->elementEnd('a');
606         $xs->elementEnd('span');
607
608         $output = $xs->getString();
609
610         Event::handle('EndLinkifyMention', array($mention, &$output));
611     }
612
613     return $output;
614 }
615
616 function common_find_mentions($text, $notice)
617 {
618     $mentions = array();
619
620     $sender = Profile::staticGet('id', $notice->profile_id);
621
622     if (empty($sender)) {
623         return $mentions;
624     }
625
626     if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
627         // Get the context of the original notice, if any
628         $originalAuthor   = null;
629         $originalNotice   = null;
630         $originalMentions = array();
631
632         // Is it a reply?
633
634         if (!empty($notice) && !empty($notice->reply_to)) {
635             $originalNotice = Notice::staticGet('id', $notice->reply_to);
636             if (!empty($originalNotice)) {
637                 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
638
639                 $ids = $originalNotice->getReplies();
640
641                 foreach ($ids as $id) {
642                     $repliedTo = Profile::staticGet('id', $id);
643                     if (!empty($repliedTo)) {
644                         $originalMentions[$repliedTo->nickname] = $repliedTo;
645                     }
646                 }
647             }
648         }
649
650         preg_match_all('/^T ([A-Z0-9]{1,64}) /',
651                        $text,
652                        $tmatches,
653                        PREG_OFFSET_CAPTURE);
654
655         preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
656                        $text,
657                        $atmatches,
658                        PREG_OFFSET_CAPTURE);
659
660         $matches = array_merge($tmatches[1], $atmatches[1]);
661
662         foreach ($matches as $match) {
663             $nickname = common_canonical_nickname($match[0]);
664
665             // Try to get a profile for this nickname.
666             // Start with conversation context, then go to
667             // sender context.
668
669             if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
670                 $mentioned = $originalAuthor;
671             } else if (!empty($originalMentions) &&
672                        array_key_exists($nickname, $originalMentions)) {
673                 $mentioned = $originalMentions[$nickname];
674             } else {
675                 $mentioned = common_relative_profile($sender, $nickname);
676             }
677
678             if (!empty($mentioned)) {
679                 $user = User::staticGet('id', $mentioned->id);
680
681                 if ($user) {
682                     $url = common_local_url('userbyid', array('id' => $user->id));
683                 } else {
684                     $url = $mentioned->profileurl;
685                 }
686
687                 $mention = array('mentioned' => array($mentioned),
688                                  'text' => $match[0],
689                                  'position' => $match[1],
690                                  'url' => $url);
691
692                 if (!empty($mentioned->fullname)) {
693                     $mention['title'] = $mentioned->fullname;
694                 }
695
696                 $mentions[] = $mention;
697             }
698         }
699
700         // @#tag => mention of all subscriptions tagged 'tag'
701
702         preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
703                        $text,
704                        $hmatches,
705                        PREG_OFFSET_CAPTURE);
706
707         foreach ($hmatches[1] as $hmatch) {
708
709             $tag = common_canonical_tag($hmatch[0]);
710
711             $tagged = Profile_tag::getTagged($sender->id, $tag);
712
713             $url = common_local_url('subscriptions',
714                                     array('nickname' => $sender->nickname,
715                                           'tag' => $tag));
716
717             $mentions[] = array('mentioned' => $tagged,
718                                 'text' => $hmatch[0],
719                                 'position' => $hmatch[1],
720                                 'url' => $url);
721         }
722
723         Event::handle('EndFindMentions', array($sender, $text, &$mentions));
724     }
725
726     return $mentions;
727 }
728
729 function common_render_text($text)
730 {
731     $r = htmlspecialchars($text);
732
733     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
734     $r = common_replace_urls_callback($r, 'common_linkify');
735     $r = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
736     // XXX: machine tags
737     return $r;
738 }
739
740 function common_replace_urls_callback($text, $callback, $notice_id = null) {
741     // Start off with a regex
742     $regex = '#'.
743     '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
744     '('.
745         '(?:'.
746             '(?:'. //Known protocols
747                 '(?:'.
748                     '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
749                     '|'.
750                     '(?:(?:mailto|aim|tel|xmpp):)'.
751                 ')'.
752                 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
753                 '(?:'.
754                     '(?:'.
755                         '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
756                     ')|(?:'.
757                         '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
758                     ')'.
759                 ')'.
760             ')'.
761             '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'. //IPv4
762             '|(?:'. //IPv6
763                 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
764             ')|(?:'. //DNS
765                 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
766                 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
767                 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
768                 '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZW|local|loc|onion)'.
769             ')(?![\pN\pL\-\_])'.
770         ')'.
771         '(?:'.
772             '(?:\:\d+)?'. //:port
773             '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
774             '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
775             '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
776         ')(?<![\?\.\,\#\,])'.
777     ')'.
778     '#ixu';
779     //preg_match_all($regex,$text,$matches);
780     //print_r($matches);
781     return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
782 }
783
784 function callback_helper($matches, $callback, $notice_id) {
785     $url=$matches[1];
786     $left = strpos($matches[0],$url);
787     $right = $left+strlen($url);
788
789     $groupSymbolSets=array(
790         array(
791             'left'=>'(',
792             'right'=>')'
793         ),
794         array(
795             'left'=>'[',
796             'right'=>']'
797         ),
798         array(
799             'left'=>'{',
800             'right'=>'}'
801         ),
802         array(
803             'left'=>'<',
804             'right'=>'>'
805         )
806     );
807     $cannotEndWith=array('.','?',',','#');
808     $original_url=$url;
809     do{
810         $original_url=$url;
811         foreach($groupSymbolSets as $groupSymbolSet){
812             if(substr($url,-1)==$groupSymbolSet['right']){
813                 $group_left_count = substr_count($url,$groupSymbolSet['left']);
814                 $group_right_count = substr_count($url,$groupSymbolSet['right']);
815                 if($group_left_count<$group_right_count){
816                     $right-=1;
817                     $url=substr($url,0,-1);
818                 }
819             }
820         }
821         if(in_array(substr($url,-1),$cannotEndWith)){
822             $right-=1;
823             $url=substr($url,0,-1);
824         }
825     }while($original_url!=$url);
826
827     if(empty($notice_id)){
828         $result = call_user_func_array($callback, array($url));
829     }else{
830         $result = call_user_func_array($callback, array(array($url,$notice_id)) );
831     }
832     return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
833 }
834
835 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
836     // lambda implementation in a separate file; PHP 5.2 won't parse it.
837     require_once INSTALLDIR . "/lib/curry.php";
838 } else {
839     function curry($fn) {
840         $args = func_get_args();
841         array_shift($args);
842         $id = uniqid('_partial');
843         $GLOBALS[$id] = array($fn, $args);
844         return create_function('',
845                                '$args = func_get_args(); '.
846                                'return call_user_func_array('.
847                                '$GLOBALS["'.$id.'"][0],'.
848                                'array_merge('.
849                                '$args,'.
850                                '$GLOBALS["'.$id.'"][1]));');
851     }
852 }
853
854 function common_linkify($url) {
855     // It comes in special'd, so we unspecial it before passing to the stringifying
856     // functions
857     $url = htmlspecialchars_decode($url);
858
859    if(strpos($url, '@') !== false && strpos($url, ':') === false) {
860        //url is an email address without the mailto: protocol
861        $canon = "mailto:$url";
862        $longurl = "mailto:$url";
863    }else{
864
865         $canon = File_redirection::_canonUrl($url);
866
867         $longurl_data = File_redirection::where($canon);
868         if (is_array($longurl_data)) {
869             $longurl = $longurl_data['url'];
870         } elseif (is_string($longurl_data)) {
871             $longurl = $longurl_data;
872         } else {
873             // Unable to reach the server to verify contents, etc
874             // Just pass the link on through for now.
875             common_log(LOG_ERR, "Can't linkify url '$url'");
876             $longurl = $url;
877         }
878     }
879
880     $attrs = array('href' => $canon, 'title' => $longurl);
881
882     $is_attachment = false;
883     $attachment_id = null;
884     $has_thumb = false;
885
886     // Check to see whether this is a known "attachment" URL.
887
888     $f = File::staticGet('url', $longurl);
889
890     if (empty($f)) {
891         // XXX: this writes to the database. :<
892         $f = File::processNew($longurl);
893     }
894
895     if (!empty($f)) {
896         if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
897             $is_attachment = true;
898             $attachment_id = $f->id;
899
900             $thumb = File_thumbnail::staticGet('file_id', $f->id);
901             if (!empty($thumb)) {
902                 $has_thumb = true;
903             }
904         }
905     }
906
907     // Add clippy
908     if ($is_attachment) {
909         $attrs['class'] = 'attachment';
910         if ($has_thumb) {
911             $attrs['class'] = 'attachment thumbnail';
912         }
913         $attrs['id'] = "attachment-{$attachment_id}";
914     }
915
916     // Whether to nofollow
917
918     $nf = common_config('nofollow', 'external');
919
920     if ($nf == 'never') {
921         $attrs['rel'] = 'external';
922     } else {
923         $attrs['rel'] = 'nofollow external';
924     }
925
926     return XMLStringer::estring('a', $attrs, $url);
927 }
928
929 function common_shorten_links($text, $always = false)
930 {
931     common_debug("common_shorten_links() called");
932
933     $user = common_current_user();
934
935     $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
936
937     common_debug("maxLength = $maxLength");
938
939     if ($always || mb_strlen($text) > $maxLength) {
940         common_debug("Forcing shortening");
941         return common_replace_urls_callback($text, array('File_redirection', 'forceShort'));
942     } else {
943         common_debug("Not forcing shortening");
944         return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
945     }
946 }
947
948 /**
949  * Very basic stripping of invalid UTF-8 input text.
950  *
951  * @param string $str
952  * @return mixed string or null if invalid input
953  *
954  * @todo ideally we should drop bad chars, and maybe do some of the checks
955  *       from common_xml_safe_str. But we can't strip newlines, etc.
956  * @todo Unicode normalization might also be useful, but not needed now.
957  */
958 function common_validate_utf8($str)
959 {
960     // preg_replace will return NULL on invalid UTF-8 input.
961     //
962     // Note: empty regex //u also caused NULL return on some
963     // production machines, but none of our test machines.
964     //
965     // This should be replaced with a more reliable check.
966     return preg_replace('/\x00/u', '', $str);
967 }
968
969 /**
970  * Make sure an arbitrary string is safe for output in XML as a single line.
971  *
972  * @param string $str
973  * @return string
974  */
975 function common_xml_safe_str($str)
976 {
977     // Replace common eol and extra whitespace input chars
978     $unWelcome = array(
979         "\t",  // tab
980         "\n",  // newline
981         "\r",  // cr
982         "\0",  // null byte eos
983         "\x0B" // vertical tab
984     );
985
986     $replacement = array(
987         ' ', // single space
988         ' ',
989         '',  // nothing
990         '',
991         ' '
992     );
993
994     $str = str_replace($unWelcome, $replacement, $str);
995
996     // Neutralize any additional control codes and UTF-16 surrogates
997     // (Twitter uses '*')
998     return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
999 }
1000
1001 function common_tag_link($tag)
1002 {
1003     $canonical = common_canonical_tag($tag);
1004     if (common_config('singleuser', 'enabled')) {
1005         // regular TagAction isn't set up in 1user mode
1006         $user = User::singleUser();
1007         $url = common_local_url('showstream',
1008                                 array('nickname' => $user->nickname,
1009                                       'tag' => $canonical));
1010     } else {
1011         $url = common_local_url('tag', array('tag' => $canonical));
1012     }
1013     $xs = new XMLStringer();
1014     $xs->elementStart('span', 'tag');
1015     $xs->element('a', array('href' => $url,
1016                             'rel' => 'tag'),
1017                  $tag);
1018     $xs->elementEnd('span');
1019     return $xs->getString();
1020 }
1021
1022 function common_canonical_tag($tag)
1023 {
1024   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1025   return str_replace(array('-', '_', '.'), '', $tag);
1026 }
1027
1028 function common_valid_profile_tag($str)
1029 {
1030     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1031 }
1032
1033 function common_group_link($sender_id, $nickname)
1034 {
1035     $sender = Profile::staticGet($sender_id);
1036     $group = User_group::getForNickname($nickname, $sender);
1037     if ($sender && $group && $sender->isMember($group)) {
1038         $attrs = array('href' => $group->permalink(),
1039                        'class' => 'url');
1040         if (!empty($group->fullname)) {
1041             $attrs['title'] = $group->getFancyName();
1042         }
1043         $xs = new XMLStringer();
1044         $xs->elementStart('span', 'vcard');
1045         $xs->elementStart('a', $attrs);
1046         $xs->element('span', 'fn nickname', $nickname);
1047         $xs->elementEnd('a');
1048         $xs->elementEnd('span');
1049         return $xs->getString();
1050     } else {
1051         return $nickname;
1052     }
1053 }
1054
1055 function common_relative_profile($sender, $nickname, $dt=null)
1056 {
1057     // Try to find profiles this profile is subscribed to that have this nickname
1058     $recipient = new Profile();
1059     // XXX: use a join instead of a subquery
1060     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1061     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1062     if ($recipient->find(true)) {
1063         // XXX: should probably differentiate between profiles with
1064         // the same name by date of most recent update
1065         return $recipient;
1066     }
1067     // Try to find profiles that listen to this profile and that have this nickname
1068     $recipient = new Profile();
1069     // XXX: use a join instead of a subquery
1070     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1071     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1072     if ($recipient->find(true)) {
1073         // XXX: should probably differentiate between profiles with
1074         // the same name by date of most recent update
1075         return $recipient;
1076     }
1077     // If this is a local user, try to find a local user with that nickname.
1078     $sender = User::staticGet($sender->id);
1079     if ($sender) {
1080         $recipient_user = User::staticGet('nickname', $nickname);
1081         if ($recipient_user) {
1082             return $recipient_user->getProfile();
1083         }
1084     }
1085     // Otherwise, no links. @messages from local users to remote users,
1086     // or from remote users to other remote users, are just
1087     // outside our ability to make intelligent guesses about
1088     return null;
1089 }
1090
1091 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1092 {
1093     $r = Router::get();
1094     $path = $r->build($action, $args, $params, $fragment);
1095
1096     $ssl = common_is_sensitive($action);
1097
1098     if (common_config('site','fancy')) {
1099         $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1100     } else {
1101         if (mb_strpos($path, '/index.php') === 0) {
1102             $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1103         } else {
1104             $url = common_path('index.php'.$path, $ssl, $addSession);
1105         }
1106     }
1107     return $url;
1108 }
1109
1110 function common_is_sensitive($action)
1111 {
1112     static $sensitive = array(
1113         'login',
1114         'register',
1115         'passwordsettings',
1116         'api',
1117         'ApiOauthRequestToken',
1118         'ApiOauthAccessToken',
1119         'ApiOauthAuthorize',
1120         'ApiOauthPin',
1121         'showapplication'
1122     );
1123     $ssl = null;
1124
1125     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1126         $ssl = in_array($action, $sensitive);
1127     }
1128
1129     return $ssl;
1130 }
1131
1132 function common_path($relative, $ssl=false, $addSession=true)
1133 {
1134     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1135
1136     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1137         || common_config('site', 'ssl') === 'always') {
1138         $proto = 'https';
1139         if (is_string(common_config('site', 'sslserver')) &&
1140             mb_strlen(common_config('site', 'sslserver')) > 0) {
1141             $serverpart = common_config('site', 'sslserver');
1142         } else if (common_config('site', 'server')) {
1143             $serverpart = common_config('site', 'server');
1144         } else {
1145             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1146         }
1147     } else {
1148         $proto = 'http';
1149         if (common_config('site', 'server')) {
1150             $serverpart = common_config('site', 'server');
1151         } else {
1152             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1153         }
1154     }
1155
1156     if ($addSession) {
1157         $relative = common_inject_session($relative, $serverpart);
1158     }
1159
1160     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1161 }
1162
1163 function common_inject_session($url, $serverpart = null)
1164 {
1165     if (common_have_session()) {
1166
1167         if (empty($serverpart)) {
1168             $serverpart = parse_url($url, PHP_URL_HOST);
1169         }
1170
1171         $currentServer = $_SERVER['HTTP_HOST'];
1172
1173         // Are we pointing to another server (like an SSL server?)
1174
1175         if (!empty($currentServer) &&
1176             0 != strcasecmp($currentServer, $serverpart)) {
1177             // Pass the session ID as a GET parameter
1178             $sesspart = session_name() . '=' . session_id();
1179             $i = strpos($url, '?');
1180             if ($i === false) { // no GET params, just append
1181                 $url .= '?' . $sesspart;
1182             } else {
1183                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1184             }
1185         }
1186     }
1187
1188     return $url;
1189 }
1190
1191 function common_date_string($dt)
1192 {
1193     // XXX: do some sexy date formatting
1194     // return date(DATE_RFC822, $dt);
1195     $t = strtotime($dt);
1196     $now = time();
1197     $diff = $now - $t;
1198
1199     if ($now < $t) { // that shouldn't happen!
1200         return common_exact_date($dt);
1201     } else if ($diff < 60) {
1202         // TRANS: Used in notices to indicate when the notice was made compared to now.
1203         return _('a few seconds ago');
1204     } else if ($diff < 92) {
1205         // TRANS: Used in notices to indicate when the notice was made compared to now.
1206         return _('about a minute ago');
1207     } else if ($diff < 3300) {
1208         $minutes = round($diff/60);
1209         // TRANS: Used in notices to indicate when the notice was made compared to now.
1210         return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1211     } else if ($diff < 5400) {
1212         // TRANS: Used in notices to indicate when the notice was made compared to now.
1213         return _('about an hour ago');
1214     } else if ($diff < 22 * 3600) {
1215         $hours = round($diff/3600);
1216         // TRANS: Used in notices to indicate when the notice was made compared to now.
1217         return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1218     } else if ($diff < 37 * 3600) {
1219         // TRANS: Used in notices to indicate when the notice was made compared to now.
1220         return _('about a day ago');
1221     } else if ($diff < 24 * 24 * 3600) {
1222         $days = round($diff/(24*3600));
1223         // TRANS: Used in notices to indicate when the notice was made compared to now.
1224         return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1225     } else if ($diff < 46 * 24 * 3600) {
1226         // TRANS: Used in notices to indicate when the notice was made compared to now.
1227         return _('about a month ago');
1228     } else if ($diff < 330 * 24 * 3600) {
1229         $months = round($diff/(30*24*3600));
1230         // TRANS: Used in notices to indicate when the notice was made compared to now.
1231         return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1232     } else if ($diff < 480 * 24 * 3600) {
1233         // TRANS: Used in notices to indicate when the notice was made compared to now.
1234         return _('about a year ago');
1235     } else {
1236         return common_exact_date($dt);
1237     }
1238 }
1239
1240 function common_exact_date($dt)
1241 {
1242     static $_utc;
1243     static $_siteTz;
1244
1245     if (!$_utc) {
1246         $_utc = new DateTimeZone('UTC');
1247         $_siteTz = new DateTimeZone(common_timezone());
1248     }
1249
1250     $dateStr = date('d F Y H:i:s', strtotime($dt));
1251     $d = new DateTime($dateStr, $_utc);
1252     $d->setTimezone($_siteTz);
1253     return $d->format(DATE_RFC850);
1254 }
1255
1256 function common_date_w3dtf($dt)
1257 {
1258     $dateStr = date('d F Y H:i:s', strtotime($dt));
1259     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1260     $d->setTimezone(new DateTimeZone(common_timezone()));
1261     return $d->format(DATE_W3C);
1262 }
1263
1264 function common_date_rfc2822($dt)
1265 {
1266     $dateStr = date('d F Y H:i:s', strtotime($dt));
1267     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1268     $d->setTimezone(new DateTimeZone(common_timezone()));
1269     return $d->format('r');
1270 }
1271
1272 function common_date_iso8601($dt)
1273 {
1274     $dateStr = date('d F Y H:i:s', strtotime($dt));
1275     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1276     $d->setTimezone(new DateTimeZone(common_timezone()));
1277     return $d->format('c');
1278 }
1279
1280 function common_sql_now()
1281 {
1282     return common_sql_date(time());
1283 }
1284
1285 function common_sql_date($datetime)
1286 {
1287     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1288 }
1289
1290 /**
1291  * Return an SQL fragment to calculate an age-based weight from a given
1292  * timestamp or datetime column.
1293  *
1294  * @param string $column name of field we're comparing against current time
1295  * @param integer $dropoff divisor for age in seconds before exponentiation
1296  * @return string SQL fragment
1297  */
1298 function common_sql_weight($column, $dropoff)
1299 {
1300     if (common_config('db', 'type') == 'pgsql') {
1301         // PostgreSQL doesn't support timestampdiff function.
1302         // @fixme will this use the right time zone?
1303         // @fixme does this handle cross-year subtraction correctly?
1304         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1305     } else {
1306         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1307     }
1308 }
1309
1310 function common_redirect($url, $code=307)
1311 {
1312     static $status = array(301 => "Moved Permanently",
1313                            302 => "Found",
1314                            303 => "See Other",
1315                            307 => "Temporary Redirect");
1316
1317     header('HTTP/1.1 '.$code.' '.$status[$code]);
1318     header("Location: $url");
1319
1320     $xo = new XMLOutputter();
1321     $xo->startXML('a',
1322                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1323                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1324     $xo->element('a', array('href' => $url), $url);
1325     $xo->endXML();
1326     exit;
1327 }
1328
1329 // Stick the notice on the queue
1330
1331 function common_enqueue_notice($notice)
1332 {
1333     static $localTransports = array('omb',
1334                                     'ping');
1335
1336     $transports = array();
1337     if (common_config('sms', 'enabled')) {
1338         $transports[] = 'sms';
1339     }
1340     if (Event::hasHandler('HandleQueuedNotice')) {
1341         $transports[] = 'plugin';
1342     }
1343
1344     // We can skip these for gatewayed notices.
1345     if ($notice->isLocal()) {
1346         $transports = array_merge($transports, $localTransports);
1347     }
1348
1349     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1350
1351         $qm = QueueManager::get();
1352
1353         foreach ($transports as $transport)
1354         {
1355             $qm->enqueue($notice, $transport);
1356         }
1357
1358         Event::handle('EndEnqueueNotice', array($notice, $transports));
1359     }
1360
1361     return true;
1362 }
1363
1364 /**
1365  * Broadcast profile updates to OMB and other remote subscribers.
1366  *
1367  * Since this may be slow with a lot of subscribers or bad remote sites,
1368  * this is run through the background queues if possible.
1369  */
1370 function common_broadcast_profile(Profile $profile)
1371 {
1372     $qm = QueueManager::get();
1373     $qm->enqueue($profile, "profile");
1374     return true;
1375 }
1376
1377 function common_profile_url($nickname)
1378 {
1379     return common_local_url('showstream', array('nickname' => $nickname),
1380                             null, null, false);
1381 }
1382
1383 /**
1384  * Should make up a reasonable root URL
1385  */
1386 function common_root_url($ssl=false)
1387 {
1388     $url = common_path('', $ssl, false);
1389     $i = strpos($url, '?');
1390     if ($i !== false) {
1391         $url = substr($url, 0, $i);
1392     }
1393     return $url;
1394 }
1395
1396 /**
1397  * returns $bytes bytes of random data as a hexadecimal string
1398  * "good" here is a goal and not a guarantee
1399  */
1400 function common_good_rand($bytes)
1401 {
1402     // XXX: use random.org...?
1403     if (@file_exists('/dev/urandom')) {
1404         return common_urandom($bytes);
1405     } else { // FIXME: this is probably not good enough
1406         return common_mtrand($bytes);
1407     }
1408 }
1409
1410 function common_urandom($bytes)
1411 {
1412     $h = fopen('/dev/urandom', 'rb');
1413     // should not block
1414     $src = fread($h, $bytes);
1415     fclose($h);
1416     $enc = '';
1417     for ($i = 0; $i < $bytes; $i++) {
1418         $enc .= sprintf("%02x", (ord($src[$i])));
1419     }
1420     return $enc;
1421 }
1422
1423 function common_mtrand($bytes)
1424 {
1425     $enc = '';
1426     for ($i = 0; $i < $bytes; $i++) {
1427         $enc .= sprintf("%02x", mt_rand(0, 255));
1428     }
1429     return $enc;
1430 }
1431
1432 /**
1433  * Record the given URL as the return destination for a future
1434  * form submission, to be read by common_get_returnto().
1435  *
1436  * @param string $url
1437  *
1438  * @fixme as a session-global setting, this can allow multiple forms
1439  * to conflict and overwrite each others' returnto destinations if
1440  * the user has multiple tabs or windows open.
1441  *
1442  * Should refactor to index with a token or otherwise only pass the
1443  * data along its intended path.
1444  */
1445 function common_set_returnto($url)
1446 {
1447     common_ensure_session();
1448     $_SESSION['returnto'] = $url;
1449 }
1450
1451 /**
1452  * Fetch a return-destination URL previously recorded by
1453  * common_set_returnto().
1454  *
1455  * @return mixed URL string or null
1456  *
1457  * @fixme as a session-global setting, this can allow multiple forms
1458  * to conflict and overwrite each others' returnto destinations if
1459  * the user has multiple tabs or windows open.
1460  *
1461  * Should refactor to index with a token or otherwise only pass the
1462  * data along its intended path.
1463  */
1464 function common_get_returnto()
1465 {
1466     common_ensure_session();
1467     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1468 }
1469
1470 function common_timestamp()
1471 {
1472     return date('YmdHis');
1473 }
1474
1475 function common_ensure_syslog()
1476 {
1477     static $initialized = false;
1478     if (!$initialized) {
1479         openlog(common_config('syslog', 'appname'), 0,
1480             common_config('syslog', 'facility'));
1481         $initialized = true;
1482     }
1483 }
1484
1485 function common_log_line($priority, $msg)
1486 {
1487     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1488                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1489     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1490 }
1491
1492 function common_request_id()
1493 {
1494     $pid = getmypid();
1495     $server = common_config('site', 'server');
1496     if (php_sapi_name() == 'cli') {
1497         $script = basename($_SERVER['PHP_SELF']);
1498         return "$server:$script:$pid";
1499     } else {
1500         static $req_id = null;
1501         if (!isset($req_id)) {
1502             $req_id = substr(md5(mt_rand()), 0, 8);
1503         }
1504         if (isset($_SERVER['REQUEST_URI'])) {
1505             $url = $_SERVER['REQUEST_URI'];
1506         }
1507         $method = $_SERVER['REQUEST_METHOD'];
1508         return "$server:$pid.$req_id $method $url";
1509     }
1510 }
1511
1512 function common_log($priority, $msg, $filename=null)
1513 {
1514     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1515         $msg = '[' . common_request_id() . '] ' . $msg;
1516         $logfile = common_config('site', 'logfile');
1517         if ($logfile) {
1518             $log = fopen($logfile, "a");
1519             if ($log) {
1520                 $output = common_log_line($priority, $msg);
1521                 fwrite($log, $output);
1522                 fclose($log);
1523             }
1524         } else {
1525             common_ensure_syslog();
1526             syslog($priority, $msg);
1527         }
1528         Event::handle('EndLog', array($priority, $msg, $filename));
1529     }
1530 }
1531
1532 function common_debug($msg, $filename=null)
1533 {
1534     if ($filename) {
1535         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1536     } else {
1537         common_log(LOG_DEBUG, $msg);
1538     }
1539 }
1540
1541 function common_log_db_error(&$object, $verb, $filename=null)
1542 {
1543     $objstr = common_log_objstring($object);
1544     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1545     if (is_object($last_error)) {
1546         $msg = $last_error->message;
1547     } else {
1548         $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1549     }
1550     common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1551 }
1552
1553 function common_log_objstring(&$object)
1554 {
1555     if (is_null($object)) {
1556         return "null";
1557     }
1558     if (!($object instanceof DB_DataObject)) {
1559         return "(unknown)";
1560     }
1561     $arr = $object->toArray();
1562     $fields = array();
1563     foreach ($arr as $k => $v) {
1564         if (is_object($v)) {
1565             $fields[] = "$k='".get_class($v)."'";
1566         } else {
1567             $fields[] = "$k='$v'";
1568         }
1569     }
1570     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1571     return $objstring;
1572 }
1573
1574 function common_valid_http_url($url)
1575 {
1576     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1577 }
1578
1579 function common_valid_tag($tag)
1580 {
1581     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1582         return (Validate::email($matches[1]) ||
1583                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1584     }
1585     return false;
1586 }
1587
1588 /**
1589  * Determine if given domain or address literal is valid
1590  * eg for use in JIDs and URLs. Does not check if the domain
1591  * exists!
1592  *
1593  * @param string $domain
1594  * @return boolean valid or not
1595  */
1596 function common_valid_domain($domain)
1597 {
1598     $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1599     $ipv4 = "(?:$octet(?:\.$octet){3})";
1600     if (preg_match("/^$ipv4$/u", $domain)) return true;
1601
1602     $group = "(?:[0-9a-f]{1,4})";
1603     $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1604
1605     if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1606         $before = explode(":", $matches[1]);
1607         $zeroes = $matches[2];
1608         $after = explode(":", $matches[3]);
1609         if ($zeroes) {
1610             $min = 0;
1611             $max = 7;
1612         } else {
1613             $min = 1;
1614             $max = 8;
1615         }
1616         $explicit = count($before) + count($after);
1617         if ($explicit < $min || $explicit > $max) {
1618             return false;
1619         }
1620         return true;
1621     }
1622
1623     try {
1624         require_once "Net/IDNA.php";
1625         $idn = Net_IDNA::getInstance();
1626         $domain = $idn->encode($domain);
1627     } catch (Exception $e) {
1628         return false;
1629     }
1630
1631     $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1632     $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1633
1634     return preg_match("/^$fqdn$/ui", $domain);
1635 }
1636
1637 /* Following functions are copied from MediaWiki GlobalFunctions.php
1638  * and written by Evan Prodromou. */
1639
1640 function common_accept_to_prefs($accept, $def = '*/*')
1641 {
1642     // No arg means accept anything (per HTTP spec)
1643     if(!$accept) {
1644         return array($def => 1);
1645     }
1646
1647     $prefs = array();
1648
1649     $parts = explode(',', $accept);
1650
1651     foreach($parts as $part) {
1652         // FIXME: doesn't deal with params like 'text/html; level=1'
1653         @list($value, $qpart) = explode(';', trim($part));
1654         $match = array();
1655         if(!isset($qpart)) {
1656             $prefs[$value] = 1;
1657         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1658             $prefs[$value] = $match[1];
1659         }
1660     }
1661
1662     return $prefs;
1663 }
1664
1665 function common_mime_type_match($type, $avail)
1666 {
1667     if(array_key_exists($type, $avail)) {
1668         return $type;
1669     } else {
1670         $parts = explode('/', $type);
1671         if(array_key_exists($parts[0] . '/*', $avail)) {
1672             return $parts[0] . '/*';
1673         } elseif(array_key_exists('*/*', $avail)) {
1674             return '*/*';
1675         } else {
1676             return null;
1677         }
1678     }
1679 }
1680
1681 function common_negotiate_type($cprefs, $sprefs)
1682 {
1683     $combine = array();
1684
1685     foreach(array_keys($sprefs) as $type) {
1686         $parts = explode('/', $type);
1687         if($parts[1] != '*') {
1688             $ckey = common_mime_type_match($type, $cprefs);
1689             if($ckey) {
1690                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1691             }
1692         }
1693     }
1694
1695     foreach(array_keys($cprefs) as $type) {
1696         $parts = explode('/', $type);
1697         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1698             $skey = common_mime_type_match($type, $sprefs);
1699             if($skey) {
1700                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1701             }
1702         }
1703     }
1704
1705     $bestq = 0;
1706     $besttype = 'text/html';
1707
1708     foreach(array_keys($combine) as $type) {
1709         if($combine[$type] > $bestq) {
1710             $besttype = $type;
1711             $bestq = $combine[$type];
1712         }
1713     }
1714
1715     if ('text/html' === $besttype) {
1716         return "text/html; charset=utf-8";
1717     }
1718     return $besttype;
1719 }
1720
1721 function common_config($main, $sub)
1722 {
1723     global $config;
1724     return (array_key_exists($main, $config) &&
1725             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1726 }
1727
1728 /**
1729  * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1730  * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1731  *
1732  * @param array $from
1733  * @return array
1734  */
1735 function common_copy_args($from)
1736 {
1737     $to = array();
1738     $strip = get_magic_quotes_gpc();
1739     foreach ($from as $k => $v) {
1740         if(is_array($v)) {
1741             $to[$k] = common_copy_args($v);
1742         } else {
1743             if ($strip) {
1744                 $v = stripslashes($v);
1745             }
1746             $to[$k] = strval(common_validate_utf8($v));
1747         }
1748     }
1749     return $to;
1750 }
1751
1752 /**
1753  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1754  * This is used before handing a request off to OAuthRequest::from_request.
1755  * @fixme Doesn't consider vars other than _POST and _GET?
1756  * @fixme Can't be undone and could corrupt data if run twice.
1757  */
1758 function common_remove_magic_from_request()
1759 {
1760     if(get_magic_quotes_gpc()) {
1761         $_POST=array_map('stripslashes',$_POST);
1762         $_GET=array_map('stripslashes',$_GET);
1763     }
1764 }
1765
1766 function common_user_uri(&$user)
1767 {
1768     return common_local_url('userbyid', array('id' => $user->id),
1769                             null, null, false);
1770 }
1771
1772 function common_notice_uri(&$notice)
1773 {
1774     return common_local_url('shownotice',
1775                             array('notice' => $notice->id),
1776                             null, null, false);
1777 }
1778
1779 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1780
1781 function common_confirmation_code($bits)
1782 {
1783     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1784     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1785     $chars = ceil($bits/5);
1786     $code = '';
1787     for ($i = 0; $i < $chars; $i++) {
1788         // XXX: convert to string and back
1789         $num = hexdec(common_good_rand(1));
1790         // XXX: randomness is too precious to throw away almost
1791         // 40% of the bits we get!
1792         $code .= $codechars[$num%32];
1793     }
1794     return $code;
1795 }
1796
1797 // convert markup to HTML
1798
1799 function common_markup_to_html($c)
1800 {
1801     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1802     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1803     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1804     return Markdown($c);
1805 }
1806
1807 function common_profile_uri($profile)
1808 {
1809     if (!$profile) {
1810         return null;
1811     }
1812     $user = User::staticGet($profile->id);
1813     if ($user) {
1814         return $user->uri;
1815     }
1816
1817     $remote = Remote_profile::staticGet($profile->id);
1818     if ($remote) {
1819         return $remote->uri;
1820     }
1821     // XXX: this is a very bad profile!
1822     return null;
1823 }
1824
1825 function common_canonical_sms($sms)
1826 {
1827     // strip non-digits
1828     preg_replace('/\D/', '', $sms);
1829     return $sms;
1830 }
1831
1832 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1833 {
1834     switch ($errno) {
1835
1836      case E_ERROR:
1837      case E_COMPILE_ERROR:
1838      case E_CORE_ERROR:
1839      case E_USER_ERROR:
1840      case E_PARSE:
1841      case E_RECOVERABLE_ERROR:
1842         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1843         die();
1844         break;
1845
1846      case E_WARNING:
1847      case E_COMPILE_WARNING:
1848      case E_CORE_WARNING:
1849      case E_USER_WARNING:
1850         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1851         break;
1852
1853      case E_NOTICE:
1854      case E_USER_NOTICE:
1855         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1856         break;
1857
1858      case E_STRICT:
1859      case E_DEPRECATED:
1860      case E_USER_DEPRECATED:
1861         // XXX: config variable to log this stuff, too
1862         break;
1863
1864      default:
1865         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1866         die();
1867         break;
1868     }
1869
1870     // FIXME: show error page if we're on the Web
1871     /* Don't execute PHP internal error handler */
1872     return true;
1873 }
1874
1875 function common_session_token()
1876 {
1877     common_ensure_session();
1878     if (!array_key_exists('token', $_SESSION)) {
1879         $_SESSION['token'] = common_good_rand(64);
1880     }
1881     return $_SESSION['token'];
1882 }
1883
1884 function common_license_terms($uri)
1885 {
1886     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1887         return explode('-',$matches[1]);
1888     }
1889     return array($uri);
1890 }
1891
1892 function common_compatible_license($from, $to)
1893 {
1894     $from_terms = common_license_terms($from);
1895     // public domain and cc-by are compatible with everything
1896     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1897         return true;
1898     }
1899     $to_terms = common_license_terms($to);
1900     // sa is compatible across versions. IANAL
1901     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1902         return count(array_diff($from_terms, $to_terms)) == 0;
1903     }
1904     // XXX: better compatibility check needed here!
1905     // Should at least normalise URIs
1906     return ($from == $to);
1907 }
1908
1909 /**
1910  * returns a quoted table name, if required according to config
1911  */
1912 function common_database_tablename($tablename)
1913 {
1914   if(common_config('db','quote_identifiers')) {
1915       $tablename = '"'. $tablename .'"';
1916   }
1917   //table prefixes could be added here later
1918   return $tablename;
1919 }
1920
1921 /**
1922  * Shorten a URL with the current user's configured shortening service,
1923  * or ur1.ca if configured, or not at all if no shortening is set up.
1924  *
1925  * @param string  $long_url original URL
1926  * @param boolean $force    Force shortening (used when notice is too long)
1927  *
1928  * @return string may return the original URL if shortening failed
1929  *
1930  * @fixme provide a way to specify a particular shortener
1931  * @fixme provide a way to specify to use a given user's shortening preferences
1932  */
1933
1934 function common_shorten_url($long_url, $force = false)
1935 {
1936     common_debug("Shortening URL '$long_url' (force = $force)");
1937
1938     $long_url = trim($long_url);
1939
1940     $user = common_current_user();
1941
1942     $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
1943     common_debug("maxUrlLength = $maxUrlLength");
1944
1945     // $force forces shortening even if it's not strictly needed
1946
1947     if (mb_strlen($long_url) < $maxUrlLength && !$force) {
1948         common_debug("Skipped shortening URL.");
1949         return $long_url;
1950     }
1951
1952     $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
1953
1954     common_debug("Shortener name = '$shortenerName'");
1955
1956     if (Event::handle('StartShortenUrl', array($long_url, $shortenerName, &$shortenedUrl))) {
1957         //URL wasn't shortened, so return the long url
1958         return $long_url;
1959     } else {
1960         //URL was shortened, so return the result
1961         return trim($shortenedUrl);
1962     }
1963 }
1964
1965 /**
1966  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1967  *               null if not a web request
1968  *
1969  * @fixme X-Forwarded-For can be chained by multiple proxies;
1970           we should parse the list and provide a cleaner array
1971  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1972  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1973  *        use function to get exact request headers from Apache if possible.
1974  */
1975 function common_client_ip()
1976 {
1977     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1978         return null;
1979     }
1980
1981     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1982         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1983             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1984         } else {
1985             $proxy = $_SERVER['REMOTE_ADDR'];
1986         }
1987         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1988     } else {
1989         $proxy = null;
1990         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1991             $ip = $_SERVER['HTTP_CLIENT_IP'];
1992         } else {
1993             $ip = $_SERVER['REMOTE_ADDR'];
1994         }
1995     }
1996
1997     return array($proxy, $ip);
1998 }
1999
2000 function common_url_to_nickname($url)
2001 {
2002     static $bad = array('query', 'user', 'password', 'port', 'fragment');
2003
2004     $parts = parse_url($url);
2005
2006     # If any of these parts exist, this won't work
2007
2008     foreach ($bad as $badpart) {
2009         if (array_key_exists($badpart, $parts)) {
2010             return null;
2011         }
2012     }
2013
2014     # We just have host and/or path
2015
2016     # If it's just a host...
2017     if (array_key_exists('host', $parts) &&
2018         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2019     {
2020         $hostparts = explode('.', $parts['host']);
2021
2022         # Try to catch common idiom of nickname.service.tld
2023
2024         if ((count($hostparts) > 2) &&
2025             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2026             (strcmp($hostparts[0], 'www') != 0))
2027         {
2028             return common_nicknamize($hostparts[0]);
2029         } else {
2030             # Do the whole hostname
2031             return common_nicknamize($parts['host']);
2032         }
2033     } else {
2034         if (array_key_exists('path', $parts)) {
2035             # Strip starting, ending slashes
2036             $path = preg_replace('@/$@', '', $parts['path']);
2037             $path = preg_replace('@^/@', '', $path);
2038             $path = basename($path);
2039
2040             // Hack for MediaWiki user pages, in the form:
2041             // http://example.com/wiki/User:Myname
2042             // ('User' may be localized.)
2043             if (strpos($path, ':')) {
2044                 $parts = array_filter(explode(':', $path));
2045                 $path = $parts[count($parts) - 1];
2046             }
2047
2048             if ($path) {
2049                 return common_nicknamize($path);
2050             }
2051         }
2052     }
2053
2054     return null;
2055 }
2056
2057 function common_nicknamize($str)
2058 {
2059     $str = preg_replace('/\W/', '', $str);
2060     return strtolower($str);
2061 }