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