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