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