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