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