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