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