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