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