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