]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
better calculation for end date in notice sitemaps
[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()) {
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         return _('a few seconds ago');
1083     } else if ($diff < 92) {
1084         return _('about a minute ago');
1085     } else if ($diff < 3300) {
1086         return sprintf(_('about %d minutes ago'), round($diff/60));
1087     } else if ($diff < 5400) {
1088         return _('about an hour ago');
1089     } else if ($diff < 22 * 3600) {
1090         return sprintf(_('about %d hours ago'), round($diff/3600));
1091     } else if ($diff < 37 * 3600) {
1092         return _('about a day ago');
1093     } else if ($diff < 24 * 24 * 3600) {
1094         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1095     } else if ($diff < 46 * 24 * 3600) {
1096         return _('about a month ago');
1097     } else if ($diff < 330 * 24 * 3600) {
1098         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1099     } else if ($diff < 480 * 24 * 3600) {
1100         return _('about a year ago');
1101     } else {
1102         return common_exact_date($dt);
1103     }
1104 }
1105
1106 function common_exact_date($dt)
1107 {
1108     static $_utc;
1109     static $_siteTz;
1110
1111     if (!$_utc) {
1112         $_utc = new DateTimeZone('UTC');
1113         $_siteTz = new DateTimeZone(common_timezone());
1114     }
1115
1116     $dateStr = date('d F Y H:i:s', strtotime($dt));
1117     $d = new DateTime($dateStr, $_utc);
1118     $d->setTimezone($_siteTz);
1119     return $d->format(DATE_RFC850);
1120 }
1121
1122 function common_date_w3dtf($dt)
1123 {
1124     $dateStr = date('d F Y H:i:s', strtotime($dt));
1125     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1126     $d->setTimezone(new DateTimeZone(common_timezone()));
1127     return $d->format(DATE_W3C);
1128 }
1129
1130 function common_date_rfc2822($dt)
1131 {
1132     $dateStr = date('d F Y H:i:s', strtotime($dt));
1133     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1134     $d->setTimezone(new DateTimeZone(common_timezone()));
1135     return $d->format('r');
1136 }
1137
1138 function common_date_iso8601($dt)
1139 {
1140     $dateStr = date('d F Y H:i:s', strtotime($dt));
1141     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1142     $d->setTimezone(new DateTimeZone(common_timezone()));
1143     return $d->format('c');
1144 }
1145
1146 function common_sql_now()
1147 {
1148     return common_sql_date(time());
1149 }
1150
1151 function common_sql_date($datetime)
1152 {
1153     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1154 }
1155
1156 /**
1157  * Return an SQL fragment to calculate an age-based weight from a given
1158  * timestamp or datetime column.
1159  *
1160  * @param string $column name of field we're comparing against current time
1161  * @param integer $dropoff divisor for age in seconds before exponentiation
1162  * @return string SQL fragment
1163  */
1164 function common_sql_weight($column, $dropoff)
1165 {
1166     if (common_config('db', 'type') == 'pgsql') {
1167         // PostgreSQL doesn't support timestampdiff function.
1168         // @fixme will this use the right time zone?
1169         // @fixme does this handle cross-year subtraction correctly?
1170         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1171     } else {
1172         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1173     }
1174 }
1175
1176 function common_redirect($url, $code=307)
1177 {
1178     static $status = array(301 => "Moved Permanently",
1179                            302 => "Found",
1180                            303 => "See Other",
1181                            307 => "Temporary Redirect");
1182
1183     header('HTTP/1.1 '.$code.' '.$status[$code]);
1184     header("Location: $url");
1185
1186     $xo = new XMLOutputter();
1187     $xo->startXML('a',
1188                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1189                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1190     $xo->element('a', array('href' => $url), $url);
1191     $xo->endXML();
1192     exit;
1193 }
1194
1195 function common_broadcast_notice($notice, $remote=false)
1196 {
1197     // DO NOTHING!
1198 }
1199
1200 // Stick the notice on the queue
1201
1202 function common_enqueue_notice($notice)
1203 {
1204     static $localTransports = array('omb',
1205                                     'ping');
1206
1207     $transports = array();
1208     if (common_config('sms', 'enabled')) {
1209         $transports[] = 'sms';
1210     }
1211     if (Event::hasHandler('HandleQueuedNotice')) {
1212         $transports[] = 'plugin';
1213     }
1214
1215     $xmpp = common_config('xmpp', 'enabled');
1216
1217     if ($xmpp) {
1218         $transports[] = 'jabber';
1219     }
1220
1221     // @fixme move these checks into QueueManager and/or individual handlers
1222     if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1223         $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1224         $transports = array_merge($transports, $localTransports);
1225         if ($xmpp) {
1226             $transports[] = 'public';
1227         }
1228     }
1229
1230     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1231
1232         $qm = QueueManager::get();
1233
1234         foreach ($transports as $transport)
1235         {
1236             $qm->enqueue($notice, $transport);
1237         }
1238
1239         Event::handle('EndEnqueueNotice', array($notice, $transports));
1240     }
1241
1242     return true;
1243 }
1244
1245 /**
1246  * Broadcast profile updates to OMB and other remote subscribers.
1247  *
1248  * Since this may be slow with a lot of subscribers or bad remote sites,
1249  * this is run through the background queues if possible.
1250  */
1251 function common_broadcast_profile(Profile $profile)
1252 {
1253     $qm = QueueManager::get();
1254     $qm->enqueue($profile, "profile");
1255     return true;
1256 }
1257
1258 function common_profile_url($nickname)
1259 {
1260     return common_local_url('showstream', array('nickname' => $nickname),
1261                             null, null, false);
1262 }
1263
1264 // Should make up a reasonable root URL
1265
1266 function common_root_url($ssl=false)
1267 {
1268     $url = common_path('', $ssl, false);
1269     $i = strpos($url, '?');
1270     if ($i !== false) {
1271         $url = substr($url, 0, $i);
1272     }
1273     return $url;
1274 }
1275
1276 // returns $bytes bytes of random data as a hexadecimal string
1277 // "good" here is a goal and not a guarantee
1278
1279 function common_good_rand($bytes)
1280 {
1281     // XXX: use random.org...?
1282     if (@file_exists('/dev/urandom')) {
1283         return common_urandom($bytes);
1284     } else { // FIXME: this is probably not good enough
1285         return common_mtrand($bytes);
1286     }
1287 }
1288
1289 function common_urandom($bytes)
1290 {
1291     $h = fopen('/dev/urandom', 'rb');
1292     // should not block
1293     $src = fread($h, $bytes);
1294     fclose($h);
1295     $enc = '';
1296     for ($i = 0; $i < $bytes; $i++) {
1297         $enc .= sprintf("%02x", (ord($src[$i])));
1298     }
1299     return $enc;
1300 }
1301
1302 function common_mtrand($bytes)
1303 {
1304     $enc = '';
1305     for ($i = 0; $i < $bytes; $i++) {
1306         $enc .= sprintf("%02x", mt_rand(0, 255));
1307     }
1308     return $enc;
1309 }
1310
1311 function common_set_returnto($url)
1312 {
1313     common_ensure_session();
1314     $_SESSION['returnto'] = $url;
1315 }
1316
1317 function common_get_returnto()
1318 {
1319     common_ensure_session();
1320     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1321 }
1322
1323 function common_timestamp()
1324 {
1325     return date('YmdHis');
1326 }
1327
1328 function common_ensure_syslog()
1329 {
1330     static $initialized = false;
1331     if (!$initialized) {
1332         openlog(common_config('syslog', 'appname'), 0,
1333             common_config('syslog', 'facility'));
1334         $initialized = true;
1335     }
1336 }
1337
1338 function common_log_line($priority, $msg)
1339 {
1340     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1341                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1342     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1343 }
1344
1345 function common_request_id()
1346 {
1347     $pid = getmypid();
1348     $server = common_config('site', 'server');
1349     if (php_sapi_name() == 'cli') {
1350         $script = basename($_SERVER['PHP_SELF']);
1351         return "$server:$script:$pid";
1352     } else {
1353         static $req_id = null;
1354         if (!isset($req_id)) {
1355             $req_id = substr(md5(mt_rand()), 0, 8);
1356         }
1357         if (isset($_SERVER['REQUEST_URI'])) {
1358             $url = $_SERVER['REQUEST_URI'];
1359         }
1360         $method = $_SERVER['REQUEST_METHOD'];
1361         return "$server:$pid.$req_id $method $url";
1362     }
1363 }
1364
1365 function common_log($priority, $msg, $filename=null)
1366 {
1367     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1368         $msg = '[' . common_request_id() . '] ' . $msg;
1369         $logfile = common_config('site', 'logfile');
1370         if ($logfile) {
1371             $log = fopen($logfile, "a");
1372             if ($log) {
1373                 $output = common_log_line($priority, $msg);
1374                 fwrite($log, $output);
1375                 fclose($log);
1376             }
1377         } else {
1378             common_ensure_syslog();
1379             syslog($priority, $msg);
1380         }
1381         Event::handle('EndLog', array($priority, $msg, $filename));
1382     }
1383 }
1384
1385 function common_debug($msg, $filename=null)
1386 {
1387     if ($filename) {
1388         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1389     } else {
1390         common_log(LOG_DEBUG, $msg);
1391     }
1392 }
1393
1394 function common_log_db_error(&$object, $verb, $filename=null)
1395 {
1396     $objstr = common_log_objstring($object);
1397     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1398     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1399 }
1400
1401 function common_log_objstring(&$object)
1402 {
1403     if (is_null($object)) {
1404         return "null";
1405     }
1406     if (!($object instanceof DB_DataObject)) {
1407         return "(unknown)";
1408     }
1409     $arr = $object->toArray();
1410     $fields = array();
1411     foreach ($arr as $k => $v) {
1412         if (is_object($v)) {
1413             $fields[] = "$k='".get_class($v)."'";
1414         } else {
1415             $fields[] = "$k='$v'";
1416         }
1417     }
1418     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1419     return $objstring;
1420 }
1421
1422 function common_valid_http_url($url)
1423 {
1424     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1425 }
1426
1427 function common_valid_tag($tag)
1428 {
1429     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1430         return (Validate::email($matches[1]) ||
1431                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1432     }
1433     return false;
1434 }
1435
1436 /* Following functions are copied from MediaWiki GlobalFunctions.php
1437  * and written by Evan Prodromou. */
1438
1439 function common_accept_to_prefs($accept, $def = '*/*')
1440 {
1441     // No arg means accept anything (per HTTP spec)
1442     if(!$accept) {
1443         return array($def => 1);
1444     }
1445
1446     $prefs = array();
1447
1448     $parts = explode(',', $accept);
1449
1450     foreach($parts as $part) {
1451         // FIXME: doesn't deal with params like 'text/html; level=1'
1452         @list($value, $qpart) = explode(';', trim($part));
1453         $match = array();
1454         if(!isset($qpart)) {
1455             $prefs[$value] = 1;
1456         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1457             $prefs[$value] = $match[1];
1458         }
1459     }
1460
1461     return $prefs;
1462 }
1463
1464 function common_mime_type_match($type, $avail)
1465 {
1466     if(array_key_exists($type, $avail)) {
1467         return $type;
1468     } else {
1469         $parts = explode('/', $type);
1470         if(array_key_exists($parts[0] . '/*', $avail)) {
1471             return $parts[0] . '/*';
1472         } elseif(array_key_exists('*/*', $avail)) {
1473             return '*/*';
1474         } else {
1475             return null;
1476         }
1477     }
1478 }
1479
1480 function common_negotiate_type($cprefs, $sprefs)
1481 {
1482     $combine = array();
1483
1484     foreach(array_keys($sprefs) as $type) {
1485         $parts = explode('/', $type);
1486         if($parts[1] != '*') {
1487             $ckey = common_mime_type_match($type, $cprefs);
1488             if($ckey) {
1489                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1490             }
1491         }
1492     }
1493
1494     foreach(array_keys($cprefs) as $type) {
1495         $parts = explode('/', $type);
1496         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1497             $skey = common_mime_type_match($type, $sprefs);
1498             if($skey) {
1499                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1500             }
1501         }
1502     }
1503
1504     $bestq = 0;
1505     $besttype = 'text/html';
1506
1507     foreach(array_keys($combine) as $type) {
1508         if($combine[$type] > $bestq) {
1509             $besttype = $type;
1510             $bestq = $combine[$type];
1511         }
1512     }
1513
1514     if ('text/html' === $besttype) {
1515         return "text/html; charset=utf-8";
1516     }
1517     return $besttype;
1518 }
1519
1520 function common_config($main, $sub)
1521 {
1522     global $config;
1523     return (array_key_exists($main, $config) &&
1524             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1525 }
1526
1527 function common_copy_args($from)
1528 {
1529     $to = array();
1530     $strip = get_magic_quotes_gpc();
1531     foreach ($from as $k => $v) {
1532         if($strip) {
1533             if(is_array($v)) {
1534                 $to[$k] = common_copy_args($v);
1535             } else {
1536                 $to[$k] = stripslashes($v);
1537             }
1538         } else {
1539             $to[$k] = $v;
1540         }
1541     }
1542     return $to;
1543 }
1544
1545 /**
1546  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1547  * This is used before handing a request off to OAuthRequest::from_request.
1548  * @fixme Doesn't consider vars other than _POST and _GET?
1549  * @fixme Can't be undone and could corrupt data if run twice.
1550  */
1551 function common_remove_magic_from_request()
1552 {
1553     if(get_magic_quotes_gpc()) {
1554         $_POST=array_map('stripslashes',$_POST);
1555         $_GET=array_map('stripslashes',$_GET);
1556     }
1557 }
1558
1559 function common_user_uri(&$user)
1560 {
1561     return common_local_url('userbyid', array('id' => $user->id),
1562                             null, null, false);
1563 }
1564
1565 function common_notice_uri(&$notice)
1566 {
1567     return common_local_url('shownotice',
1568                             array('notice' => $notice->id),
1569                             null, null, false);
1570 }
1571
1572 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1573
1574 function common_confirmation_code($bits)
1575 {
1576     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1577     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1578     $chars = ceil($bits/5);
1579     $code = '';
1580     for ($i = 0; $i < $chars; $i++) {
1581         // XXX: convert to string and back
1582         $num = hexdec(common_good_rand(1));
1583         // XXX: randomness is too precious to throw away almost
1584         // 40% of the bits we get!
1585         $code .= $codechars[$num%32];
1586     }
1587     return $code;
1588 }
1589
1590 // convert markup to HTML
1591
1592 function common_markup_to_html($c)
1593 {
1594     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1595     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1596     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1597     return Markdown($c);
1598 }
1599
1600 function common_profile_uri($profile)
1601 {
1602     if (!$profile) {
1603         return null;
1604     }
1605     $user = User::staticGet($profile->id);
1606     if ($user) {
1607         return $user->uri;
1608     }
1609
1610     $remote = Remote_profile::staticGet($profile->id);
1611     if ($remote) {
1612         return $remote->uri;
1613     }
1614     // XXX: this is a very bad profile!
1615     return null;
1616 }
1617
1618 function common_canonical_sms($sms)
1619 {
1620     // strip non-digits
1621     preg_replace('/\D/', '', $sms);
1622     return $sms;
1623 }
1624
1625 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1626 {
1627     switch ($errno) {
1628
1629      case E_ERROR:
1630      case E_COMPILE_ERROR:
1631      case E_CORE_ERROR:
1632      case E_USER_ERROR:
1633      case E_PARSE:
1634      case E_RECOVERABLE_ERROR:
1635         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1636         die();
1637         break;
1638
1639      case E_WARNING:
1640      case E_COMPILE_WARNING:
1641      case E_CORE_WARNING:
1642      case E_USER_WARNING:
1643         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1644         break;
1645
1646      case E_NOTICE:
1647      case E_USER_NOTICE:
1648         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1649         break;
1650
1651      case E_STRICT:
1652      case E_DEPRECATED:
1653      case E_USER_DEPRECATED:
1654         // XXX: config variable to log this stuff, too
1655         break;
1656
1657      default:
1658         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1659         die();
1660         break;
1661     }
1662
1663     // FIXME: show error page if we're on the Web
1664     /* Don't execute PHP internal error handler */
1665     return true;
1666 }
1667
1668 function common_session_token()
1669 {
1670     common_ensure_session();
1671     if (!array_key_exists('token', $_SESSION)) {
1672         $_SESSION['token'] = common_good_rand(64);
1673     }
1674     return $_SESSION['token'];
1675 }
1676
1677 function common_cache_key($extra)
1678 {
1679     return Cache::key($extra);
1680 }
1681
1682 function common_keyize($str)
1683 {
1684     return Cache::keyize($str);
1685 }
1686
1687 function common_memcache()
1688 {
1689     return Cache::instance();
1690 }
1691
1692 function common_license_terms($uri)
1693 {
1694     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1695         return explode('-',$matches[1]);
1696     }
1697     return array($uri);
1698 }
1699
1700 function common_compatible_license($from, $to)
1701 {
1702     $from_terms = common_license_terms($from);
1703     // public domain and cc-by are compatible with everything
1704     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1705         return true;
1706     }
1707     $to_terms = common_license_terms($to);
1708     // sa is compatible across versions. IANAL
1709     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1710         return count(array_diff($from_terms, $to_terms)) == 0;
1711     }
1712     // XXX: better compatibility check needed here!
1713     // Should at least normalise URIs
1714     return ($from == $to);
1715 }
1716
1717 /**
1718  * returns a quoted table name, if required according to config
1719  */
1720 function common_database_tablename($tablename)
1721 {
1722
1723   if(common_config('db','quote_identifiers')) {
1724       $tablename = '"'. $tablename .'"';
1725   }
1726   //table prefixes could be added here later
1727   return $tablename;
1728 }
1729
1730 /**
1731  * Shorten a URL with the current user's configured shortening service,
1732  * or ur1.ca if configured, or not at all if no shortening is set up.
1733  * Length is not considered.
1734  *
1735  * @param string $long_url
1736  * @return string may return the original URL if shortening failed
1737  *
1738  * @fixme provide a way to specify a particular shortener
1739  * @fixme provide a way to specify to use a given user's shortening preferences
1740  */
1741 function common_shorten_url($long_url)
1742 {
1743     $long_url = trim($long_url);
1744     $user = common_current_user();
1745     if (empty($user)) {
1746         // common current user does not find a user when called from the XMPP daemon
1747         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1748         $shortenerName = 'ur1.ca';
1749     } else {
1750         $shortenerName = $user->urlshorteningservice;
1751     }
1752
1753     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1754         //URL wasn't shortened, so return the long url
1755         return $long_url;
1756     }else{
1757         //URL was shortened, so return the result
1758         return trim($shortenedUrl);
1759     }
1760 }
1761
1762 /**
1763  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1764  *               null if not a web request
1765  *
1766  * @fixme X-Forwarded-For can be chained by multiple proxies;
1767           we should parse the list and provide a cleaner array
1768  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1769  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1770  *        use function to get exact request headers from Apache if possible.
1771  */
1772 function common_client_ip()
1773 {
1774     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1775         return null;
1776     }
1777
1778     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1779         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1780             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1781         } else {
1782             $proxy = $_SERVER['REMOTE_ADDR'];
1783         }
1784         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1785     } else {
1786         $proxy = null;
1787         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1788             $ip = $_SERVER['HTTP_CLIENT_IP'];
1789         } else {
1790             $ip = $_SERVER['REMOTE_ADDR'];
1791         }
1792     }
1793
1794     return array($proxy, $ip);
1795 }
1796
1797 function common_url_to_nickname($url)
1798 {
1799     static $bad = array('query', 'user', 'password', 'port', 'fragment');
1800
1801     $parts = parse_url($url);
1802
1803     # If any of these parts exist, this won't work
1804
1805     foreach ($bad as $badpart) {
1806         if (array_key_exists($badpart, $parts)) {
1807             return null;
1808         }
1809     }
1810
1811     # We just have host and/or path
1812
1813     # If it's just a host...
1814     if (array_key_exists('host', $parts) &&
1815         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1816     {
1817         $hostparts = explode('.', $parts['host']);
1818
1819         # Try to catch common idiom of nickname.service.tld
1820
1821         if ((count($hostparts) > 2) &&
1822             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1823             (strcmp($hostparts[0], 'www') != 0))
1824         {
1825             return common_nicknamize($hostparts[0]);
1826         } else {
1827             # Do the whole hostname
1828             return common_nicknamize($parts['host']);
1829         }
1830     } else {
1831         if (array_key_exists('path', $parts)) {
1832             # Strip starting, ending slashes
1833             $path = preg_replace('@/$@', '', $parts['path']);
1834             $path = preg_replace('@^/@', '', $path);
1835             $path = basename($path);
1836             if ($path) {
1837                 return common_nicknamize($path);
1838             }
1839         }
1840     }
1841
1842     return null;
1843 }
1844
1845 function common_nicknamize($str)
1846 {
1847     $str = preg_replace('/\W/', '', $str);
1848     return strtolower($str);
1849 }