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