]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.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)
859 {
860     $maxLength = Notice::maxContent();
861     if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
862     return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
863 }
864
865 function common_xml_safe_str($str)
866 {
867     // Replace common eol and extra whitespace input chars
868     $unWelcome = array(
869         "\t",  // tab
870         "\n",  // newline
871         "\r",  // cr
872         "\0",  // null byte eos
873         "\x0B" // vertical tab
874     );
875
876     $replacement = array(
877         ' ', // single space
878         ' ',
879         '',  // nothing
880         '',
881         ' '
882     );
883
884     $str = str_replace($unWelcome, $replacement, $str);
885
886     // Neutralize any additional control codes and UTF-16 surrogates
887     // (Twitter uses '*')
888     return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
889 }
890
891 function common_tag_link($tag)
892 {
893     $canonical = common_canonical_tag($tag);
894     if (common_config('singleuser', 'enabled')) {
895         // regular TagAction isn't set up in 1user mode
896         $url = common_local_url('showstream',
897                                 array('nickname' => common_config('singleuser', 'nickname'),
898                                       'tag' => $canonical));
899     } else {
900         $url = common_local_url('tag', array('tag' => $canonical));
901     }
902     $xs = new XMLStringer();
903     $xs->elementStart('span', 'tag');
904     $xs->element('a', array('href' => $url,
905                             'rel' => 'tag'),
906                  $tag);
907     $xs->elementEnd('span');
908     return $xs->getString();
909 }
910
911 function common_canonical_tag($tag)
912 {
913   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
914   return str_replace(array('-', '_', '.'), '', $tag);
915 }
916
917 function common_valid_profile_tag($str)
918 {
919     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
920 }
921
922 function common_group_link($sender_id, $nickname)
923 {
924     $sender = Profile::staticGet($sender_id);
925     $group = User_group::getForNickname($nickname, $sender);
926     if ($sender && $group && $sender->isMember($group)) {
927         $attrs = array('href' => $group->permalink(),
928                        'class' => 'url');
929         if (!empty($group->fullname)) {
930             $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
931         }
932         $xs = new XMLStringer();
933         $xs->elementStart('span', 'vcard');
934         $xs->elementStart('a', $attrs);
935         $xs->element('span', 'fn nickname', $nickname);
936         $xs->elementEnd('a');
937         $xs->elementEnd('span');
938         return $xs->getString();
939     } else {
940         return $nickname;
941     }
942 }
943
944 function common_relative_profile($sender, $nickname, $dt=null)
945 {
946     // Try to find profiles this profile is subscribed to that have this nickname
947     $recipient = new Profile();
948     // XXX: use a join instead of a subquery
949     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
950     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
951     if ($recipient->find(true)) {
952         // XXX: should probably differentiate between profiles with
953         // the same name by date of most recent update
954         return $recipient;
955     }
956     // Try to find profiles that listen to this profile and that have this nickname
957     $recipient = new Profile();
958     // XXX: use a join instead of a subquery
959     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
960     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
961     if ($recipient->find(true)) {
962         // XXX: should probably differentiate between profiles with
963         // the same name by date of most recent update
964         return $recipient;
965     }
966     // If this is a local user, try to find a local user with that nickname.
967     $sender = User::staticGet($sender->id);
968     if ($sender) {
969         $recipient_user = User::staticGet('nickname', $nickname);
970         if ($recipient_user) {
971             return $recipient_user->getProfile();
972         }
973     }
974     // Otherwise, no links. @messages from local users to remote users,
975     // or from remote users to other remote users, are just
976     // outside our ability to make intelligent guesses about
977     return null;
978 }
979
980 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
981 {
982     $r = Router::get();
983     $path = $r->build($action, $args, $params, $fragment);
984
985     $ssl = common_is_sensitive($action);
986
987     if (common_config('site','fancy')) {
988         $url = common_path(mb_substr($path, 1), $ssl, $addSession);
989     } else {
990         if (mb_strpos($path, '/index.php') === 0) {
991             $url = common_path(mb_substr($path, 1), $ssl, $addSession);
992         } else {
993             $url = common_path('index.php'.$path, $ssl, $addSession);
994         }
995     }
996     return $url;
997 }
998
999 function common_is_sensitive($action)
1000 {
1001     static $sensitive = array('login', 'register', 'passwordsettings',
1002                               'twittersettings', 'api');
1003     $ssl = null;
1004
1005     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1006         $ssl = in_array($action, $sensitive);
1007     }
1008
1009     return $ssl;
1010 }
1011
1012 function common_path($relative, $ssl=false, $addSession=true)
1013 {
1014     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1015
1016     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1017         || common_config('site', 'ssl') === 'always') {
1018         $proto = 'https';
1019         if (is_string(common_config('site', 'sslserver')) &&
1020             mb_strlen(common_config('site', 'sslserver')) > 0) {
1021             $serverpart = common_config('site', 'sslserver');
1022         } else if (common_config('site', 'server')) {
1023             $serverpart = common_config('site', 'server');
1024         } else {
1025             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1026         }
1027     } else {
1028         $proto = 'http';
1029         if (common_config('site', 'server')) {
1030             $serverpart = common_config('site', 'server');
1031         } else {
1032             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1033         }
1034     }
1035
1036     if ($addSession) {
1037         $relative = common_inject_session($relative, $serverpart);
1038     }
1039
1040     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1041 }
1042
1043 function common_inject_session($url, $serverpart = null)
1044 {
1045     if (common_have_session()) {
1046
1047         if (empty($serverpart)) {
1048             $serverpart = parse_url($url, PHP_URL_HOST);
1049         }
1050
1051         $currentServer = $_SERVER['HTTP_HOST'];
1052
1053         // Are we pointing to another server (like an SSL server?)
1054
1055         if (!empty($currentServer) &&
1056             0 != strcasecmp($currentServer, $serverpart)) {
1057             // Pass the session ID as a GET parameter
1058             $sesspart = session_name() . '=' . session_id();
1059             $i = strpos($url, '?');
1060             if ($i === false) { // no GET params, just append
1061                 $url .= '?' . $sesspart;
1062             } else {
1063                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1064             }
1065         }
1066     }
1067
1068     return $url;
1069 }
1070
1071 function common_date_string($dt)
1072 {
1073     // XXX: do some sexy date formatting
1074     // return date(DATE_RFC822, $dt);
1075     $t = strtotime($dt);
1076     $now = time();
1077     $diff = $now - $t;
1078
1079     if ($now < $t) { // that shouldn't happen!
1080         return common_exact_date($dt);
1081     } else if ($diff < 60) {
1082         // TRANS: Used in notices to indicate when the notice was made compared to now.
1083         return _('a few seconds ago');
1084     } else if ($diff < 92) {
1085         // TRANS: Used in notices to indicate when the notice was made compared to now.
1086         return _('about a minute ago');
1087     } else if ($diff < 3300) {
1088         // XXX: should support plural.
1089         // TRANS: Used in notices to indicate when the notice was made compared to now.
1090         return sprintf(_('about %d minutes ago'), round($diff/60));
1091     } else if ($diff < 5400) {
1092         // TRANS: Used in notices to indicate when the notice was made compared to now.
1093         return _('about an hour ago');
1094     } else if ($diff < 22 * 3600) {
1095         // XXX: should support plural.
1096         // TRANS: Used in notices to indicate when the notice was made compared to now.
1097         return sprintf(_('about %d hours ago'), round($diff/3600));
1098     } else if ($diff < 37 * 3600) {
1099         // TRANS: Used in notices to indicate when the notice was made compared to now.
1100         return _('about a day ago');
1101     } else if ($diff < 24 * 24 * 3600) {
1102         // XXX: should support plural.
1103         // TRANS: Used in notices to indicate when the notice was made compared to now.
1104         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1105     } else if ($diff < 46 * 24 * 3600) {
1106         // TRANS: Used in notices to indicate when the notice was made compared to now.
1107         return _('about a month ago');
1108     } else if ($diff < 330 * 24 * 3600) {
1109         // XXX: should support plural.
1110         // TRANS: Used in notices to indicate when the notice was made compared to now.
1111         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1112     } else if ($diff < 480 * 24 * 3600) {
1113         // TRANS: Used in notices to indicate when the notice was made compared to now.
1114         return _('about a year ago');
1115     } else {
1116         return common_exact_date($dt);
1117     }
1118 }
1119
1120 function common_exact_date($dt)
1121 {
1122     static $_utc;
1123     static $_siteTz;
1124
1125     if (!$_utc) {
1126         $_utc = new DateTimeZone('UTC');
1127         $_siteTz = new DateTimeZone(common_timezone());
1128     }
1129
1130     $dateStr = date('d F Y H:i:s', strtotime($dt));
1131     $d = new DateTime($dateStr, $_utc);
1132     $d->setTimezone($_siteTz);
1133     return $d->format(DATE_RFC850);
1134 }
1135
1136 function common_date_w3dtf($dt)
1137 {
1138     $dateStr = date('d F Y H:i:s', strtotime($dt));
1139     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1140     $d->setTimezone(new DateTimeZone(common_timezone()));
1141     return $d->format(DATE_W3C);
1142 }
1143
1144 function common_date_rfc2822($dt)
1145 {
1146     $dateStr = date('d F Y H:i:s', strtotime($dt));
1147     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1148     $d->setTimezone(new DateTimeZone(common_timezone()));
1149     return $d->format('r');
1150 }
1151
1152 function common_date_iso8601($dt)
1153 {
1154     $dateStr = date('d F Y H:i:s', strtotime($dt));
1155     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1156     $d->setTimezone(new DateTimeZone(common_timezone()));
1157     return $d->format('c');
1158 }
1159
1160 function common_sql_now()
1161 {
1162     return common_sql_date(time());
1163 }
1164
1165 function common_sql_date($datetime)
1166 {
1167     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1168 }
1169
1170 /**
1171  * Return an SQL fragment to calculate an age-based weight from a given
1172  * timestamp or datetime column.
1173  *
1174  * @param string $column name of field we're comparing against current time
1175  * @param integer $dropoff divisor for age in seconds before exponentiation
1176  * @return string SQL fragment
1177  */
1178 function common_sql_weight($column, $dropoff)
1179 {
1180     if (common_config('db', 'type') == 'pgsql') {
1181         // PostgreSQL doesn't support timestampdiff function.
1182         // @fixme will this use the right time zone?
1183         // @fixme does this handle cross-year subtraction correctly?
1184         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1185     } else {
1186         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1187     }
1188 }
1189
1190 function common_redirect($url, $code=307)
1191 {
1192     static $status = array(301 => "Moved Permanently",
1193                            302 => "Found",
1194                            303 => "See Other",
1195                            307 => "Temporary Redirect");
1196
1197     header('HTTP/1.1 '.$code.' '.$status[$code]);
1198     header("Location: $url");
1199
1200     $xo = new XMLOutputter();
1201     $xo->startXML('a',
1202                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1203                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1204     $xo->element('a', array('href' => $url), $url);
1205     $xo->endXML();
1206     exit;
1207 }
1208
1209 function common_broadcast_notice($notice, $remote=false)
1210 {
1211     // DO NOTHING!
1212 }
1213
1214 // Stick the notice on the queue
1215
1216 function common_enqueue_notice($notice)
1217 {
1218     static $localTransports = array('omb',
1219                                     'ping');
1220
1221     $transports = array();
1222     if (common_config('sms', 'enabled')) {
1223         $transports[] = 'sms';
1224     }
1225     if (Event::hasHandler('HandleQueuedNotice')) {
1226         $transports[] = 'plugin';
1227     }
1228
1229     $xmpp = common_config('xmpp', 'enabled');
1230
1231     if ($xmpp) {
1232         $transports[] = 'jabber';
1233     }
1234
1235     // @fixme move these checks into QueueManager and/or individual handlers
1236     if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1237         $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1238         $transports = array_merge($transports, $localTransports);
1239         if ($xmpp) {
1240             $transports[] = 'public';
1241         }
1242     }
1243
1244     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1245
1246         $qm = QueueManager::get();
1247
1248         foreach ($transports as $transport)
1249         {
1250             $qm->enqueue($notice, $transport);
1251         }
1252
1253         Event::handle('EndEnqueueNotice', array($notice, $transports));
1254     }
1255
1256     return true;
1257 }
1258
1259 /**
1260  * Broadcast profile updates to OMB and other remote subscribers.
1261  *
1262  * Since this may be slow with a lot of subscribers or bad remote sites,
1263  * this is run through the background queues if possible.
1264  */
1265 function common_broadcast_profile(Profile $profile)
1266 {
1267     $qm = QueueManager::get();
1268     $qm->enqueue($profile, "profile");
1269     return true;
1270 }
1271
1272 function common_profile_url($nickname)
1273 {
1274     return common_local_url('showstream', array('nickname' => $nickname),
1275                             null, null, false);
1276 }
1277
1278 // Should make up a reasonable root URL
1279
1280 function common_root_url($ssl=false)
1281 {
1282     $url = common_path('', $ssl, false);
1283     $i = strpos($url, '?');
1284     if ($i !== false) {
1285         $url = substr($url, 0, $i);
1286     }
1287     return $url;
1288 }
1289
1290 // returns $bytes bytes of random data as a hexadecimal string
1291 // "good" here is a goal and not a guarantee
1292
1293 function common_good_rand($bytes)
1294 {
1295     // XXX: use random.org...?
1296     if (@file_exists('/dev/urandom')) {
1297         return common_urandom($bytes);
1298     } else { // FIXME: this is probably not good enough
1299         return common_mtrand($bytes);
1300     }
1301 }
1302
1303 function common_urandom($bytes)
1304 {
1305     $h = fopen('/dev/urandom', 'rb');
1306     // should not block
1307     $src = fread($h, $bytes);
1308     fclose($h);
1309     $enc = '';
1310     for ($i = 0; $i < $bytes; $i++) {
1311         $enc .= sprintf("%02x", (ord($src[$i])));
1312     }
1313     return $enc;
1314 }
1315
1316 function common_mtrand($bytes)
1317 {
1318     $enc = '';
1319     for ($i = 0; $i < $bytes; $i++) {
1320         $enc .= sprintf("%02x", mt_rand(0, 255));
1321     }
1322     return $enc;
1323 }
1324
1325 /**
1326  * Record the given URL as the return destination for a future
1327  * form submission, to be read by common_get_returnto().
1328  * 
1329  * @param string $url
1330  * 
1331  * @fixme as a session-global setting, this can allow multiple forms
1332  * to conflict and overwrite each others' returnto destinations if
1333  * the user has multiple tabs or windows open.
1334  * 
1335  * Should refactor to index with a token or otherwise only pass the
1336  * data along its intended path.
1337  */
1338 function common_set_returnto($url)
1339 {
1340     common_ensure_session();
1341     $_SESSION['returnto'] = $url;
1342 }
1343
1344 /**
1345  * Fetch a return-destination URL previously recorded by
1346  * common_set_returnto().
1347  * 
1348  * @return mixed URL string or null
1349  * 
1350  * @fixme as a session-global setting, this can allow multiple forms
1351  * to conflict and overwrite each others' returnto destinations if
1352  * the user has multiple tabs or windows open.
1353  * 
1354  * Should refactor to index with a token or otherwise only pass the
1355  * data along its intended path.
1356  */
1357 function common_get_returnto()
1358 {
1359     common_ensure_session();
1360     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1361 }
1362
1363 function common_timestamp()
1364 {
1365     return date('YmdHis');
1366 }
1367
1368 function common_ensure_syslog()
1369 {
1370     static $initialized = false;
1371     if (!$initialized) {
1372         openlog(common_config('syslog', 'appname'), 0,
1373             common_config('syslog', 'facility'));
1374         $initialized = true;
1375     }
1376 }
1377
1378 function common_log_line($priority, $msg)
1379 {
1380     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1381                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1382     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1383 }
1384
1385 function common_request_id()
1386 {
1387     $pid = getmypid();
1388     $server = common_config('site', 'server');
1389     if (php_sapi_name() == 'cli') {
1390         $script = basename($_SERVER['PHP_SELF']);
1391         return "$server:$script:$pid";
1392     } else {
1393         static $req_id = null;
1394         if (!isset($req_id)) {
1395             $req_id = substr(md5(mt_rand()), 0, 8);
1396         }
1397         if (isset($_SERVER['REQUEST_URI'])) {
1398             $url = $_SERVER['REQUEST_URI'];
1399         }
1400         $method = $_SERVER['REQUEST_METHOD'];
1401         return "$server:$pid.$req_id $method $url";
1402     }
1403 }
1404
1405 function common_log($priority, $msg, $filename=null)
1406 {
1407     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1408         $msg = '[' . common_request_id() . '] ' . $msg;
1409         $logfile = common_config('site', 'logfile');
1410         if ($logfile) {
1411             $log = fopen($logfile, "a");
1412             if ($log) {
1413                 $output = common_log_line($priority, $msg);
1414                 fwrite($log, $output);
1415                 fclose($log);
1416             }
1417         } else {
1418             common_ensure_syslog();
1419             syslog($priority, $msg);
1420         }
1421         Event::handle('EndLog', array($priority, $msg, $filename));
1422     }
1423 }
1424
1425 function common_debug($msg, $filename=null)
1426 {
1427     if ($filename) {
1428         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1429     } else {
1430         common_log(LOG_DEBUG, $msg);
1431     }
1432 }
1433
1434 function common_log_db_error(&$object, $verb, $filename=null)
1435 {
1436     $objstr = common_log_objstring($object);
1437     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1438     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1439 }
1440
1441 function common_log_objstring(&$object)
1442 {
1443     if (is_null($object)) {
1444         return "null";
1445     }
1446     if (!($object instanceof DB_DataObject)) {
1447         return "(unknown)";
1448     }
1449     $arr = $object->toArray();
1450     $fields = array();
1451     foreach ($arr as $k => $v) {
1452         if (is_object($v)) {
1453             $fields[] = "$k='".get_class($v)."'";
1454         } else {
1455             $fields[] = "$k='$v'";
1456         }
1457     }
1458     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1459     return $objstring;
1460 }
1461
1462 function common_valid_http_url($url)
1463 {
1464     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1465 }
1466
1467 function common_valid_tag($tag)
1468 {
1469     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1470         return (Validate::email($matches[1]) ||
1471                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1472     }
1473     return false;
1474 }
1475
1476 /**
1477  * Determine if given domain or address literal is valid
1478  * eg for use in JIDs and URLs. Does not check if the domain
1479  * exists!
1480  * 
1481  * @param string $domain
1482  * @return boolean valid or not
1483  */
1484 function common_valid_domain($domain)
1485 {
1486     $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1487     $ipv4 = "(?:$octet(?:\.$octet){3})";
1488     if (preg_match("/^$ipv4$/u", $domain)) return true;
1489
1490     $group = "(?:[0-9a-f]{1,4})";
1491     $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1492
1493     if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1494         $before = explode(":", $matches[1]);
1495         $zeroes = $matches[2];
1496         $after = explode(":", $matches[3]);
1497         if ($zeroes) {
1498             $min = 0;
1499             $max = 7;
1500         } else {
1501             $min = 1;
1502             $max = 8;
1503         }
1504         $explicit = count($before) + count($after);
1505         if ($explicit < $min || $explicit > $max) {
1506             return false;
1507         }
1508         return true;
1509     }
1510
1511     try {
1512         require_once "Net/IDNA.php";
1513         $idn = Net_IDNA::getInstance();
1514         $domain = $idn->encode($domain);
1515     } catch (Exception $e) {
1516         return false;
1517     }
1518
1519     $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1520     $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1521
1522     return preg_match("/^$fqdn$/ui", $domain);
1523 }
1524
1525 /* Following functions are copied from MediaWiki GlobalFunctions.php
1526  * and written by Evan Prodromou. */
1527
1528 function common_accept_to_prefs($accept, $def = '*/*')
1529 {
1530     // No arg means accept anything (per HTTP spec)
1531     if(!$accept) {
1532         return array($def => 1);
1533     }
1534
1535     $prefs = array();
1536
1537     $parts = explode(',', $accept);
1538
1539     foreach($parts as $part) {
1540         // FIXME: doesn't deal with params like 'text/html; level=1'
1541         @list($value, $qpart) = explode(';', trim($part));
1542         $match = array();
1543         if(!isset($qpart)) {
1544             $prefs[$value] = 1;
1545         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1546             $prefs[$value] = $match[1];
1547         }
1548     }
1549
1550     return $prefs;
1551 }
1552
1553 function common_mime_type_match($type, $avail)
1554 {
1555     if(array_key_exists($type, $avail)) {
1556         return $type;
1557     } else {
1558         $parts = explode('/', $type);
1559         if(array_key_exists($parts[0] . '/*', $avail)) {
1560             return $parts[0] . '/*';
1561         } elseif(array_key_exists('*/*', $avail)) {
1562             return '*/*';
1563         } else {
1564             return null;
1565         }
1566     }
1567 }
1568
1569 function common_negotiate_type($cprefs, $sprefs)
1570 {
1571     $combine = array();
1572
1573     foreach(array_keys($sprefs) as $type) {
1574         $parts = explode('/', $type);
1575         if($parts[1] != '*') {
1576             $ckey = common_mime_type_match($type, $cprefs);
1577             if($ckey) {
1578                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1579             }
1580         }
1581     }
1582
1583     foreach(array_keys($cprefs) as $type) {
1584         $parts = explode('/', $type);
1585         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1586             $skey = common_mime_type_match($type, $sprefs);
1587             if($skey) {
1588                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1589             }
1590         }
1591     }
1592
1593     $bestq = 0;
1594     $besttype = 'text/html';
1595
1596     foreach(array_keys($combine) as $type) {
1597         if($combine[$type] > $bestq) {
1598             $besttype = $type;
1599             $bestq = $combine[$type];
1600         }
1601     }
1602
1603     if ('text/html' === $besttype) {
1604         return "text/html; charset=utf-8";
1605     }
1606     return $besttype;
1607 }
1608
1609 function common_config($main, $sub)
1610 {
1611     global $config;
1612     return (array_key_exists($main, $config) &&
1613             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1614 }
1615
1616 function common_copy_args($from)
1617 {
1618     $to = array();
1619     $strip = get_magic_quotes_gpc();
1620     foreach ($from as $k => $v) {
1621         if($strip) {
1622             if(is_array($v)) {
1623                 $to[$k] = common_copy_args($v);
1624             } else {
1625                 $to[$k] = stripslashes($v);
1626             }
1627         } else {
1628             $to[$k] = $v;
1629         }
1630     }
1631     return $to;
1632 }
1633
1634 /**
1635  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1636  * This is used before handing a request off to OAuthRequest::from_request.
1637  * @fixme Doesn't consider vars other than _POST and _GET?
1638  * @fixme Can't be undone and could corrupt data if run twice.
1639  */
1640 function common_remove_magic_from_request()
1641 {
1642     if(get_magic_quotes_gpc()) {
1643         $_POST=array_map('stripslashes',$_POST);
1644         $_GET=array_map('stripslashes',$_GET);
1645     }
1646 }
1647
1648 function common_user_uri(&$user)
1649 {
1650     return common_local_url('userbyid', array('id' => $user->id),
1651                             null, null, false);
1652 }
1653
1654 function common_notice_uri(&$notice)
1655 {
1656     return common_local_url('shownotice',
1657                             array('notice' => $notice->id),
1658                             null, null, false);
1659 }
1660
1661 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1662
1663 function common_confirmation_code($bits)
1664 {
1665     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1666     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1667     $chars = ceil($bits/5);
1668     $code = '';
1669     for ($i = 0; $i < $chars; $i++) {
1670         // XXX: convert to string and back
1671         $num = hexdec(common_good_rand(1));
1672         // XXX: randomness is too precious to throw away almost
1673         // 40% of the bits we get!
1674         $code .= $codechars[$num%32];
1675     }
1676     return $code;
1677 }
1678
1679 // convert markup to HTML
1680
1681 function common_markup_to_html($c)
1682 {
1683     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1684     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1685     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1686     return Markdown($c);
1687 }
1688
1689 function common_profile_uri($profile)
1690 {
1691     if (!$profile) {
1692         return null;
1693     }
1694     $user = User::staticGet($profile->id);
1695     if ($user) {
1696         return $user->uri;
1697     }
1698
1699     $remote = Remote_profile::staticGet($profile->id);
1700     if ($remote) {
1701         return $remote->uri;
1702     }
1703     // XXX: this is a very bad profile!
1704     return null;
1705 }
1706
1707 function common_canonical_sms($sms)
1708 {
1709     // strip non-digits
1710     preg_replace('/\D/', '', $sms);
1711     return $sms;
1712 }
1713
1714 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1715 {
1716     switch ($errno) {
1717
1718      case E_ERROR:
1719      case E_COMPILE_ERROR:
1720      case E_CORE_ERROR:
1721      case E_USER_ERROR:
1722      case E_PARSE:
1723      case E_RECOVERABLE_ERROR:
1724         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1725         die();
1726         break;
1727
1728      case E_WARNING:
1729      case E_COMPILE_WARNING:
1730      case E_CORE_WARNING:
1731      case E_USER_WARNING:
1732         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1733         break;
1734
1735      case E_NOTICE:
1736      case E_USER_NOTICE:
1737         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1738         break;
1739
1740      case E_STRICT:
1741      case E_DEPRECATED:
1742      case E_USER_DEPRECATED:
1743         // XXX: config variable to log this stuff, too
1744         break;
1745
1746      default:
1747         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1748         die();
1749         break;
1750     }
1751
1752     // FIXME: show error page if we're on the Web
1753     /* Don't execute PHP internal error handler */
1754     return true;
1755 }
1756
1757 function common_session_token()
1758 {
1759     common_ensure_session();
1760     if (!array_key_exists('token', $_SESSION)) {
1761         $_SESSION['token'] = common_good_rand(64);
1762     }
1763     return $_SESSION['token'];
1764 }
1765
1766 function common_cache_key($extra)
1767 {
1768     return Cache::key($extra);
1769 }
1770
1771 function common_keyize($str)
1772 {
1773     return Cache::keyize($str);
1774 }
1775
1776 function common_memcache()
1777 {
1778     return Cache::instance();
1779 }
1780
1781 function common_license_terms($uri)
1782 {
1783     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1784         return explode('-',$matches[1]);
1785     }
1786     return array($uri);
1787 }
1788
1789 function common_compatible_license($from, $to)
1790 {
1791     $from_terms = common_license_terms($from);
1792     // public domain and cc-by are compatible with everything
1793     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1794         return true;
1795     }
1796     $to_terms = common_license_terms($to);
1797     // sa is compatible across versions. IANAL
1798     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1799         return count(array_diff($from_terms, $to_terms)) == 0;
1800     }
1801     // XXX: better compatibility check needed here!
1802     // Should at least normalise URIs
1803     return ($from == $to);
1804 }
1805
1806 /**
1807  * returns a quoted table name, if required according to config
1808  */
1809 function common_database_tablename($tablename)
1810 {
1811
1812   if(common_config('db','quote_identifiers')) {
1813       $tablename = '"'. $tablename .'"';
1814   }
1815   //table prefixes could be added here later
1816   return $tablename;
1817 }
1818
1819 /**
1820  * Shorten a URL with the current user's configured shortening service,
1821  * or ur1.ca if configured, or not at all if no shortening is set up.
1822  * Length is not considered.
1823  *
1824  * @param string $long_url
1825  * @return string may return the original URL if shortening failed
1826  *
1827  * @fixme provide a way to specify a particular shortener
1828  * @fixme provide a way to specify to use a given user's shortening preferences
1829  */
1830 function common_shorten_url($long_url)
1831 {
1832     $long_url = trim($long_url);
1833     $user = common_current_user();
1834     if (empty($user)) {
1835         // common current user does not find a user when called from the XMPP daemon
1836         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1837         $shortenerName = 'ur1.ca';
1838     } else {
1839         $shortenerName = $user->urlshorteningservice;
1840     }
1841
1842     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1843         //URL wasn't shortened, so return the long url
1844         return $long_url;
1845     }else{
1846         //URL was shortened, so return the result
1847         return trim($shortenedUrl);
1848     }
1849 }
1850
1851 /**
1852  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1853  *               null if not a web request
1854  *
1855  * @fixme X-Forwarded-For can be chained by multiple proxies;
1856           we should parse the list and provide a cleaner array
1857  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1858  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1859  *        use function to get exact request headers from Apache if possible.
1860  */
1861 function common_client_ip()
1862 {
1863     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1864         return null;
1865     }
1866
1867     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1868         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1869             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1870         } else {
1871             $proxy = $_SERVER['REMOTE_ADDR'];
1872         }
1873         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1874     } else {
1875         $proxy = null;
1876         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1877             $ip = $_SERVER['HTTP_CLIENT_IP'];
1878         } else {
1879             $ip = $_SERVER['REMOTE_ADDR'];
1880         }
1881     }
1882
1883     return array($proxy, $ip);
1884 }
1885
1886 function common_url_to_nickname($url)
1887 {
1888     static $bad = array('query', 'user', 'password', 'port', 'fragment');
1889
1890     $parts = parse_url($url);
1891
1892     # If any of these parts exist, this won't work
1893
1894     foreach ($bad as $badpart) {
1895         if (array_key_exists($badpart, $parts)) {
1896             return null;
1897         }
1898     }
1899
1900     # We just have host and/or path
1901
1902     # If it's just a host...
1903     if (array_key_exists('host', $parts) &&
1904         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1905     {
1906         $hostparts = explode('.', $parts['host']);
1907
1908         # Try to catch common idiom of nickname.service.tld
1909
1910         if ((count($hostparts) > 2) &&
1911             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1912             (strcmp($hostparts[0], 'www') != 0))
1913         {
1914             return common_nicknamize($hostparts[0]);
1915         } else {
1916             # Do the whole hostname
1917             return common_nicknamize($parts['host']);
1918         }
1919     } else {
1920         if (array_key_exists('path', $parts)) {
1921             # Strip starting, ending slashes
1922             $path = preg_replace('@/$@', '', $parts['path']);
1923             $path = preg_replace('@^/@', '', $path);
1924             $path = basename($path);
1925             if ($path) {
1926                 return common_nicknamize($path);
1927             }
1928         }
1929     }
1930
1931     return null;
1932 }
1933
1934 function common_nicknamize($str)
1935 {
1936     $str = preg_replace('/\W/', '', $str);
1937     return strtolower($str);
1938 }