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