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