]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch 'testing' 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($id, $r);
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($profile_id, $text)
435 {
436     $mentions = common_find_mentions($profile_id, $text);
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($profile_id, $text)
491 {
492     $mentions = array();
493
494     $sender = Profile::staticGet('id', $profile_id);
495
496     if (empty($sender)) {
497         return $mentions;
498     }
499
500     if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
501
502         preg_match_all('/^T ([A-Z0-9]{1,64}) /',
503                        $text,
504                        $tmatches,
505                        PREG_OFFSET_CAPTURE);
506
507         preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
508                        $text,
509                        $atmatches,
510                        PREG_OFFSET_CAPTURE);
511
512         $matches = array_merge($tmatches[1], $atmatches[1]);
513
514         foreach ($matches as $match) {
515
516             $nickname = common_canonical_nickname($match[0]);
517             $mentioned = common_relative_profile($sender, $nickname);
518
519             if (!empty($mentioned)) {
520
521                 $user = User::staticGet('id', $mentioned->id);
522
523                 if ($user) {
524                     $url = common_local_url('userbyid', array('id' => $user->id));
525                 } else {
526                     $url = $mentioned->profileurl;
527                 }
528
529                 $mention = array('mentioned' => array($mentioned),
530                                  'text' => $match[0],
531                                  'position' => $match[1],
532                                  'url' => $url);
533
534                 if (!empty($mentioned->fullname)) {
535                     $mention['title'] = $mentioned->fullname;
536                 }
537
538                 $mentions[] = $mention;
539             }
540         }
541
542         // @#tag => mention of all subscriptions tagged 'tag'
543
544         preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
545                        $text,
546                        $hmatches,
547                        PREG_OFFSET_CAPTURE);
548
549         foreach ($hmatches[1] as $hmatch) {
550
551             $tag = common_canonical_tag($hmatch[0]);
552
553             $tagged = Profile_tag::getTagged($sender->id, $tag);
554
555             $url = common_local_url('subscriptions',
556                                     array('nickname' => $sender->nickname,
557                                           'tag' => $tag));
558
559             $mentions[] = array('mentioned' => $tagged,
560                                 'text' => $hmatch[0],
561                                 'position' => $hmatch[1],
562                                 'url' => $url);
563         }
564
565         Event::handle('EndFindMentions', array($sender, $text, &$mentions));
566     }
567
568     return $mentions;
569 }
570
571 function common_render_text($text)
572 {
573     $r = htmlspecialchars($text);
574
575     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
576     $r = common_replace_urls_callback($r, 'common_linkify');
577     $r = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
578     // XXX: machine tags
579     return $r;
580 }
581
582 function common_replace_urls_callback($text, $callback, $notice_id = null) {
583     // Start off with a regex
584     $regex = '#'.
585     '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
586     '('.
587         '(?:'.
588             '(?:'. //Known protocols
589                 '(?:'.
590                     '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
591                     '|'.
592                     '(?:(?:mailto|aim|tel|xmpp):)'.
593                 ')'.
594                 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
595                 '(?:'.
596                     '(?:'.
597                         '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
598                     ')|(?:'.
599                         '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
600                     ')'.
601                 ')'.
602             ')'.
603             '|(?:(?: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
604             '|(?:'. //IPv6
605                 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
606             ')|(?:'. //DNS
607                 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
608                 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
609                 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
610                 '(?: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)'.
611             ')(?![\pN\pL\-\_])'.
612         ')'.
613         '(?:'.
614             '(?:\:\d+)?'. //:port
615             '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
616             '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
617             '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
618         ')(?<![\?\.\,\#\,])'.
619     ')'.
620     '#ixu';
621     //preg_match_all($regex,$text,$matches);
622     //print_r($matches);
623     return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
624 }
625
626 function callback_helper($matches, $callback, $notice_id) {
627     $url=$matches[1];
628     $left = strpos($matches[0],$url);
629     $right = $left+strlen($url);
630
631     $groupSymbolSets=array(
632         array(
633             'left'=>'(',
634             'right'=>')'
635         ),
636         array(
637             'left'=>'[',
638             'right'=>']'
639         ),
640         array(
641             'left'=>'{',
642             'right'=>'}'
643         ),
644         array(
645             'left'=>'<',
646             'right'=>'>'
647         )
648     );
649     $cannotEndWith=array('.','?',',','#');
650     $original_url=$url;
651     do{
652         $original_url=$url;
653         foreach($groupSymbolSets as $groupSymbolSet){
654             if(substr($url,-1)==$groupSymbolSet['right']){
655                 $group_left_count = substr_count($url,$groupSymbolSet['left']);
656                 $group_right_count = substr_count($url,$groupSymbolSet['right']);
657                 if($group_left_count<$group_right_count){
658                     $right-=1;
659                     $url=substr($url,0,-1);
660                 }
661             }
662         }
663         if(in_array(substr($url,-1),$cannotEndWith)){
664             $right-=1;
665             $url=substr($url,0,-1);
666         }
667     }while($original_url!=$url);
668
669     if(empty($notice_id)){
670         $result = call_user_func_array($callback, array($url));
671     }else{
672         $result = call_user_func_array($callback, array(array($url,$notice_id)) );
673     }
674     return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
675 }
676
677 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
678     // lambda implementation in a separate file; PHP 5.2 won't parse it.
679     require_once INSTALLDIR . "/lib/curry.php";
680 } else {
681     function curry($fn) {
682         $args = func_get_args();
683         array_shift($args);
684         $id = uniqid('_partial');
685         $GLOBALS[$id] = array($fn, $args);
686         return create_function('',
687                                '$args = func_get_args(); '.
688                                'return call_user_func_array('.
689                                '$GLOBALS["'.$id.'"][0],'.
690                                'array_merge('.
691                                '$args,'.
692                                '$GLOBALS["'.$id.'"][1]));');
693     }
694 }
695
696 function common_linkify($url) {
697     // It comes in special'd, so we unspecial it before passing to the stringifying
698     // functions
699     $url = htmlspecialchars_decode($url);
700
701    if(strpos($url, '@') !== false && strpos($url, ':') === false) {
702        //url is an email address without the mailto: protocol
703        $canon = "mailto:$url";
704        $longurl = "mailto:$url";
705    }else{
706
707         $canon = File_redirection::_canonUrl($url);
708
709         $longurl_data = File_redirection::where($canon);
710         if (is_array($longurl_data)) {
711             $longurl = $longurl_data['url'];
712         } elseif (is_string($longurl_data)) {
713             $longurl = $longurl_data;
714         } else {
715             throw new ServerException("Can't linkify url '$url'");
716         }
717     }
718     $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
719
720     $is_attachment = false;
721     $attachment_id = null;
722     $has_thumb = false;
723
724     // Check to see whether this is a known "attachment" URL.
725
726     $f = File::staticGet('url', $longurl);
727
728     if (empty($f)) {
729         // XXX: this writes to the database. :<
730         $f = File::processNew($longurl);
731     }
732
733     if (!empty($f)) {
734         if ($f->isEnclosure()) {
735             $is_attachment = true;
736             $attachment_id = $f->id;
737         } else {
738             $foe = File_oembed::staticGet('file_id', $f->id);
739             if (!empty($foe)) {
740                 // if it has OEmbed info, it's an attachment, too
741                 $is_attachment = true;
742                 $attachment_id = $f->id;
743
744                 $thumb = File_thumbnail::staticGet('file_id', $f->id);
745                 if (!empty($thumb)) {
746                     $has_thumb = true;
747                 }
748             }
749         }
750     }
751
752     // Add clippy
753     if ($is_attachment) {
754         $attrs['class'] = 'attachment';
755         if ($has_thumb) {
756             $attrs['class'] = 'attachment thumbnail';
757         }
758         $attrs['id'] = "attachment-{$attachment_id}";
759     }
760
761     return XMLStringer::estring('a', $attrs, $url);
762 }
763
764 function common_shorten_links($text)
765 {
766     $maxLength = Notice::maxContent();
767     if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
768     return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
769 }
770
771 function common_xml_safe_str($str)
772 {
773     // Neutralize control codes and surrogates
774         return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
775 }
776
777 function common_tag_link($tag)
778 {
779     $canonical = common_canonical_tag($tag);
780     $url = common_local_url('tag', array('tag' => $canonical));
781     $xs = new XMLStringer();
782     $xs->elementStart('span', 'tag');
783     $xs->element('a', array('href' => $url,
784                             'rel' => 'tag'),
785                  $tag);
786     $xs->elementEnd('span');
787     return $xs->getString();
788 }
789
790 function common_canonical_tag($tag)
791 {
792   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
793   return str_replace(array('-', '_', '.'), '', $tag);
794 }
795
796 function common_valid_profile_tag($str)
797 {
798     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
799 }
800
801 function common_group_link($sender_id, $nickname)
802 {
803     $sender = Profile::staticGet($sender_id);
804     $group = User_group::getForNickname($nickname);
805     if ($sender && $group && $sender->isMember($group)) {
806         $attrs = array('href' => $group->permalink(),
807                        'class' => 'url');
808         if (!empty($group->fullname)) {
809             $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
810         }
811         $xs = new XMLStringer();
812         $xs->elementStart('span', 'vcard');
813         $xs->elementStart('a', $attrs);
814         $xs->element('span', 'fn nickname', $nickname);
815         $xs->elementEnd('a');
816         $xs->elementEnd('span');
817         return $xs->getString();
818     } else {
819         return $nickname;
820     }
821 }
822
823 function common_relative_profile($sender, $nickname, $dt=null)
824 {
825     // Try to find profiles this profile is subscribed to that have this nickname
826     $recipient = new Profile();
827     // XXX: use a join instead of a subquery
828     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
829     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
830     if ($recipient->find(true)) {
831         // XXX: should probably differentiate between profiles with
832         // the same name by date of most recent update
833         return $recipient;
834     }
835     // Try to find profiles that listen to this profile and that have this nickname
836     $recipient = new Profile();
837     // XXX: use a join instead of a subquery
838     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
839     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
840     if ($recipient->find(true)) {
841         // XXX: should probably differentiate between profiles with
842         // the same name by date of most recent update
843         return $recipient;
844     }
845     // If this is a local user, try to find a local user with that nickname.
846     $sender = User::staticGet($sender->id);
847     if ($sender) {
848         $recipient_user = User::staticGet('nickname', $nickname);
849         if ($recipient_user) {
850             return $recipient_user->getProfile();
851         }
852     }
853     // Otherwise, no links. @messages from local users to remote users,
854     // or from remote users to other remote users, are just
855     // outside our ability to make intelligent guesses about
856     return null;
857 }
858
859 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
860 {
861     $r = Router::get();
862     $path = $r->build($action, $args, $params, $fragment);
863
864     $ssl = common_is_sensitive($action);
865
866     if (common_config('site','fancy')) {
867         $url = common_path(mb_substr($path, 1), $ssl, $addSession);
868     } else {
869         if (mb_strpos($path, '/index.php') === 0) {
870             $url = common_path(mb_substr($path, 1), $ssl, $addSession);
871         } else {
872             $url = common_path('index.php'.$path, $ssl, $addSession);
873         }
874     }
875     return $url;
876 }
877
878 function common_is_sensitive($action)
879 {
880     static $sensitive = array('login', 'register', 'passwordsettings',
881                               'twittersettings', 'api');
882     $ssl = null;
883
884     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
885         $ssl = in_array($action, $sensitive);
886     }
887
888     return $ssl;
889 }
890
891 function common_path($relative, $ssl=false, $addSession=true)
892 {
893     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
894
895     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
896         || common_config('site', 'ssl') === 'always') {
897         $proto = 'https';
898         if (is_string(common_config('site', 'sslserver')) &&
899             mb_strlen(common_config('site', 'sslserver')) > 0) {
900             $serverpart = common_config('site', 'sslserver');
901         } else if (common_config('site', 'server')) {
902             $serverpart = common_config('site', 'server');
903         } else {
904             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
905         }
906     } else {
907         $proto = 'http';
908         if (common_config('site', 'server')) {
909             $serverpart = common_config('site', 'server');
910         } else {
911             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
912         }
913     }
914
915     if ($addSession) {
916         $relative = common_inject_session($relative, $serverpart);
917     }
918
919     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
920 }
921
922 function common_inject_session($url, $serverpart = null)
923 {
924     if (common_have_session()) {
925
926         if (empty($serverpart)) {
927             $serverpart = parse_url($url, PHP_URL_HOST);
928         }
929
930         $currentServer = $_SERVER['HTTP_HOST'];
931
932         // Are we pointing to another server (like an SSL server?)
933
934         if (!empty($currentServer) &&
935             0 != strcasecmp($currentServer, $serverpart)) {
936             // Pass the session ID as a GET parameter
937             $sesspart = session_name() . '=' . session_id();
938             $i = strpos($url, '?');
939             if ($i === false) { // no GET params, just append
940                 $url .= '?' . $sesspart;
941             } else {
942                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
943             }
944         }
945     }
946
947     return $url;
948 }
949
950 function common_date_string($dt)
951 {
952     // XXX: do some sexy date formatting
953     // return date(DATE_RFC822, $dt);
954     $t = strtotime($dt);
955     $now = time();
956     $diff = $now - $t;
957
958     if ($now < $t) { // that shouldn't happen!
959         return common_exact_date($dt);
960     } else if ($diff < 60) {
961         return _('a few seconds ago');
962     } else if ($diff < 92) {
963         return _('about a minute ago');
964     } else if ($diff < 3300) {
965         return sprintf(_('about %d minutes ago'), round($diff/60));
966     } else if ($diff < 5400) {
967         return _('about an hour ago');
968     } else if ($diff < 22 * 3600) {
969         return sprintf(_('about %d hours ago'), round($diff/3600));
970     } else if ($diff < 37 * 3600) {
971         return _('about a day ago');
972     } else if ($diff < 24 * 24 * 3600) {
973         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
974     } else if ($diff < 46 * 24 * 3600) {
975         return _('about a month ago');
976     } else if ($diff < 330 * 24 * 3600) {
977         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
978     } else if ($diff < 480 * 24 * 3600) {
979         return _('about a year ago');
980     } else {
981         return common_exact_date($dt);
982     }
983 }
984
985 function common_exact_date($dt)
986 {
987     static $_utc;
988     static $_siteTz;
989
990     if (!$_utc) {
991         $_utc = new DateTimeZone('UTC');
992         $_siteTz = new DateTimeZone(common_timezone());
993     }
994
995     $dateStr = date('d F Y H:i:s', strtotime($dt));
996     $d = new DateTime($dateStr, $_utc);
997     $d->setTimezone($_siteTz);
998     return $d->format(DATE_RFC850);
999 }
1000
1001 function common_date_w3dtf($dt)
1002 {
1003     $dateStr = date('d F Y H:i:s', strtotime($dt));
1004     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1005     $d->setTimezone(new DateTimeZone(common_timezone()));
1006     return $d->format(DATE_W3C);
1007 }
1008
1009 function common_date_rfc2822($dt)
1010 {
1011     $dateStr = date('d F Y H:i:s', strtotime($dt));
1012     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1013     $d->setTimezone(new DateTimeZone(common_timezone()));
1014     return $d->format('r');
1015 }
1016
1017 function common_date_iso8601($dt)
1018 {
1019     $dateStr = date('d F Y H:i:s', strtotime($dt));
1020     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1021     $d->setTimezone(new DateTimeZone(common_timezone()));
1022     return $d->format('c');
1023 }
1024
1025 function common_sql_now()
1026 {
1027     return common_sql_date(time());
1028 }
1029
1030 function common_sql_date($datetime)
1031 {
1032     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1033 }
1034
1035 /**
1036  * Return an SQL fragment to calculate an age-based weight from a given
1037  * timestamp or datetime column.
1038  *
1039  * @param string $column name of field we're comparing against current time
1040  * @param integer $dropoff divisor for age in seconds before exponentiation
1041  * @return string SQL fragment
1042  */
1043 function common_sql_weight($column, $dropoff)
1044 {
1045     if (common_config('db', 'type') == 'pgsql') {
1046         // PostgreSQL doesn't support timestampdiff function.
1047         // @fixme will this use the right time zone?
1048         // @fixme does this handle cross-year subtraction correctly?
1049         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1050     } else {
1051         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1052     }
1053 }
1054
1055 function common_redirect($url, $code=307)
1056 {
1057     static $status = array(301 => "Moved Permanently",
1058                            302 => "Found",
1059                            303 => "See Other",
1060                            307 => "Temporary Redirect");
1061
1062     header('HTTP/1.1 '.$code.' '.$status[$code]);
1063     header("Location: $url");
1064
1065     $xo = new XMLOutputter();
1066     $xo->startXML('a',
1067                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1068                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1069     $xo->element('a', array('href' => $url), $url);
1070     $xo->endXML();
1071     exit;
1072 }
1073
1074 function common_broadcast_notice($notice, $remote=false)
1075 {
1076     // DO NOTHING!
1077 }
1078
1079 // Stick the notice on the queue
1080
1081 function common_enqueue_notice($notice)
1082 {
1083     static $localTransports = array('omb',
1084                                     'ping');
1085
1086     $transports = array();
1087     if (common_config('sms', 'enabled')) {
1088         $transports[] = 'sms';
1089     }
1090     if (Event::hasHandler('HandleQueuedNotice')) {
1091         $transports[] = 'plugin';
1092     }
1093
1094     $xmpp = common_config('xmpp', 'enabled');
1095
1096     if ($xmpp) {
1097         $transports[] = 'jabber';
1098     }
1099
1100     // @fixme move these checks into QueueManager and/or individual handlers
1101     if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1102         $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1103         $transports = array_merge($transports, $localTransports);
1104         if ($xmpp) {
1105             $transports[] = 'public';
1106         }
1107     }
1108
1109     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1110
1111         $qm = QueueManager::get();
1112
1113         foreach ($transports as $transport)
1114         {
1115             $qm->enqueue($notice, $transport);
1116         }
1117
1118         Event::handle('EndEnqueueNotice', array($notice, $transports));
1119     }
1120
1121     return true;
1122 }
1123
1124 /**
1125  * Broadcast profile updates to OMB and other remote subscribers.
1126  *
1127  * Since this may be slow with a lot of subscribers or bad remote sites,
1128  * this is run through the background queues if possible.
1129  */
1130 function common_broadcast_profile(Profile $profile)
1131 {
1132     $qm = QueueManager::get();
1133     $qm->enqueue($profile, "profile");
1134     return true;
1135 }
1136
1137 function common_profile_url($nickname)
1138 {
1139     return common_local_url('showstream', array('nickname' => $nickname),
1140                             null, null, false);
1141 }
1142
1143 // Should make up a reasonable root URL
1144
1145 function common_root_url($ssl=false)
1146 {
1147     $url = common_path('', $ssl, false);
1148     $i = strpos($url, '?');
1149     if ($i !== false) {
1150         $url = substr($url, 0, $i);
1151     }
1152     return $url;
1153 }
1154
1155 // returns $bytes bytes of random data as a hexadecimal string
1156 // "good" here is a goal and not a guarantee
1157
1158 function common_good_rand($bytes)
1159 {
1160     // XXX: use random.org...?
1161     if (@file_exists('/dev/urandom')) {
1162         return common_urandom($bytes);
1163     } else { // FIXME: this is probably not good enough
1164         return common_mtrand($bytes);
1165     }
1166 }
1167
1168 function common_urandom($bytes)
1169 {
1170     $h = fopen('/dev/urandom', 'rb');
1171     // should not block
1172     $src = fread($h, $bytes);
1173     fclose($h);
1174     $enc = '';
1175     for ($i = 0; $i < $bytes; $i++) {
1176         $enc .= sprintf("%02x", (ord($src[$i])));
1177     }
1178     return $enc;
1179 }
1180
1181 function common_mtrand($bytes)
1182 {
1183     $enc = '';
1184     for ($i = 0; $i < $bytes; $i++) {
1185         $enc .= sprintf("%02x", mt_rand(0, 255));
1186     }
1187     return $enc;
1188 }
1189
1190 function common_set_returnto($url)
1191 {
1192     common_ensure_session();
1193     $_SESSION['returnto'] = $url;
1194 }
1195
1196 function common_get_returnto()
1197 {
1198     common_ensure_session();
1199     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1200 }
1201
1202 function common_timestamp()
1203 {
1204     return date('YmdHis');
1205 }
1206
1207 function common_ensure_syslog()
1208 {
1209     static $initialized = false;
1210     if (!$initialized) {
1211         openlog(common_config('syslog', 'appname'), 0,
1212             common_config('syslog', 'facility'));
1213         $initialized = true;
1214     }
1215 }
1216
1217 function common_log_line($priority, $msg)
1218 {
1219     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1220                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1221     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1222 }
1223
1224 function common_request_id()
1225 {
1226     $pid = getmypid();
1227     $server = common_config('site', 'server');
1228     if (php_sapi_name() == 'cli') {
1229         $script = basename($_SERVER['PHP_SELF']);
1230         return "$server:$script:$pid";
1231     } else {
1232         static $req_id = null;
1233         if (!isset($req_id)) {
1234             $req_id = substr(md5(mt_rand()), 0, 8);
1235         }
1236         if (isset($_SERVER['REQUEST_URI'])) {
1237             $url = $_SERVER['REQUEST_URI'];
1238         }
1239         $method = $_SERVER['REQUEST_METHOD'];
1240         return "$server:$pid.$req_id $method $url";
1241     }
1242 }
1243
1244 function common_log($priority, $msg, $filename=null)
1245 {
1246     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1247         $msg = '[' . common_request_id() . '] ' . $msg;
1248         $logfile = common_config('site', 'logfile');
1249         if ($logfile) {
1250             $log = fopen($logfile, "a");
1251             if ($log) {
1252                 $output = common_log_line($priority, $msg);
1253                 fwrite($log, $output);
1254                 fclose($log);
1255             }
1256         } else {
1257             common_ensure_syslog();
1258             syslog($priority, $msg);
1259         }
1260         Event::handle('EndLog', array($priority, $msg, $filename));
1261     }
1262 }
1263
1264 function common_debug($msg, $filename=null)
1265 {
1266     if ($filename) {
1267         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1268     } else {
1269         common_log(LOG_DEBUG, $msg);
1270     }
1271 }
1272
1273 function common_log_db_error(&$object, $verb, $filename=null)
1274 {
1275     $objstr = common_log_objstring($object);
1276     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1277     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1278 }
1279
1280 function common_log_objstring(&$object)
1281 {
1282     if (is_null($object)) {
1283         return "null";
1284     }
1285     if (!($object instanceof DB_DataObject)) {
1286         return "(unknown)";
1287     }
1288     $arr = $object->toArray();
1289     $fields = array();
1290     foreach ($arr as $k => $v) {
1291         if (is_object($v)) {
1292             $fields[] = "$k='".get_class($v)."'";
1293         } else {
1294             $fields[] = "$k='$v'";
1295         }
1296     }
1297     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1298     return $objstring;
1299 }
1300
1301 function common_valid_http_url($url)
1302 {
1303     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1304 }
1305
1306 function common_valid_tag($tag)
1307 {
1308     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1309         return (Validate::email($matches[1]) ||
1310                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1311     }
1312     return false;
1313 }
1314
1315 /* Following functions are copied from MediaWiki GlobalFunctions.php
1316  * and written by Evan Prodromou. */
1317
1318 function common_accept_to_prefs($accept, $def = '*/*')
1319 {
1320     // No arg means accept anything (per HTTP spec)
1321     if(!$accept) {
1322         return array($def => 1);
1323     }
1324
1325     $prefs = array();
1326
1327     $parts = explode(',', $accept);
1328
1329     foreach($parts as $part) {
1330         // FIXME: doesn't deal with params like 'text/html; level=1'
1331         @list($value, $qpart) = explode(';', trim($part));
1332         $match = array();
1333         if(!isset($qpart)) {
1334             $prefs[$value] = 1;
1335         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1336             $prefs[$value] = $match[1];
1337         }
1338     }
1339
1340     return $prefs;
1341 }
1342
1343 function common_mime_type_match($type, $avail)
1344 {
1345     if(array_key_exists($type, $avail)) {
1346         return $type;
1347     } else {
1348         $parts = explode('/', $type);
1349         if(array_key_exists($parts[0] . '/*', $avail)) {
1350             return $parts[0] . '/*';
1351         } elseif(array_key_exists('*/*', $avail)) {
1352             return '*/*';
1353         } else {
1354             return null;
1355         }
1356     }
1357 }
1358
1359 function common_negotiate_type($cprefs, $sprefs)
1360 {
1361     $combine = array();
1362
1363     foreach(array_keys($sprefs) as $type) {
1364         $parts = explode('/', $type);
1365         if($parts[1] != '*') {
1366             $ckey = common_mime_type_match($type, $cprefs);
1367             if($ckey) {
1368                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1369             }
1370         }
1371     }
1372
1373     foreach(array_keys($cprefs) as $type) {
1374         $parts = explode('/', $type);
1375         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1376             $skey = common_mime_type_match($type, $sprefs);
1377             if($skey) {
1378                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1379             }
1380         }
1381     }
1382
1383     $bestq = 0;
1384     $besttype = 'text/html';
1385
1386     foreach(array_keys($combine) as $type) {
1387         if($combine[$type] > $bestq) {
1388             $besttype = $type;
1389             $bestq = $combine[$type];
1390         }
1391     }
1392
1393     if ('text/html' === $besttype) {
1394         return "text/html; charset=utf-8";
1395     }
1396     return $besttype;
1397 }
1398
1399 function common_config($main, $sub)
1400 {
1401     global $config;
1402     return (array_key_exists($main, $config) &&
1403             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1404 }
1405
1406 function common_copy_args($from)
1407 {
1408     $to = array();
1409     $strip = get_magic_quotes_gpc();
1410     foreach ($from as $k => $v) {
1411         $to[$k] = ($strip) ? stripslashes($v) : $v;
1412     }
1413     return $to;
1414 }
1415
1416 /**
1417  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1418  * This is used before handing a request off to OAuthRequest::from_request.
1419  * @fixme Doesn't consider vars other than _POST and _GET?
1420  * @fixme Can't be undone and could corrupt data if run twice.
1421  */
1422 function common_remove_magic_from_request()
1423 {
1424     if(get_magic_quotes_gpc()) {
1425         $_POST=array_map('stripslashes',$_POST);
1426         $_GET=array_map('stripslashes',$_GET);
1427     }
1428 }
1429
1430 function common_user_uri(&$user)
1431 {
1432     return common_local_url('userbyid', array('id' => $user->id),
1433                             null, null, false);
1434 }
1435
1436 function common_notice_uri(&$notice)
1437 {
1438     return common_local_url('shownotice',
1439                             array('notice' => $notice->id));
1440 }
1441
1442 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1443
1444 function common_confirmation_code($bits)
1445 {
1446     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1447     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1448     $chars = ceil($bits/5);
1449     $code = '';
1450     for ($i = 0; $i < $chars; $i++) {
1451         // XXX: convert to string and back
1452         $num = hexdec(common_good_rand(1));
1453         // XXX: randomness is too precious to throw away almost
1454         // 40% of the bits we get!
1455         $code .= $codechars[$num%32];
1456     }
1457     return $code;
1458 }
1459
1460 // convert markup to HTML
1461
1462 function common_markup_to_html($c)
1463 {
1464     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1465     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1466     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1467     return Markdown($c);
1468 }
1469
1470 function common_profile_uri($profile)
1471 {
1472     if (!$profile) {
1473         return null;
1474     }
1475     $user = User::staticGet($profile->id);
1476     if ($user) {
1477         return $user->uri;
1478     }
1479
1480     $remote = Remote_profile::staticGet($profile->id);
1481     if ($remote) {
1482         return $remote->uri;
1483     }
1484     // XXX: this is a very bad profile!
1485     return null;
1486 }
1487
1488 function common_canonical_sms($sms)
1489 {
1490     // strip non-digits
1491     preg_replace('/\D/', '', $sms);
1492     return $sms;
1493 }
1494
1495 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1496 {
1497     switch ($errno) {
1498
1499      case E_ERROR:
1500      case E_COMPILE_ERROR:
1501      case E_CORE_ERROR:
1502      case E_USER_ERROR:
1503      case E_PARSE:
1504      case E_RECOVERABLE_ERROR:
1505         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1506         die();
1507         break;
1508
1509      case E_WARNING:
1510      case E_COMPILE_WARNING:
1511      case E_CORE_WARNING:
1512      case E_USER_WARNING:
1513         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1514         break;
1515
1516      case E_NOTICE:
1517      case E_USER_NOTICE:
1518         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1519         break;
1520
1521      case E_STRICT:
1522      case E_DEPRECATED:
1523      case E_USER_DEPRECATED:
1524         // XXX: config variable to log this stuff, too
1525         break;
1526
1527      default:
1528         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1529         die();
1530         break;
1531     }
1532
1533     // FIXME: show error page if we're on the Web
1534     /* Don't execute PHP internal error handler */
1535     return true;
1536 }
1537
1538 function common_session_token()
1539 {
1540     common_ensure_session();
1541     if (!array_key_exists('token', $_SESSION)) {
1542         $_SESSION['token'] = common_good_rand(64);
1543     }
1544     return $_SESSION['token'];
1545 }
1546
1547 function common_cache_key($extra)
1548 {
1549     return Cache::key($extra);
1550 }
1551
1552 function common_keyize($str)
1553 {
1554     return Cache::keyize($str);
1555 }
1556
1557 function common_memcache()
1558 {
1559     return Cache::instance();
1560 }
1561
1562 function common_license_terms($uri)
1563 {
1564     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1565         return explode('-',$matches[1]);
1566     }
1567     return array($uri);
1568 }
1569
1570 function common_compatible_license($from, $to)
1571 {
1572     $from_terms = common_license_terms($from);
1573     // public domain and cc-by are compatible with everything
1574     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1575         return true;
1576     }
1577     $to_terms = common_license_terms($to);
1578     // sa is compatible across versions. IANAL
1579     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1580         return count(array_diff($from_terms, $to_terms)) == 0;
1581     }
1582     // XXX: better compatibility check needed here!
1583     // Should at least normalise URIs
1584     return ($from == $to);
1585 }
1586
1587 /**
1588  * returns a quoted table name, if required according to config
1589  */
1590 function common_database_tablename($tablename)
1591 {
1592
1593   if(common_config('db','quote_identifiers')) {
1594       $tablename = '"'. $tablename .'"';
1595   }
1596   //table prefixes could be added here later
1597   return $tablename;
1598 }
1599
1600 /**
1601  * Shorten a URL with the current user's configured shortening service,
1602  * or ur1.ca if configured, or not at all if no shortening is set up.
1603  * Length is not considered.
1604  *
1605  * @param string $long_url
1606  * @return string may return the original URL if shortening failed
1607  *
1608  * @fixme provide a way to specify a particular shortener
1609  * @fixme provide a way to specify to use a given user's shortening preferences
1610  */
1611 function common_shorten_url($long_url)
1612 {
1613     $long_url = trim($long_url);
1614     $user = common_current_user();
1615     if (empty($user)) {
1616         // common current user does not find a user when called from the XMPP daemon
1617         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1618         $shortenerName = 'ur1.ca';
1619     } else {
1620         $shortenerName = $user->urlshorteningservice;
1621     }
1622
1623     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1624         //URL wasn't shortened, so return the long url
1625         return $long_url;
1626     }else{
1627         //URL was shortened, so return the result
1628         return trim($shortenedUrl);
1629     }
1630 }
1631
1632 /**
1633  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1634  *               null if not a web request
1635  *
1636  * @fixme X-Forwarded-For can be chained by multiple proxies;
1637           we should parse the list and provide a cleaner array
1638  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1639  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1640  *        use function to get exact request headers from Apache if possible.
1641  */
1642 function common_client_ip()
1643 {
1644     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1645         return null;
1646     }
1647
1648     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1649         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1650             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1651         } else {
1652             $proxy = $_SERVER['REMOTE_ADDR'];
1653         }
1654         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1655     } else {
1656         $proxy = null;
1657         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1658             $ip = $_SERVER['HTTP_CLIENT_IP'];
1659         } else {
1660             $ip = $_SERVER['REMOTE_ADDR'];
1661         }
1662     }
1663
1664     return array($proxy, $ip);
1665 }
1666
1667 function common_url_to_nickname($url)
1668 {
1669     static $bad = array('query', 'user', 'password', 'port', 'fragment');
1670
1671     $parts = parse_url($url);
1672
1673     # If any of these parts exist, this won't work
1674
1675     foreach ($bad as $badpart) {
1676         if (array_key_exists($badpart, $parts)) {
1677             return null;
1678         }
1679     }
1680
1681     # We just have host and/or path
1682
1683     # If it's just a host...
1684     if (array_key_exists('host', $parts) &&
1685         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1686     {
1687         $hostparts = explode('.', $parts['host']);
1688
1689         # Try to catch common idiom of nickname.service.tld
1690
1691         if ((count($hostparts) > 2) &&
1692             (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1693             (strcmp($hostparts[0], 'www') != 0))
1694         {
1695             return common_nicknamize($hostparts[0]);
1696         } else {
1697             # Do the whole hostname
1698             return common_nicknamize($parts['host']);
1699         }
1700     } else {
1701         if (array_key_exists('path', $parts)) {
1702             # Strip starting, ending slashes
1703             $path = preg_replace('@/$@', '', $parts['path']);
1704             $path = preg_replace('@^/@', '', $path);
1705             $path = basename($path);
1706             if ($path) {
1707                 return common_nicknamize($path);
1708             }
1709         }
1710     }
1711
1712     return null;
1713 }
1714
1715 function common_nicknamize($str)
1716 {
1717     $str = preg_replace('/\W/', '', $str);
1718     return strtolower($str);
1719 }