]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch '0.9.x' of gitorious.org:statusnet/mainline 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 }
347
348 define('REMEMBERME', 'rememberme');
349 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
350
351 function common_rememberme($user=null)
352 {
353     if (!$user) {
354         $user = common_current_user();
355         if (!$user) {
356             return false;
357         }
358     }
359
360     $rm = new Remember_me();
361
362     $rm->code = common_good_rand(16);
363     $rm->user_id = $user->id;
364
365     // Wrap the insert in some good ol' fashioned transaction code
366
367     $rm->query('BEGIN');
368
369     $result = $rm->insert();
370
371     if (!$result) {
372         common_log_db_error($rm, 'INSERT', __FILE__);
373         return false;
374     }
375
376     $rm->query('COMMIT');
377
378     $cookieval = $rm->user_id . ':' . $rm->code;
379
380     common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
381
382     common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
383
384     return true;
385 }
386
387 function common_remembered_user()
388 {
389     $user = null;
390
391     $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
392
393     if (!$packed) {
394         return null;
395     }
396
397     list($id, $code) = explode(':', $packed);
398
399     if (!$id || !$code) {
400         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
401         common_forgetme();
402         return null;
403     }
404
405     $rm = Remember_me::staticGet($code);
406
407     if (!$rm) {
408         common_log(LOG_WARNING, 'No such remember code: ' . $code);
409         common_forgetme();
410         return null;
411     }
412
413     if ($rm->user_id != $id) {
414         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
415         common_forgetme();
416         return null;
417     }
418
419     $user = User::staticGet($rm->user_id);
420
421     if (!$user) {
422         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
423         common_forgetme();
424         return null;
425     }
426
427     // successful!
428     $result = $rm->delete();
429
430     if (!$result) {
431         common_log_db_error($rm, 'DELETE', __FILE__);
432         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
433         common_forgetme();
434         return null;
435     }
436
437     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
438
439     common_set_user($user);
440     common_real_login(false);
441
442     // We issue a new cookie, so they can log in
443     // automatically again after this session
444
445     common_rememberme($user);
446
447     return $user;
448 }
449
450 /**
451  * must be called with a valid user!
452  */
453 function common_forgetme()
454 {
455     common_set_cookie(REMEMBERME, '', 0);
456 }
457
458 /**
459  * Who is the current user?
460  */
461 function common_current_user()
462 {
463     global $_cur;
464
465     if (!_have_config()) {
466         return null;
467     }
468
469     if ($_cur === false) {
470
471         if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
472             || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
473             common_ensure_session();
474             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
475             if ($id) {
476                 $user = User::staticGet($id);
477                 if ($user) {
478                         $_cur = $user;
479                         return $_cur;
480                 }
481             }
482         }
483
484         // that didn't work; try to remember; will init $_cur to null on failure
485         $_cur = common_remembered_user();
486
487         if ($_cur) {
488             // XXX: Is this necessary?
489             $_SESSION['userid'] = $_cur->id;
490         }
491     }
492
493     return $_cur;
494 }
495
496 /**
497  * Logins that are 'remembered' aren't 'real' -- they're subject to
498  * cookie-stealing. So, we don't let them do certain things. New reg,
499  * OpenID, and password logins _are_ real.
500  */
501 function common_real_login($real=true)
502 {
503     common_ensure_session();
504     $_SESSION['real_login'] = $real;
505 }
506
507 function common_is_real_login()
508 {
509     return common_logged_in() && $_SESSION['real_login'];
510 }
511
512 /**
513  * Get a hash portion for HTTP caching Etags and such including
514  * info on the current user's session. If login/logout state changes,
515  * or we've changed accounts, or we've renamed the current user,
516  * we'll get a new hash value.
517  *
518  * This should not be considered secure information.
519  *
520  * @param User $user (optional; uses common_current_user() if left out)
521  * @return string
522  */
523 function common_user_cache_hash($user=false)
524 {
525     if ($user === false) {
526         $user = common_current_user();
527     }
528     if ($user) {
529         return crc32($user->id . ':' . $user->nickname);
530     } else {
531         return '0';
532     }
533 }
534
535 // get canonical version of nickname for comparison
536 function common_canonical_nickname($nickname)
537 {
538     // XXX: UTF-8 canonicalization (like combining chars)
539     return strtolower($nickname);
540 }
541
542 // get canonical version of email for comparison
543 function common_canonical_email($email)
544 {
545     // XXX: canonicalize UTF-8
546     // XXX: lcase the domain part
547     return $email;
548 }
549
550 function common_render_content($text, $notice)
551 {
552     $r = common_render_text($text);
553     $id = $notice->profile_id;
554     $r = common_linkify_mentions($r, $notice);
555     $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
556     return $r;
557 }
558
559 function common_linkify_mentions($text, $notice)
560 {
561     $mentions = common_find_mentions($text, $notice);
562
563     // We need to go through in reverse order by position,
564     // so our positions stay valid despite our fudging with the
565     // string!
566
567     $points = array();
568
569     foreach ($mentions as $mention)
570     {
571         $points[$mention['position']] = $mention;
572     }
573
574     krsort($points);
575
576     foreach ($points as $position => $mention) {
577
578         $linkText = common_linkify_mention($mention);
579
580         $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
581     }
582
583     return $text;
584 }
585
586 function common_linkify_mention($mention)
587 {
588     $output = null;
589
590     if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
591
592         $xs = new XMLStringer(false);
593
594         $attrs = array('href' => $mention['url'],
595                        'class' => 'url');
596
597         if (!empty($mention['title'])) {
598             $attrs['title'] = $mention['title'];
599         }
600
601         $xs->elementStart('span', 'vcard');
602         $xs->elementStart('a', $attrs);
603         $xs->element('span', 'fn nickname', $mention['text']);
604         $xs->elementEnd('a');
605         $xs->elementEnd('span');
606
607         $output = $xs->getString();
608
609         Event::handle('EndLinkifyMention', array($mention, &$output));
610     }
611
612     return $output;
613 }
614
615 function common_find_mentions($text, $notice)
616 {
617     $mentions = array();
618
619     $sender = Profile::staticGet('id', $notice->profile_id);
620
621     if (empty($sender)) {
622         return $mentions;
623     }
624
625     if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
626         // Get the context of the original notice, if any
627         $originalAuthor   = null;
628         $originalNotice   = null;
629         $originalMentions = array();
630
631         // Is it a reply?
632
633         if (!empty($notice) && !empty($notice->reply_to)) {
634             $originalNotice = Notice::staticGet('id', $notice->reply_to);
635             if (!empty($originalNotice)) {
636                 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
637
638                 $ids = $originalNotice->getReplies();
639
640                 foreach ($ids as $id) {
641                     $repliedTo = Profile::staticGet('id', $id);
642                     if (!empty($repliedTo)) {
643                         $originalMentions[$repliedTo->nickname] = $repliedTo;
644                     }
645                 }
646             }
647         }
648
649         preg_match_all('/^T ([A-Z0-9]{1,64}) /',
650                        $text,
651                        $tmatches,
652                        PREG_OFFSET_CAPTURE);
653
654         preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
655                        $text,
656                        $atmatches,
657                        PREG_OFFSET_CAPTURE);
658
659         $matches = array_merge($tmatches[1], $atmatches[1]);
660
661         foreach ($matches as $match) {
662             $nickname = common_canonical_nickname($match[0]);
663
664             // Try to get a profile for this nickname.
665             // Start with conversation context, then go to
666             // sender context.
667
668             if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
669                 $mentioned = $originalAuthor;
670             } else if (!empty($originalMentions) &&
671                        array_key_exists($nickname, $originalMentions)) {
672                 $mentioned = $originalMentions[$nickname];
673             } else {
674                 $mentioned = common_relative_profile($sender, $nickname);
675             }
676
677             if (!empty($mentioned)) {
678                 $user = User::staticGet('id', $mentioned->id);
679
680                 if ($user) {
681                     $url = common_local_url('userbyid', array('id' => $user->id));
682                 } else {
683                     $url = $mentioned->profileurl;
684                 }
685
686                 $mention = array('mentioned' => array($mentioned),
687                                  'text' => $match[0],
688                                  'position' => $match[1],
689                                  'url' => $url);
690
691                 if (!empty($mentioned->fullname)) {
692                     $mention['title'] = $mentioned->fullname;
693                 }
694
695                 $mentions[] = $mention;
696             }
697         }
698
699         // @#tag => mention of all subscriptions tagged 'tag'
700
701         preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
702                        $text,
703                        $hmatches,
704                        PREG_OFFSET_CAPTURE);
705
706         foreach ($hmatches[1] as $hmatch) {
707
708             $tag = common_canonical_tag($hmatch[0]);
709
710             $tagged = Profile_tag::getTagged($sender->id, $tag);
711
712             $url = common_local_url('subscriptions',
713                                     array('nickname' => $sender->nickname,
714                                           'tag' => $tag));
715
716             $mentions[] = array('mentioned' => $tagged,
717                                 'text' => $hmatch[0],
718                                 'position' => $hmatch[1],
719                                 'url' => $url);
720         }
721
722         Event::handle('EndFindMentions', array($sender, $text, &$mentions));
723     }
724
725     return $mentions;
726 }
727
728 function common_render_text($text)
729 {
730     $r = htmlspecialchars($text);
731
732     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
733     $r = common_replace_urls_callback($r, 'common_linkify');
734     $r = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
735     // XXX: machine tags
736     return $r;
737 }
738
739 function common_replace_urls_callback($text, $callback, $notice_id = null) {
740     // Start off with a regex
741     $regex = '#'.
742     '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
743     '('.
744         '(?:'.
745             '(?:'. //Known protocols
746                 '(?:'.
747                     '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
748                     '|'.
749                     '(?:(?:mailto|aim|tel|xmpp):)'.
750                 ')'.
751                 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
752                 '(?:'.
753                     '(?:'.
754                         '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
755                     ')|(?:'.
756                         '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
757                     ')'.
758                 ')'.
759             ')'.
760             '|(?:(?: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
761             '|(?:'. //IPv6
762                 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
763             ')|(?:'. //DNS
764                 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
765                 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
766                 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
767                 '(?: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)'.
768             ')(?![\pN\pL\-\_])'.
769         ')'.
770         '(?:'.
771             '(?:\:\d+)?'. //:port
772             '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
773             '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
774             '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
775         ')(?<![\?\.\,\#\,])'.
776     ')'.
777     '#ixu';
778     //preg_match_all($regex,$text,$matches);
779     //print_r($matches);
780     return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
781 }
782
783 function callback_helper($matches, $callback, $notice_id) {
784     $url=$matches[1];
785     $left = strpos($matches[0],$url);
786     $right = $left+strlen($url);
787
788     $groupSymbolSets=array(
789         array(
790             'left'=>'(',
791             'right'=>')'
792         ),
793         array(
794             'left'=>'[',
795             'right'=>']'
796         ),
797         array(
798             'left'=>'{',
799             'right'=>'}'
800         ),
801         array(
802             'left'=>'<',
803             'right'=>'>'
804         )
805     );
806     $cannotEndWith=array('.','?',',','#');
807     $original_url=$url;
808     do{
809         $original_url=$url;
810         foreach($groupSymbolSets as $groupSymbolSet){
811             if(substr($url,-1)==$groupSymbolSet['right']){
812                 $group_left_count = substr_count($url,$groupSymbolSet['left']);
813                 $group_right_count = substr_count($url,$groupSymbolSet['right']);
814                 if($group_left_count<$group_right_count){
815                     $right-=1;
816                     $url=substr($url,0,-1);
817                 }
818             }
819         }
820         if(in_array(substr($url,-1),$cannotEndWith)){
821             $right-=1;
822             $url=substr($url,0,-1);
823         }
824     }while($original_url!=$url);
825
826     if(empty($notice_id)){
827         $result = call_user_func_array($callback, array($url));
828     }else{
829         $result = call_user_func_array($callback, array(array($url,$notice_id)) );
830     }
831     return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
832 }
833
834 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
835     // lambda implementation in a separate file; PHP 5.2 won't parse it.
836     require_once INSTALLDIR . "/lib/curry.php";
837 } else {
838     function curry($fn) {
839         $args = func_get_args();
840         array_shift($args);
841         $id = uniqid('_partial');
842         $GLOBALS[$id] = array($fn, $args);
843         return create_function('',
844                                '$args = func_get_args(); '.
845                                'return call_user_func_array('.
846                                '$GLOBALS["'.$id.'"][0],'.
847                                'array_merge('.
848                                '$args,'.
849                                '$GLOBALS["'.$id.'"][1]));');
850     }
851 }
852
853 function common_linkify($url) {
854     // It comes in special'd, so we unspecial it before passing to the stringifying
855     // functions
856     $url = htmlspecialchars_decode($url);
857
858    if(strpos($url, '@') !== false && strpos($url, ':') === false) {
859        //url is an email address without the mailto: protocol
860        $canon = "mailto:$url";
861        $longurl = "mailto:$url";
862    }else{
863
864         $canon = File_redirection::_canonUrl($url);
865
866         $longurl_data = File_redirection::where($canon);
867         if (is_array($longurl_data)) {
868             $longurl = $longurl_data['url'];
869         } elseif (is_string($longurl_data)) {
870             $longurl = $longurl_data;
871         } else {
872             // Unable to reach the server to verify contents, etc
873             // Just pass the link on through for now.
874             common_log(LOG_ERR, "Can't linkify url '$url'");
875             $longurl = $url;
876         }
877     }
878     $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
879
880     $is_attachment = false;
881     $attachment_id = null;
882     $has_thumb = false;
883
884     // Check to see whether this is a known "attachment" URL.
885
886     $f = File::staticGet('url', $longurl);
887
888     if (empty($f)) {
889         // XXX: this writes to the database. :<
890         $f = File::processNew($longurl);
891     }
892
893     if (!empty($f)) {
894         if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
895             $is_attachment = true;
896             $attachment_id = $f->id;
897
898             $thumb = File_thumbnail::staticGet('file_id', $f->id);
899             if (!empty($thumb)) {
900                 $has_thumb = true;
901             }
902         }
903     }
904
905     // Add clippy
906     if ($is_attachment) {
907         $attrs['class'] = 'attachment';
908         if ($has_thumb) {
909             $attrs['class'] = 'attachment thumbnail';
910         }
911         $attrs['id'] = "attachment-{$attachment_id}";
912     }
913
914     return XMLStringer::estring('a', $attrs, $url);
915 }
916
917 function common_shorten_links($text, $always = false)
918 {
919     common_debug("common_shorten_links() called");
920
921     $user = common_current_user();
922
923     $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
924
925     common_debug("maxLength = $maxLength");
926
927     if ($always || mb_strlen($text) > $maxLength) {
928         common_debug("Forcing shortening");
929         return common_replace_urls_callback($text, array('File_redirection', 'forceShort'));
930     } else {
931         common_debug("Not forcing shortening");
932         return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
933     }
934 }
935
936 function common_xml_safe_str($str)
937 {
938     // Replace common eol and extra whitespace input chars
939     $unWelcome = array(
940         "\t",  // tab
941         "\n",  // newline
942         "\r",  // cr
943         "\0",  // null byte eos
944         "\x0B" // vertical tab
945     );
946
947     $replacement = array(
948         ' ', // single space
949         ' ',
950         '',  // nothing
951         '',
952         ' '
953     );
954
955     $str = str_replace($unWelcome, $replacement, $str);
956
957     // Neutralize any additional control codes and UTF-16 surrogates
958     // (Twitter uses '*')
959     return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
960 }
961
962 function common_tag_link($tag)
963 {
964     $canonical = common_canonical_tag($tag);
965     if (common_config('singleuser', 'enabled')) {
966         // regular TagAction isn't set up in 1user mode
967         $url = common_local_url('showstream',
968                                 array('nickname' => common_config('singleuser', 'nickname'),
969                                       'tag' => $canonical));
970     } else {
971         $url = common_local_url('tag', array('tag' => $canonical));
972     }
973     $xs = new XMLStringer();
974     $xs->elementStart('span', 'tag');
975     $xs->element('a', array('href' => $url,
976                             'rel' => 'tag'),
977                  $tag);
978     $xs->elementEnd('span');
979     return $xs->getString();
980 }
981
982 function common_canonical_tag($tag)
983 {
984   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
985   return str_replace(array('-', '_', '.'), '', $tag);
986 }
987
988 function common_valid_profile_tag($str)
989 {
990     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
991 }
992
993 function common_group_link($sender_id, $nickname)
994 {
995     $sender = Profile::staticGet($sender_id);
996     $group = User_group::getForNickname($nickname, $sender);
997     if ($sender && $group && $sender->isMember($group)) {
998         $attrs = array('href' => $group->permalink(),
999                        'class' => 'url');
1000         if (!empty($group->fullname)) {
1001             $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
1002         }
1003         $xs = new XMLStringer();
1004         $xs->elementStart('span', 'vcard');
1005         $xs->elementStart('a', $attrs);
1006         $xs->element('span', 'fn nickname', $nickname);
1007         $xs->elementEnd('a');
1008         $xs->elementEnd('span');
1009         return $xs->getString();
1010     } else {
1011         return $nickname;
1012     }
1013 }
1014
1015 function common_relative_profile($sender, $nickname, $dt=null)
1016 {
1017     // Try to find profiles this profile is subscribed to that have this nickname
1018     $recipient = new Profile();
1019     // XXX: use a join instead of a subquery
1020     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1021     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1022     if ($recipient->find(true)) {
1023         // XXX: should probably differentiate between profiles with
1024         // the same name by date of most recent update
1025         return $recipient;
1026     }
1027     // Try to find profiles that listen to this profile and that have this nickname
1028     $recipient = new Profile();
1029     // XXX: use a join instead of a subquery
1030     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1031     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1032     if ($recipient->find(true)) {
1033         // XXX: should probably differentiate between profiles with
1034         // the same name by date of most recent update
1035         return $recipient;
1036     }
1037     // If this is a local user, try to find a local user with that nickname.
1038     $sender = User::staticGet($sender->id);
1039     if ($sender) {
1040         $recipient_user = User::staticGet('nickname', $nickname);
1041         if ($recipient_user) {
1042             return $recipient_user->getProfile();
1043         }
1044     }
1045     // Otherwise, no links. @messages from local users to remote users,
1046     // or from remote users to other remote users, are just
1047     // outside our ability to make intelligent guesses about
1048     return null;
1049 }
1050
1051 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1052 {
1053     $r = Router::get();
1054     $path = $r->build($action, $args, $params, $fragment);
1055
1056     $ssl = common_is_sensitive($action);
1057
1058     if (common_config('site','fancy')) {
1059         $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1060     } else {
1061         if (mb_strpos($path, '/index.php') === 0) {
1062             $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1063         } else {
1064             $url = common_path('index.php'.$path, $ssl, $addSession);
1065         }
1066     }
1067     return $url;
1068 }
1069
1070 function common_is_sensitive($action)
1071 {
1072     static $sensitive = array('login', 'register', 'passwordsettings', 'api');
1073     $ssl = null;
1074
1075     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1076         $ssl = in_array($action, $sensitive);
1077     }
1078
1079     return $ssl;
1080 }
1081
1082 function common_path($relative, $ssl=false, $addSession=true)
1083 {
1084     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1085
1086     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1087         || common_config('site', 'ssl') === 'always') {
1088         $proto = 'https';
1089         if (is_string(common_config('site', 'sslserver')) &&
1090             mb_strlen(common_config('site', 'sslserver')) > 0) {
1091             $serverpart = common_config('site', 'sslserver');
1092         } else if (common_config('site', 'server')) {
1093             $serverpart = common_config('site', 'server');
1094         } else {
1095             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1096         }
1097     } else {
1098         $proto = 'http';
1099         if (common_config('site', 'server')) {
1100             $serverpart = common_config('site', 'server');
1101         } else {
1102             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1103         }
1104     }
1105
1106     if ($addSession) {
1107         $relative = common_inject_session($relative, $serverpart);
1108     }
1109
1110     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1111 }
1112
1113 function common_inject_session($url, $serverpart = null)
1114 {
1115     if (common_have_session()) {
1116
1117         if (empty($serverpart)) {
1118             $serverpart = parse_url($url, PHP_URL_HOST);
1119         }
1120
1121         $currentServer = $_SERVER['HTTP_HOST'];
1122
1123         // Are we pointing to another server (like an SSL server?)
1124
1125         if (!empty($currentServer) &&
1126             0 != strcasecmp($currentServer, $serverpart)) {
1127             // Pass the session ID as a GET parameter
1128             $sesspart = session_name() . '=' . session_id();
1129             $i = strpos($url, '?');
1130             if ($i === false) { // no GET params, just append
1131                 $url .= '?' . $sesspart;
1132             } else {
1133                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1134             }
1135         }
1136     }
1137
1138     return $url;
1139 }
1140
1141 function common_date_string($dt)
1142 {
1143     // XXX: do some sexy date formatting
1144     // return date(DATE_RFC822, $dt);
1145     $t = strtotime($dt);
1146     $now = time();
1147     $diff = $now - $t;
1148
1149     if ($now < $t) { // that shouldn't happen!
1150         return common_exact_date($dt);
1151     } else if ($diff < 60) {
1152         // TRANS: Used in notices to indicate when the notice was made compared to now.
1153         return _('a few seconds ago');
1154     } else if ($diff < 92) {
1155         // TRANS: Used in notices to indicate when the notice was made compared to now.
1156         return _('about a minute ago');
1157     } else if ($diff < 3300) {
1158         $minutes = round($diff/60);
1159         // TRANS: Used in notices to indicate when the notice was made compared to now.
1160         return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1161     } else if ($diff < 5400) {
1162         // TRANS: Used in notices to indicate when the notice was made compared to now.
1163         return _('about an hour ago');
1164     } else if ($diff < 22 * 3600) {
1165         $hours = round($diff/3600);
1166         // TRANS: Used in notices to indicate when the notice was made compared to now.
1167         return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1168     } else if ($diff < 37 * 3600) {
1169         // TRANS: Used in notices to indicate when the notice was made compared to now.
1170         return _('about a day ago');
1171     } else if ($diff < 24 * 24 * 3600) {
1172         $days = round($diff/(24*3600));
1173         // TRANS: Used in notices to indicate when the notice was made compared to now.
1174         return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1175     } else if ($diff < 46 * 24 * 3600) {
1176         // TRANS: Used in notices to indicate when the notice was made compared to now.
1177         return _('about a month ago');
1178     } else if ($diff < 330 * 24 * 3600) {
1179         $months = round($diff/(30*24*3600));
1180         // TRANS: Used in notices to indicate when the notice was made compared to now.
1181         return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1182     } else if ($diff < 480 * 24 * 3600) {
1183         // TRANS: Used in notices to indicate when the notice was made compared to now.
1184         return _('about a year ago');
1185     } else {
1186         return common_exact_date($dt);
1187     }
1188 }
1189
1190 function common_exact_date($dt)
1191 {
1192     static $_utc;
1193     static $_siteTz;
1194
1195     if (!$_utc) {
1196         $_utc = new DateTimeZone('UTC');
1197         $_siteTz = new DateTimeZone(common_timezone());
1198     }
1199
1200     $dateStr = date('d F Y H:i:s', strtotime($dt));
1201     $d = new DateTime($dateStr, $_utc);
1202     $d->setTimezone($_siteTz);
1203     return $d->format(DATE_RFC850);
1204 }
1205
1206 function common_date_w3dtf($dt)
1207 {
1208     $dateStr = date('d F Y H:i:s', strtotime($dt));
1209     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1210     $d->setTimezone(new DateTimeZone(common_timezone()));
1211     return $d->format(DATE_W3C);
1212 }
1213
1214 function common_date_rfc2822($dt)
1215 {
1216     $dateStr = date('d F Y H:i:s', strtotime($dt));
1217     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1218     $d->setTimezone(new DateTimeZone(common_timezone()));
1219     return $d->format('r');
1220 }
1221
1222 function common_date_iso8601($dt)
1223 {
1224     $dateStr = date('d F Y H:i:s', strtotime($dt));
1225     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1226     $d->setTimezone(new DateTimeZone(common_timezone()));
1227     return $d->format('c');
1228 }
1229
1230 function common_sql_now()
1231 {
1232     return common_sql_date(time());
1233 }
1234
1235 function common_sql_date($datetime)
1236 {
1237     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1238 }
1239
1240 /**
1241  * Return an SQL fragment to calculate an age-based weight from a given
1242  * timestamp or datetime column.
1243  *
1244  * @param string $column name of field we're comparing against current time
1245  * @param integer $dropoff divisor for age in seconds before exponentiation
1246  * @return string SQL fragment
1247  */
1248 function common_sql_weight($column, $dropoff)
1249 {
1250     if (common_config('db', 'type') == 'pgsql') {
1251         // PostgreSQL doesn't support timestampdiff function.
1252         // @fixme will this use the right time zone?
1253         // @fixme does this handle cross-year subtraction correctly?
1254         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1255     } else {
1256         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1257     }
1258 }
1259
1260 function common_redirect($url, $code=307)
1261 {
1262     static $status = array(301 => "Moved Permanently",
1263                            302 => "Found",
1264                            303 => "See Other",
1265                            307 => "Temporary Redirect");
1266
1267     header('HTTP/1.1 '.$code.' '.$status[$code]);
1268     header("Location: $url");
1269
1270     $xo = new XMLOutputter();
1271     $xo->startXML('a',
1272                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1273                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1274     $xo->element('a', array('href' => $url), $url);
1275     $xo->endXML();
1276     exit;
1277 }
1278
1279 // Stick the notice on the queue
1280
1281 function common_enqueue_notice($notice)
1282 {
1283     static $localTransports = array('omb',
1284                                     'ping');
1285
1286     $transports = array();
1287     if (common_config('sms', 'enabled')) {
1288         $transports[] = 'sms';
1289     }
1290     if (Event::hasHandler('HandleQueuedNotice')) {
1291         $transports[] = 'plugin';
1292     }
1293
1294     // We can skip these for gatewayed notices.
1295     if ($notice->isLocal()) {
1296         $transports = array_merge($transports, $localTransports);
1297     }
1298
1299     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1300
1301         $qm = QueueManager::get();
1302
1303         foreach ($transports as $transport)
1304         {
1305             $qm->enqueue($notice, $transport);
1306         }
1307
1308         Event::handle('EndEnqueueNotice', array($notice, $transports));
1309     }
1310
1311     return true;
1312 }
1313
1314 /**
1315  * Broadcast profile updates to OMB and other remote subscribers.
1316  *
1317  * Since this may be slow with a lot of subscribers or bad remote sites,
1318  * this is run through the background queues if possible.
1319  */
1320 function common_broadcast_profile(Profile $profile)
1321 {
1322     $qm = QueueManager::get();
1323     $qm->enqueue($profile, "profile");
1324     return true;
1325 }
1326
1327 function common_profile_url($nickname)
1328 {
1329     return common_local_url('showstream', array('nickname' => $nickname),
1330                             null, null, false);
1331 }
1332
1333 /**
1334  * Should make up a reasonable root URL
1335  */
1336 function common_root_url($ssl=false)
1337 {
1338     $url = common_path('', $ssl, false);
1339     $i = strpos($url, '?');
1340     if ($i !== false) {
1341         $url = substr($url, 0, $i);
1342     }
1343     return $url;
1344 }
1345
1346 /**
1347  * returns $bytes bytes of random data as a hexadecimal string
1348  * "good" here is a goal and not a guarantee
1349  */
1350 function common_good_rand($bytes)
1351 {
1352     // XXX: use random.org...?
1353     if (@file_exists('/dev/urandom')) {
1354         return common_urandom($bytes);
1355     } else { // FIXME: this is probably not good enough
1356         return common_mtrand($bytes);
1357     }
1358 }
1359
1360 function common_urandom($bytes)
1361 {
1362     $h = fopen('/dev/urandom', 'rb');
1363     // should not block
1364     $src = fread($h, $bytes);
1365     fclose($h);
1366     $enc = '';
1367     for ($i = 0; $i < $bytes; $i++) {
1368         $enc .= sprintf("%02x", (ord($src[$i])));
1369     }
1370     return $enc;
1371 }
1372
1373 function common_mtrand($bytes)
1374 {
1375     $enc = '';
1376     for ($i = 0; $i < $bytes; $i++) {
1377         $enc .= sprintf("%02x", mt_rand(0, 255));
1378     }
1379     return $enc;
1380 }
1381
1382 /**
1383  * Record the given URL as the return destination for a future
1384  * form submission, to be read by common_get_returnto().
1385  *
1386  * @param string $url
1387  *
1388  * @fixme as a session-global setting, this can allow multiple forms
1389  * to conflict and overwrite each others' returnto destinations if
1390  * the user has multiple tabs or windows open.
1391  *
1392  * Should refactor to index with a token or otherwise only pass the
1393  * data along its intended path.
1394  */
1395 function common_set_returnto($url)
1396 {
1397     common_ensure_session();
1398     $_SESSION['returnto'] = $url;
1399 }
1400
1401 /**
1402  * Fetch a return-destination URL previously recorded by
1403  * common_set_returnto().
1404  *
1405  * @return mixed URL string or null
1406  *
1407  * @fixme as a session-global setting, this can allow multiple forms
1408  * to conflict and overwrite each others' returnto destinations if
1409  * the user has multiple tabs or windows open.
1410  *
1411  * Should refactor to index with a token or otherwise only pass the
1412  * data along its intended path.
1413  */
1414 function common_get_returnto()
1415 {
1416     common_ensure_session();
1417     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1418 }
1419
1420 function common_timestamp()
1421 {
1422     return date('YmdHis');
1423 }
1424
1425 function common_ensure_syslog()
1426 {
1427     static $initialized = false;
1428     if (!$initialized) {
1429         openlog(common_config('syslog', 'appname'), 0,
1430             common_config('syslog', 'facility'));
1431         $initialized = true;
1432     }
1433 }
1434
1435 function common_log_line($priority, $msg)
1436 {
1437     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1438                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1439     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1440 }
1441
1442 function common_request_id()
1443 {
1444     $pid = getmypid();
1445     $server = common_config('site', 'server');
1446     if (php_sapi_name() == 'cli') {
1447         $script = basename($_SERVER['PHP_SELF']);
1448         return "$server:$script:$pid";
1449     } else {
1450         static $req_id = null;
1451         if (!isset($req_id)) {
1452             $req_id = substr(md5(mt_rand()), 0, 8);
1453         }
1454         if (isset($_SERVER['REQUEST_URI'])) {
1455             $url = $_SERVER['REQUEST_URI'];
1456         }
1457         $method = $_SERVER['REQUEST_METHOD'];
1458         return "$server:$pid.$req_id $method $url";
1459     }
1460 }
1461
1462 function common_log($priority, $msg, $filename=null)
1463 {
1464     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1465         $msg = '[' . common_request_id() . '] ' . $msg;
1466         $logfile = common_config('site', 'logfile');
1467         if ($logfile) {
1468             $log = fopen($logfile, "a");
1469             if ($log) {
1470                 $output = common_log_line($priority, $msg);
1471                 fwrite($log, $output);
1472                 fclose($log);
1473             }
1474         } else {
1475             common_ensure_syslog();
1476             syslog($priority, $msg);
1477         }
1478         Event::handle('EndLog', array($priority, $msg, $filename));
1479     }
1480 }
1481
1482 function common_debug($msg, $filename=null)
1483 {
1484     if ($filename) {
1485         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1486     } else {
1487         common_log(LOG_DEBUG, $msg);
1488     }
1489 }
1490
1491 function common_log_db_error(&$object, $verb, $filename=null)
1492 {
1493     $objstr = common_log_objstring($object);
1494     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1495     if (is_object($last_error)) {
1496         $msg = $last_error->message;
1497     } else {
1498         $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1499     }
1500     common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1501 }
1502
1503 function common_log_objstring(&$object)
1504 {
1505     if (is_null($object)) {
1506         return "null";
1507     }
1508     if (!($object instanceof DB_DataObject)) {
1509         return "(unknown)";
1510     }
1511     $arr = $object->toArray();
1512     $fields = array();
1513     foreach ($arr as $k => $v) {
1514         if (is_object($v)) {
1515             $fields[] = "$k='".get_class($v)."'";
1516         } else {
1517             $fields[] = "$k='$v'";
1518         }
1519     }
1520     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1521     return $objstring;
1522 }
1523
1524 function common_valid_http_url($url)
1525 {
1526     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1527 }
1528
1529 function common_valid_tag($tag)
1530 {
1531     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1532         return (Validate::email($matches[1]) ||
1533                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1534     }
1535     return false;
1536 }
1537
1538 /**
1539  * Determine if given domain or address literal is valid
1540  * eg for use in JIDs and URLs. Does not check if the domain
1541  * exists!
1542  *
1543  * @param string $domain
1544  * @return boolean valid or not
1545  */
1546 function common_valid_domain($domain)
1547 {
1548     $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1549     $ipv4 = "(?:$octet(?:\.$octet){3})";
1550     if (preg_match("/^$ipv4$/u", $domain)) return true;
1551
1552     $group = "(?:[0-9a-f]{1,4})";
1553     $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1554
1555     if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1556         $before = explode(":", $matches[1]);
1557         $zeroes = $matches[2];
1558         $after = explode(":", $matches[3]);
1559         if ($zeroes) {
1560             $min = 0;
1561             $max = 7;
1562         } else {
1563             $min = 1;
1564             $max = 8;
1565         }
1566         $explicit = count($before) + count($after);
1567         if ($explicit < $min || $explicit > $max) {
1568             return false;
1569         }
1570         return true;
1571     }
1572
1573     try {
1574         require_once "Net/IDNA.php";
1575         $idn = Net_IDNA::getInstance();
1576         $domain = $idn->encode($domain);
1577     } catch (Exception $e) {
1578         return false;
1579     }
1580
1581     $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1582     $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1583
1584     return preg_match("/^$fqdn$/ui", $domain);
1585 }
1586
1587 /* Following functions are copied from MediaWiki GlobalFunctions.php
1588  * and written by Evan Prodromou. */
1589
1590 function common_accept_to_prefs($accept, $def = '*/*')
1591 {
1592     // No arg means accept anything (per HTTP spec)
1593     if(!$accept) {
1594         return array($def => 1);
1595     }
1596
1597     $prefs = array();
1598
1599     $parts = explode(',', $accept);
1600
1601     foreach($parts as $part) {
1602         // FIXME: doesn't deal with params like 'text/html; level=1'
1603         @list($value, $qpart) = explode(';', trim($part));
1604         $match = array();
1605         if(!isset($qpart)) {
1606             $prefs[$value] = 1;
1607         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1608             $prefs[$value] = $match[1];
1609         }
1610     }
1611
1612     return $prefs;
1613 }
1614
1615 function common_mime_type_match($type, $avail)
1616 {
1617     if(array_key_exists($type, $avail)) {
1618         return $type;
1619     } else {
1620         $parts = explode('/', $type);
1621         if(array_key_exists($parts[0] . '/*', $avail)) {
1622             return $parts[0] . '/*';
1623         } elseif(array_key_exists('*/*', $avail)) {
1624             return '*/*';
1625         } else {
1626             return null;
1627         }
1628     }
1629 }
1630
1631 function common_negotiate_type($cprefs, $sprefs)
1632 {
1633     $combine = array();
1634
1635     foreach(array_keys($sprefs) as $type) {
1636         $parts = explode('/', $type);
1637         if($parts[1] != '*') {
1638             $ckey = common_mime_type_match($type, $cprefs);
1639             if($ckey) {
1640                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1641             }
1642         }
1643     }
1644
1645     foreach(array_keys($cprefs) as $type) {
1646         $parts = explode('/', $type);
1647         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1648             $skey = common_mime_type_match($type, $sprefs);
1649             if($skey) {
1650                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1651             }
1652         }
1653     }
1654
1655     $bestq = 0;
1656     $besttype = 'text/html';
1657
1658     foreach(array_keys($combine) as $type) {
1659         if($combine[$type] > $bestq) {
1660             $besttype = $type;
1661             $bestq = $combine[$type];
1662         }
1663     }
1664
1665     if ('text/html' === $besttype) {
1666         return "text/html; charset=utf-8";
1667     }
1668     return $besttype;
1669 }
1670
1671 function common_config($main, $sub)
1672 {
1673     global $config;
1674     return (array_key_exists($main, $config) &&
1675             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1676 }
1677
1678 function common_copy_args($from)
1679 {
1680     $to = array();
1681     $strip = get_magic_quotes_gpc();
1682     foreach ($from as $k => $v) {
1683         if($strip) {
1684             if(is_array($v)) {
1685                 $to[$k] = common_copy_args($v);
1686             } else {
1687                 $to[$k] = stripslashes($v);
1688             }
1689         } else {
1690             $to[$k] = $v;
1691         }
1692     }
1693     return $to;
1694 }
1695
1696 /**
1697  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1698  * This is used before handing a request off to OAuthRequest::from_request.
1699  * @fixme Doesn't consider vars other than _POST and _GET?
1700  * @fixme Can't be undone and could corrupt data if run twice.
1701  */
1702 function common_remove_magic_from_request()
1703 {
1704     if(get_magic_quotes_gpc()) {
1705         $_POST=array_map('stripslashes',$_POST);
1706         $_GET=array_map('stripslashes',$_GET);
1707     }
1708 }
1709
1710 function common_user_uri(&$user)
1711 {
1712     return common_local_url('userbyid', array('id' => $user->id),
1713                             null, null, false);
1714 }
1715
1716 function common_notice_uri(&$notice)
1717 {
1718     return common_local_url('shownotice',
1719                             array('notice' => $notice->id),
1720                             null, null, false);
1721 }
1722
1723 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1724
1725 function common_confirmation_code($bits)
1726 {
1727     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1728     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1729     $chars = ceil($bits/5);
1730     $code = '';
1731     for ($i = 0; $i < $chars; $i++) {
1732         // XXX: convert to string and back
1733         $num = hexdec(common_good_rand(1));
1734         // XXX: randomness is too precious to throw away almost
1735         // 40% of the bits we get!
1736         $code .= $codechars[$num%32];
1737     }
1738     return $code;
1739 }
1740
1741 // convert markup to HTML
1742
1743 function common_markup_to_html($c)
1744 {
1745     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1746     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1747     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1748     return Markdown($c);
1749 }
1750
1751 function common_profile_uri($profile)
1752 {
1753     if (!$profile) {
1754         return null;
1755     }
1756     $user = User::staticGet($profile->id);
1757     if ($user) {
1758         return $user->uri;
1759     }
1760
1761     $remote = Remote_profile::staticGet($profile->id);
1762     if ($remote) {
1763         return $remote->uri;
1764     }
1765     // XXX: this is a very bad profile!
1766     return null;
1767 }
1768
1769 function common_canonical_sms($sms)
1770 {
1771     // strip non-digits
1772     preg_replace('/\D/', '', $sms);
1773     return $sms;
1774 }
1775
1776 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1777 {
1778     switch ($errno) {
1779
1780      case E_ERROR:
1781      case E_COMPILE_ERROR:
1782      case E_CORE_ERROR:
1783      case E_USER_ERROR:
1784      case E_PARSE:
1785      case E_RECOVERABLE_ERROR:
1786         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1787         die();
1788         break;
1789
1790      case E_WARNING:
1791      case E_COMPILE_WARNING:
1792      case E_CORE_WARNING:
1793      case E_USER_WARNING:
1794         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1795         break;
1796
1797      case E_NOTICE:
1798      case E_USER_NOTICE:
1799         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1800         break;
1801
1802      case E_STRICT:
1803      case E_DEPRECATED:
1804      case E_USER_DEPRECATED:
1805         // XXX: config variable to log this stuff, too
1806         break;
1807
1808      default:
1809         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1810         die();
1811         break;
1812     }
1813
1814     // FIXME: show error page if we're on the Web
1815     /* Don't execute PHP internal error handler */
1816     return true;
1817 }
1818
1819 function common_session_token()
1820 {
1821     common_ensure_session();
1822     if (!array_key_exists('token', $_SESSION)) {
1823         $_SESSION['token'] = common_good_rand(64);
1824     }
1825     return $_SESSION['token'];
1826 }
1827
1828 function common_license_terms($uri)
1829 {
1830     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1831         return explode('-',$matches[1]);
1832     }
1833     return array($uri);
1834 }
1835
1836 function common_compatible_license($from, $to)
1837 {
1838     $from_terms = common_license_terms($from);
1839     // public domain and cc-by are compatible with everything
1840     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1841         return true;
1842     }
1843     $to_terms = common_license_terms($to);
1844     // sa is compatible across versions. IANAL
1845     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1846         return count(array_diff($from_terms, $to_terms)) == 0;
1847     }
1848     // XXX: better compatibility check needed here!
1849     // Should at least normalise URIs
1850     return ($from == $to);
1851 }
1852
1853 /**
1854  * returns a quoted table name, if required according to config
1855  */
1856 function common_database_tablename($tablename)
1857 {
1858   if(common_config('db','quote_identifiers')) {
1859       $tablename = '"'. $tablename .'"';
1860   }
1861   //table prefixes could be added here later
1862   return $tablename;
1863 }
1864
1865 /**
1866  * Shorten a URL with the current user's configured shortening service,
1867  * or ur1.ca if configured, or not at all if no shortening is set up.
1868  *
1869  * @param string  $long_url original URL
1870  * @param boolean $force    Force shortening (used when notice is too long)
1871  *
1872  * @return string may return the original URL if shortening failed
1873  *
1874  * @fixme provide a way to specify a particular shortener
1875  * @fixme provide a way to specify to use a given user's shortening preferences
1876  */
1877
1878 function common_shorten_url($long_url, $force = false)
1879 {
1880     common_debug("Shortening URL '$long_url' (force = $force)");
1881
1882     $long_url = trim($long_url);
1883
1884     $user = common_current_user();
1885
1886     $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
1887     common_debug("maxUrlLength = $maxUrlLength");
1888
1889     // $force forces shortening even if it's not strictly needed
1890
1891     if (mb_strlen($long_url) < $maxUrlLength && !$force) {
1892         common_debug("Skipped shortening URL.");
1893         return $long_url;
1894     }
1895
1896     $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
1897
1898     common_debug("Shortener name = '$shortenerName'");
1899
1900     if (Event::handle('StartShortenUrl', array($long_url, $shortenerName, &$shortenedUrl))) {
1901         //URL wasn't shortened, so return the long url
1902         return $long_url;
1903     } else {
1904         //URL was shortened, so return the result
1905         return trim($shortenedUrl);
1906     }
1907 }
1908
1909 /**
1910  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1911  *               null if not a web request
1912  *
1913  * @fixme X-Forwarded-For can be chained by multiple proxies;
1914           we should parse the list and provide a cleaner array
1915  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1916  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1917  *        use function to get exact request headers from Apache if possible.
1918  */
1919 function common_client_ip()
1920 {
1921     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1922         return null;
1923     }
1924
1925     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1926         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1927             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1928         } else {
1929             $proxy = $_SERVER['REMOTE_ADDR'];
1930         }
1931         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1932     } else {
1933         $proxy = null;
1934         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1935             $ip = $_SERVER['HTTP_CLIENT_IP'];
1936         } else {
1937             $ip = $_SERVER['REMOTE_ADDR'];
1938         }
1939     }
1940
1941     return array($proxy, $ip);
1942 }
1943
1944 function common_url_to_nickname($url)
1945 {
1946     static $bad = array('query', 'user', 'password', 'port', 'fragment');
1947
1948     $parts = parse_url($url);
1949
1950     # If any of these parts exist, this won't work
1951
1952     foreach ($bad as $badpart) {
1953         if (array_key_exists($badpart, $parts)) {
1954             return null;
1955         }
1956     }
1957
1958     # We just have host and/or path
1959
1960     # If it's just a host...
1961     if (array_key_exists('host', $parts) &&
1962         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1963     {
1964         $hostparts = explode('.', $parts['host']);
1965
1966         # Try to catch common idiom of nickname.service.tld
1967
1968         if ((count($hostparts) > 2) &&
1969             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1970             (strcmp($hostparts[0], 'www') != 0))
1971         {
1972             return common_nicknamize($hostparts[0]);
1973         } else {
1974             # Do the whole hostname
1975             return common_nicknamize($parts['host']);
1976         }
1977     } else {
1978         if (array_key_exists('path', $parts)) {
1979             # Strip starting, ending slashes
1980             $path = preg_replace('@/$@', '', $parts['path']);
1981             $path = preg_replace('@^/@', '', $path);
1982             $path = basename($path);
1983
1984             // Hack for MediaWiki user pages, in the form:
1985             // http://example.com/wiki/User:Myname
1986             // ('User' may be localized.)
1987             if (strpos($path, ':')) {
1988                 $parts = array_filter(explode(':', $path));
1989                 $path = $parts[count($parts) - 1];
1990             }
1991
1992             if ($path) {
1993                 return common_nicknamize($path);
1994             }
1995         }
1996     }
1997
1998     return null;
1999 }
2000
2001 function common_nicknamize($str)
2002 {
2003     $str = preg_replace('/\W/', '', $str);
2004     return strtolower($str);
2005 }