]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch 'master' into groups
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, 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     static $status = array(500 => 'Internal Server Error',
27                            501 => 'Not Implemented',
28                            502 => 'Bad Gateway',
29                            503 => 'Service Unavailable',
30                            504 => 'Gateway Timeout',
31                            505 => 'HTTP Version Not Supported');
32
33     if (!array_key_exists($code, $status)) {
34         $code = 500;
35     }
36
37     $status_string = $status[$code];
38
39     header('HTTP/1.1 '.$code.' '.$status_string);
40     header('Content-type: text/plain');
41
42     print $msg;
43     print "\n";
44     exit();
45 }
46
47 // Show a user error
48 function common_user_error($msg, $code=400)
49 {
50     static $status = array(400 => 'Bad Request',
51                            401 => 'Unauthorized',
52                            402 => 'Payment Required',
53                            403 => 'Forbidden',
54                            404 => 'Not Found',
55                            405 => 'Method Not Allowed',
56                            406 => 'Not Acceptable',
57                            407 => 'Proxy Authentication Required',
58                            408 => 'Request Timeout',
59                            409 => 'Conflict',
60                            410 => 'Gone',
61                            411 => 'Length Required',
62                            412 => 'Precondition Failed',
63                            413 => 'Request Entity Too Large',
64                            414 => 'Request-URI Too Long',
65                            415 => 'Unsupported Media Type',
66                            416 => 'Requested Range Not Satisfiable',
67                            417 => 'Expectation Failed');
68
69     if (!array_key_exists($code, $status)) {
70         $code = 400;
71     }
72
73     $status_string = $status[$code];
74
75     header('HTTP/1.1 '.$code.' '.$status_string);
76
77     common_show_header('Error');
78     common_element('div', array('class' => 'error'), $msg);
79     common_show_footer();
80 }
81
82 function common_init_locale($language=null)
83 {
84     if(!$language) {
85         $language = common_language();
86     }
87     putenv('LANGUAGE='.$language);
88     putenv('LANG='.$language);
89     return setlocale(LC_ALL, $language . ".utf8",
90                      $language . ".UTF8",
91                      $language . ".utf-8",
92                      $language . ".UTF-8",
93                      $language);
94 }
95
96 function common_init_language()
97 {
98     mb_internal_encoding('UTF-8');
99     $language = common_language();
100     // So we don't have to make people install the gettext locales
101     $locale_set = common_init_locale($language);
102     bindtextdomain("laconica", common_config('site','locale_path'));
103     bind_textdomain_codeset("laconica", "UTF-8");
104     textdomain("laconica");
105     setlocale(LC_CTYPE, 'C');
106     if(!$locale_set) {
107         common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
108     }
109 }
110
111 function common_timezone()
112 {
113     if (common_logged_in()) {
114         $user = common_current_user();
115         if ($user->timezone) {
116             return $user->timezone;
117         }
118     }
119
120     global $config;
121     return $config['site']['timezone'];
122 }
123
124 function common_language()
125 {
126
127     // If there is a user logged in and they've set a language preference
128     // then return that one...
129     if (common_logged_in()) {
130         $user = common_current_user();
131         $user_language = $user->language;
132         if ($user_language)
133           return $user_language;
134     }
135
136     // Otherwise, find the best match for the languages requested by the
137     // user's browser...
138     $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
139     if (!empty($httplang)) {
140         $language = client_prefered_language($httplang);
141         if ($language)
142           return $language;
143     }
144
145     // Finally, if none of the above worked, use the site's default...
146     return common_config('site', 'language');
147 }
148 // salted, hashed passwords are stored in the DB
149
150 function common_munge_password($password, $id)
151 {
152     return md5($password . $id);
153 }
154
155 // check if a username exists and has matching password
156 function common_check_user($nickname, $password)
157 {
158     // NEVER allow blank passwords, even if they match the DB
159     if (mb_strlen($password) == 0) {
160         return false;
161     }
162     $user = User::staticGet('nickname', $nickname);
163     if (is_null($user)) {
164         return false;
165     } else {
166         if (0 == strcmp(common_munge_password($password, $user->id),
167                         $user->password)) {
168             return $user;
169         } else {
170             return false;
171         }
172     }
173 }
174
175 // is the current user logged in?
176 function common_logged_in()
177 {
178     return (!is_null(common_current_user()));
179 }
180
181 function common_have_session()
182 {
183     return (0 != strcmp(session_id(), ''));
184 }
185
186 function common_ensure_session()
187 {
188     if (!common_have_session()) {
189         @session_start();
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         common_ensure_session();
220         $_SESSION['userid'] = $user->id;
221         $_cur = $user;
222         return $_cur;
223     }
224     return false;
225 }
226
227 function common_set_cookie($key, $value, $expiration=0)
228 {
229     $path = common_config('site', 'path');
230     $server = common_config('site', 'server');
231
232     if ($path && ($path != '/')) {
233         $cookiepath = '/' . $path . '/';
234     } else {
235         $cookiepath = '/';
236     }
237     return setcookie($key,
238                      $value,
239                      $expiration,
240                      $cookiepath,
241                      $server);
242 }
243
244 define('REMEMBERME', 'rememberme');
245 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
246
247 function common_rememberme($user=null)
248 {
249     if (!$user) {
250         $user = common_current_user();
251         if (!$user) {
252             common_debug('No current user to remember', __FILE__);
253             return false;
254         }
255     }
256
257     $rm = new Remember_me();
258
259     $rm->code = common_good_rand(16);
260     $rm->user_id = $user->id;
261
262     // Wrap the insert in some good ol' fashioned transaction code
263
264     $rm->query('BEGIN');
265
266     $result = $rm->insert();
267
268     if (!$result) {
269         common_log_db_error($rm, 'INSERT', __FILE__);
270         common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
271         return false;
272     }
273
274     $rm->query('COMMIT');
275
276     common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
277
278     $cookieval = $rm->user_id . ':' . $rm->code;
279
280     common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
281
282     common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
283
284     return true;
285 }
286
287 function common_remembered_user()
288 {
289
290     $user = null;
291
292     $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
293
294     if (!$packed) {
295         return null;
296     }
297
298     list($id, $code) = explode(':', $packed);
299
300     if (!$id || !$code) {
301         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
302         common_forgetme();
303         return null;
304     }
305
306     $rm = Remember_me::staticGet($code);
307
308     if (!$rm) {
309         common_log(LOG_WARNING, 'No such remember code: ' . $code);
310         common_forgetme();
311         return null;
312     }
313
314     if ($rm->user_id != $id) {
315         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
316         common_forgetme();
317         return null;
318     }
319
320     $user = User::staticGet($rm->user_id);
321
322     if (!$user) {
323         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
324         common_forgetme();
325         return null;
326     }
327
328     // successful!
329     $result = $rm->delete();
330
331     if (!$result) {
332         common_log_db_error($rm, 'DELETE', __FILE__);
333         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
334         common_forgetme();
335         return null;
336     }
337
338     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
339
340     common_set_user($user);
341     common_real_login(false);
342
343     // We issue a new cookie, so they can log in
344     // automatically again after this session
345
346     common_rememberme($user);
347
348     return $user;
349 }
350
351 // must be called with a valid user!
352
353 function common_forgetme()
354 {
355     common_set_cookie(REMEMBERME, '', 0);
356 }
357
358 // who is the current user?
359 function common_current_user()
360 {
361     global $_cur;
362
363     if ($_cur === false) {
364
365         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
366             common_ensure_session();
367             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
368             if ($id) {
369                 $_cur = User::staticGet($id);
370                 return $_cur;
371             }
372         }
373
374         // that didn't work; try to remember; will init $_cur to null on failure
375         $_cur = common_remembered_user();
376
377         if ($_cur) {
378             common_debug("Got User " . $_cur->nickname);
379             common_debug("Faking session on remembered user");
380             // XXX: Is this necessary?
381             $_SESSION['userid'] = $_cur->id;
382         }
383     }
384
385     return $_cur;
386 }
387
388 // Logins that are 'remembered' aren't 'real' -- they're subject to
389 // cookie-stealing. So, we don't let them do certain things. New reg,
390 // OpenID, and password logins _are_ real.
391
392 function common_real_login($real=true)
393 {
394     common_ensure_session();
395     $_SESSION['real_login'] = $real;
396 }
397
398 function common_is_real_login()
399 {
400     return common_logged_in() && $_SESSION['real_login'];
401 }
402
403 // get canonical version of nickname for comparison
404 function common_canonical_nickname($nickname)
405 {
406     // XXX: UTF-8 canonicalization (like combining chars)
407     return strtolower($nickname);
408 }
409
410 // get canonical version of email for comparison
411 function common_canonical_email($email)
412 {
413     // XXX: canonicalize UTF-8
414     // XXX: lcase the domain part
415     return $email;
416 }
417
418 define('URL_REGEX', '^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))');
419
420 function common_render_content($text, $notice)
421 {
422     $r = common_render_text($text);
423     $id = $notice->profile_id;
424     $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
425     $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
426     $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
427     return $r;
428 }
429
430 function common_render_text($text)
431 {
432     $r = htmlspecialchars($text);
433
434     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
435     $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
436     $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
437     // XXX: machine tags
438     return $r;
439 }
440
441 function common_render_uri_thingy($matches)
442 {
443     $uri = $matches[0];
444     $trailer = '';
445
446     // Some heuristics for extracting URIs from surrounding punctuation
447     // Strip from trailing text...
448     if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
449         $uri = $matches[1];
450         $trailer = $matches[2];
451     }
452
453     $pairs = array(
454                    ']' => '[', // technically disallowed in URIs, but used in Java docs
455                    ')' => '(', // far too frequent in Wikipedia and MSDN
456                    );
457     $final = substr($uri, -1, 1);
458     if (isset($pairs[$final])) {
459         $openers = substr_count($uri, $pairs[$final]);
460         $closers = substr_count($uri, $final);
461         if ($closers > $openers) {
462             // Assume the paren was opened outside the URI
463             $uri = substr($uri, 0, -1);
464             $trailer = $final . $trailer;
465         }
466     }
467     if ($longurl = common_longurl($uri)) {
468         $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
469         $title = " title='$longurl'";
470     }
471     else $title = '';
472
473     return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
474 }
475
476 function common_longurl($short_url)
477 {
478     $long_url = common_shorten_link($short_url, true);
479     if ($long_url === $short_url) return false;
480     return $long_url;
481 }
482
483 function common_longurl2($uri)
484 {
485     $uri_e = urlencode($uri);
486     $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
487     if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
488     return stripslashes($longurl['long_url']);
489 }
490
491 function common_shorten_links($text)
492 {
493     if (mb_strlen($text) <= 140) return $text;
494     static $cache = array();
495     if (isset($cache[$text])) return $cache[$text];
496     // \s = not a horizontal whitespace character (since PHP 5.2.4)
497     return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
498 }
499
500 function common_shorten_link($url, $reverse = false)
501 {
502     static $url_cache = array();
503     if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
504
505     $user = common_current_user();
506
507     $curlh = curl_init();
508     curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
509     curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
510     curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
511
512     switch($user->urlshorteningservice) {
513      case 'ur1.ca':
514         $short_url_service = new LilUrl;
515         $short_url = $short_url_service->shorten($url);
516         break;
517
518      case '2tu.us':
519         $short_url_service = new TightUrl;
520         $short_url = $short_url_service->shorten($url);
521         break;
522
523      case 'ptiturl.com':
524         $short_url_service = new PtitUrl;
525         $short_url = $short_url_service->shorten($url);
526         break;
527
528      case 'bit.ly':
529         curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
530         $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
531         break;
532
533      case 'is.gd':
534         curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
535         $short_url = curl_exec($curlh);
536         break;
537      case 'snipr.com':
538         curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
539         $short_url = curl_exec($curlh);
540         break;
541      case 'metamark.net':
542         curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
543         $short_url = curl_exec($curlh);
544         break;
545      case 'tinyurl.com':
546         curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
547         $short_url = curl_exec($curlh);
548         break;
549      default:
550         $short_url = false;
551     }
552
553     curl_close($curlh);
554
555     if ($short_url) {
556         $url_cache[(string)$short_url] = $url;
557         return (string)$short_url;
558     }
559     return $url;
560 }
561
562 function common_xml_safe_str($str)
563 {
564     $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
565
566     // Replace control, formatting, and surrogate characters with '*', ala Twitter
567     return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
568 }
569
570 function common_tag_link($tag)
571 {
572     $canonical = common_canonical_tag($tag);
573     $url = common_local_url('tag', array('tag' => $canonical));
574     return '<span class="tag"><a href="' . htmlspecialchars($url) . '" rel="tag">' . htmlspecialchars($tag) . '</a></span>';
575 }
576
577 function common_canonical_tag($tag)
578 {
579     return strtolower(str_replace(array('-', '_', '.'), '', $tag));
580 }
581
582 function common_valid_profile_tag($str)
583 {
584     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
585 }
586
587 function common_at_link($sender_id, $nickname)
588 {
589     $sender = Profile::staticGet($sender_id);
590     $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
591     if ($recipient) {
592         return '<span class="vcard"><a href="'.htmlspecialchars($recipient->profileurl).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
593     } else {
594         return $nickname;
595     }
596 }
597
598 function common_at_hash_link($sender_id, $tag)
599 {
600     $user = User::staticGet($sender_id);
601     if (!$user) {
602         return $tag;
603     }
604     $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
605     if ($tagged) {
606         $url = common_local_url('subscriptions',
607                                 array('nickname' => $user->nickname,
608                                       'tag' => $tag));
609         return '<span class="tag"><a href="'.htmlspecialchars($url).'" rel="tag">'.$tag.'</a></span>';
610     } else {
611         return $tag;
612     }
613 }
614
615 function common_relative_profile($sender, $nickname, $dt=null)
616 {
617     // Try to find profiles this profile is subscribed to that have this nickname
618     $recipient = new Profile();
619     // XXX: use a join instead of a subquery
620     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
621     $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
622     if ($recipient->find(true)) {
623         // XXX: should probably differentiate between profiles with
624         // the same name by date of most recent update
625         return $recipient;
626     }
627     // Try to find profiles that listen to this profile and that have this nickname
628     $recipient = new Profile();
629     // XXX: use a join instead of a subquery
630     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
631     $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
632     if ($recipient->find(true)) {
633         // XXX: should probably differentiate between profiles with
634         // the same name by date of most recent update
635         return $recipient;
636     }
637     // If this is a local user, try to find a local user with that nickname.
638     $sender = User::staticGet($sender->id);
639     if ($sender) {
640         $recipient_user = User::staticGet('nickname', $nickname);
641         if ($recipient_user) {
642             return $recipient_user->getProfile();
643         }
644     }
645     // Otherwise, no links. @messages from local users to remote users,
646     // or from remote users to other remote users, are just
647     // outside our ability to make intelligent guesses about
648     return null;
649 }
650
651 // where should the avatar go for this user?
652
653 function common_avatar_filename($id, $extension, $size=null, $extra=null)
654 {
655     global $config;
656
657     if ($size) {
658         return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
659     } else {
660         return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
661     }
662 }
663
664 function common_avatar_path($filename)
665 {
666     global $config;
667     return INSTALLDIR . '/avatar/' . $filename;
668 }
669
670 function common_avatar_url($filename)
671 {
672     return common_path('avatar/'.$filename);
673 }
674
675 function common_avatar_display_url($avatar)
676 {
677     $server = common_config('avatar', 'server');
678     if ($server) {
679         return 'http://'.$server.'/'.$avatar->filename;
680     } else {
681         return $avatar->url;
682     }
683 }
684
685 function common_default_avatar($size)
686 {
687     static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
688                               AVATAR_STREAM_SIZE => 'stream',
689                               AVATAR_MINI_SIZE => 'mini');
690     return theme_path('default-avatar-'.$sizenames[$size].'.png');
691 }
692
693 function common_local_url($action, $args=null, $fragment=null)
694 {
695     $url = null;
696     if (common_config('site','fancy')) {
697         $url = common_fancy_url($action, $args);
698     } else {
699         $url = common_simple_url($action, $args);
700     }
701     if (!is_null($fragment)) {
702         $url .= '#'.$fragment;
703     }
704     return $url;
705 }
706
707 function common_fancy_url($action, $args=null)
708 {
709     switch (strtolower($action)) {
710      case 'public':
711         if ($args && isset($args['page'])) {
712             return common_path('?page=' . $args['page']);
713         } else {
714             return common_path('');
715         }
716      case 'featured':
717         if ($args && isset($args['page'])) {
718             return common_path('featured?page=' . $args['page']);
719         } else {
720             return common_path('featured');
721         }
722      case 'favorited':
723         if ($args && isset($args['page'])) {
724             return common_path('favorited?page=' . $args['page']);
725         } else {
726             return common_path('favorited');
727         }
728      case 'publicrss':
729         return common_path('rss');
730      case 'publicatom':
731         return common_path("api/statuses/public_timeline.atom");
732      case 'publicxrds':
733         return common_path('xrds');
734      case 'featuredrss':
735         return common_path('featuredrss');
736      case 'favoritedrss':
737         return common_path('favoritedrss');
738      case 'opensearch':
739         if ($args && $args['type']) {
740             return common_path('opensearch/'.$args['type']);
741         } else {
742             return common_path('opensearch/people');
743         }
744      case 'doc':
745         return common_path('doc/'.$args['title']);
746      case 'block':
747      case 'login':
748      case 'logout':
749      case 'subscribe':
750      case 'unsubscribe':
751      case 'invite':
752         return common_path('main/'.$action);
753      case 'tagother':
754         return common_path('main/tagother?id='.$args['id']);
755      case 'register':
756         if ($args && $args['code']) {
757             return common_path('main/register/'.$args['code']);
758         } else {
759             return common_path('main/register');
760         }
761      case 'remotesubscribe':
762         if ($args && $args['nickname']) {
763             return common_path('main/remote?nickname=' . $args['nickname']);
764         } else {
765             return common_path('main/remote');
766         }
767      case 'nudge':
768         return common_path($args['nickname'].'/nudge');
769      case 'openidlogin':
770         return common_path('main/openid');
771      case 'profilesettings':
772         return common_path('settings/profile');
773      case 'passwordsettings':
774         return common_path('settings/password');
775      case 'emailsettings':
776         return common_path('settings/email');
777      case 'openidsettings':
778         return common_path('settings/openid');
779      case 'smssettings':
780         return common_path('settings/sms');
781      case 'twittersettings':
782         return common_path('settings/twitter');
783      case 'othersettings':
784         return common_path('settings/other');
785      case 'deleteprofile':
786         return common_path('settings/delete');
787      case 'newnotice':
788         if ($args && $args['replyto']) {
789             return common_path('notice/new?replyto='.$args['replyto']);
790         } else {
791             return common_path('notice/new');
792         }
793      case 'shownotice':
794         return common_path('notice/'.$args['notice']);
795      case 'deletenotice':
796         if ($args && $args['notice']) {
797             return common_path('notice/delete/'.$args['notice']);
798         } else {
799             return common_path('notice/delete');
800         }
801      case 'microsummary':
802      case 'xrds':
803      case 'foaf':
804         return common_path($args['nickname'].'/'.$action);
805      case 'all':
806      case 'replies':
807      case 'inbox':
808      case 'outbox':
809         if ($args && isset($args['page'])) {
810             return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
811         } else {
812             return common_path($args['nickname'].'/'.$action);
813         }
814      case 'subscriptions':
815      case 'subscribers':
816         $nickname = $args['nickname'];
817         unset($args['nickname']);
818         if (isset($args['tag'])) {
819             $tag = $args['tag'];
820             unset($args['tag']);
821         }
822         $params = http_build_query($args);
823         if ($params) {
824             return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
825         } else {
826             return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
827         }
828      case 'allrss':
829         return common_path($args['nickname'].'/all/rss');
830      case 'repliesrss':
831         return common_path($args['nickname'].'/replies/rss');
832      case 'userrss':
833         if (isset($args['limit']))
834           return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
835         return common_path($args['nickname'].'/rss');
836      case 'showstream':
837         if ($args && isset($args['page'])) {
838             return common_path($args['nickname'].'?page=' . $args['page']);
839         } else {
840             return common_path($args['nickname']);
841         }
842
843      case 'usertimeline':
844         return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
845      case 'confirmaddress':
846         return common_path('main/confirmaddress/'.$args['code']);
847      case 'userbyid':
848         return common_path('user/'.$args['id']);
849      case 'recoverpassword':
850         $path = 'main/recoverpassword';
851         if ($args['code']) {
852             $path .= '/' . $args['code'];
853         }
854         return common_path($path);
855      case 'imsettings':
856         return common_path('settings/im');
857      case 'avatarsettings':
858         return common_path('settings/avatar');
859      case 'peoplesearch':
860         return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
861      case 'noticesearch':
862         return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
863      case 'noticesearchrss':
864         return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
865      case 'avatarbynickname':
866         return common_path($args['nickname'].'/avatar/'.$args['size']);
867      case 'tag':
868         $path = 'tag/' . $args['tag'];
869         unset($args['tag']);
870         return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
871      case 'publictagcloud':
872         return common_path('tags');
873      case 'peopletag':
874         $path = 'peopletag/' . $args['tag'];
875         unset($args['tag']);
876         return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
877      case 'tags':
878         return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
879      case 'favor':
880         return common_path('main/favor');
881      case 'disfavor':
882         return common_path('main/disfavor');
883      case 'showfavorites':
884         if ($args && isset($args['page'])) {
885             return common_path($args['nickname'].'/favorites?page=' . $args['page']);
886         } else {
887             return common_path($args['nickname'].'/favorites');
888         }
889      case 'favoritesrss':
890         return common_path($args['nickname'].'/favorites/rss');
891      case 'showmessage':
892         return common_path('message/' . $args['message']);
893      case 'newmessage':
894         return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
895      case 'api':
896         // XXX: do fancy URLs for all the API methods
897         switch (strtolower($args['apiaction'])) {
898          case 'statuses':
899             switch (strtolower($args['method'])) {
900              case 'user_timeline.rss':
901                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
902              case 'user_timeline.atom':
903                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
904              case 'user_timeline.json':
905                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
906              case 'user_timeline.xml':
907                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
908              default: return common_simple_url($action, $args);
909             }
910          default: return common_simple_url($action, $args);
911         }
912      case 'sup':
913         if ($args && isset($args['seconds'])) {
914             return common_path('main/sup?seconds='.$args['seconds']);
915         } else {
916             return common_path('main/sup');
917         }
918      case 'newgroup':
919         return common_path('group/new');
920      case 'showgroup':
921         return common_path('group/'.$args['nickname']);
922      case 'editgroup':
923         return common_path('group/'.$args['nickname'].'/edit');
924      case 'joingroup':
925         return common_path('group/'.$args['nickname'].'/join');
926      case 'leavegroup':
927         return common_path('group/'.$args['nickname'].'/leave');
928      case 'groupbyid':
929         return common_path('group/'.$args['id'].'/id');
930      case 'grouprss':
931         return common_path('group/'.$args['nickname'].'/rss');
932      case 'groupmembers':
933         return common_path('group/'.$args['nickname'].'/members');
934      case 'usergroups':
935         return common_path($args['nickname'].'/groups');
936      default:
937         return common_simple_url($action, $args);
938     }
939 }
940
941 function common_simple_url($action, $args=null)
942 {
943     global $config;
944     /* XXX: pretty URLs */
945     $extra = '';
946     if ($args) {
947         foreach ($args as $key => $value) {
948             $extra .= "&${key}=${value}";
949         }
950     }
951     return common_path("index.php?action=${action}${extra}");
952 }
953
954 function common_path($relative)
955 {
956     global $config;
957     $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
958     return "http://".$config['site']['server'].'/'.$pathpart.$relative;
959 }
960
961 function common_date_string($dt)
962 {
963     // XXX: do some sexy date formatting
964     // return date(DATE_RFC822, $dt);
965     $t = strtotime($dt);
966     $now = time();
967     $diff = $now - $t;
968
969     if ($now < $t) { // that shouldn't happen!
970         return common_exact_date($dt);
971     } else if ($diff < 60) {
972         return _('a few seconds ago');
973     } else if ($diff < 92) {
974         return _('about a minute ago');
975     } else if ($diff < 3300) {
976         return sprintf(_('about %d minutes ago'), round($diff/60));
977     } else if ($diff < 5400) {
978         return _('about an hour ago');
979     } else if ($diff < 22 * 3600) {
980         return sprintf(_('about %d hours ago'), round($diff/3600));
981     } else if ($diff < 37 * 3600) {
982         return _('about a day ago');
983     } else if ($diff < 24 * 24 * 3600) {
984         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
985     } else if ($diff < 46 * 24 * 3600) {
986         return _('about a month ago');
987     } else if ($diff < 330 * 24 * 3600) {
988         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
989     } else if ($diff < 480 * 24 * 3600) {
990         return _('about a year ago');
991     } else {
992         return common_exact_date($dt);
993     }
994 }
995
996 function common_exact_date($dt)
997 {
998     static $_utc;
999     static $_siteTz;
1000
1001     if (!$_utc) {
1002         $_utc = new DateTimeZone('UTC');
1003         $_siteTz = new DateTimeZone(common_timezone());
1004     }
1005
1006     $dateStr = date('d F Y H:i:s', strtotime($dt));
1007     $d = new DateTime($dateStr, $_utc);
1008     $d->setTimezone($_siteTz);
1009     return $d->format(DATE_RFC850);
1010 }
1011
1012 function common_date_w3dtf($dt)
1013 {
1014     $dateStr = date('d F Y H:i:s', strtotime($dt));
1015     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1016     $d->setTimezone(new DateTimeZone(common_timezone()));
1017     return $d->format(DATE_W3C);
1018 }
1019
1020 function common_date_rfc2822($dt)
1021 {
1022     $dateStr = date('d F Y H:i:s', strtotime($dt));
1023     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1024     $d->setTimezone(new DateTimeZone(common_timezone()));
1025     return $d->format('r');
1026 }
1027
1028 function common_date_iso8601($dt)
1029 {
1030     $dateStr = date('d F Y H:i:s', strtotime($dt));
1031     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1032     $d->setTimezone(new DateTimeZone(common_timezone()));
1033     return $d->format('c');
1034 }
1035
1036 function common_sql_now()
1037 {
1038     return strftime('%Y-%m-%d %H:%M:%S', time());
1039 }
1040
1041 function common_redirect($url, $code=307)
1042 {
1043     static $status = array(301 => "Moved Permanently",
1044                            302 => "Found",
1045                            303 => "See Other",
1046                            307 => "Temporary Redirect");
1047
1048     header("Status: ${code} $status[$code]");
1049     header("Location: $url");
1050
1051     $xo = new XMLOutputter();
1052     $xo->startXML('a',
1053                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1054                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1055     $xo->output('a', array('href' => $url), $url);
1056     $xo->endXML();
1057     exit;
1058 }
1059
1060 function common_save_replies($notice)
1061 {
1062     // Alternative reply format
1063     $tname = false;
1064     if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1065         $tname = $match[1];
1066     }
1067     // extract all @messages
1068     $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1069
1070     $names = array();
1071
1072     if ($cnt || $tname) {
1073         // XXX: is there another way to make an array copy?
1074         $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1075     }
1076
1077     $sender = Profile::staticGet($notice->profile_id);
1078
1079     $replied = array();
1080
1081     // store replied only for first @ (what user/notice what the reply directed,
1082     // we assume first @ is it)
1083
1084     for ($i=0; $i<count($names); $i++) {
1085         $nickname = $names[$i];
1086         $recipient = common_relative_profile($sender, $nickname, $notice->created);
1087         if (!$recipient) {
1088             continue;
1089         }
1090         if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self
1091             $reply_for = $recipient;
1092             $recipient_notice = $reply_for->getCurrentNotice();
1093             if ($recipient_notice) {
1094                 $orig = clone($notice);
1095                 $notice->reply_to = $recipient_notice->id;
1096                 $notice->update($orig);
1097             }
1098         }
1099         // Don't save replies from blocked profile to local user
1100         $recipient_user = User::staticGet('id', $recipient->id);
1101         if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1102             continue;
1103         }
1104         $reply = new Reply();
1105         $reply->notice_id = $notice->id;
1106         $reply->profile_id = $recipient->id;
1107         $id = $reply->insert();
1108         if (!$id) {
1109             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1110             common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1111             common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1112             return;
1113         } else {
1114             $replied[$recipient->id] = 1;
1115         }
1116     }
1117
1118     // Hash format replies, too
1119     $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1120     if ($cnt) {
1121         foreach ($match[1] as $tag) {
1122             $tagged = Profile_tag::getTagged($sender->id, $tag);
1123             foreach ($tagged as $t) {
1124                 if (!$replied[$t->id]) {
1125                     // Don't save replies from blocked profile to local user
1126                     $t_user = User::staticGet('id', $t->id);
1127                     if ($t_user && $t_user->hasBlocked($sender)) {
1128                         continue;
1129                     }
1130                     $reply = new Reply();
1131                     $reply->notice_id = $notice->id;
1132                     $reply->profile_id = $t->id;
1133                     $id = $reply->insert();
1134                     if (!$id) {
1135                         common_log_db_error($reply, 'INSERT', __FILE__);
1136                         return;
1137                     }
1138                 }
1139             }
1140         }
1141     }
1142 }
1143
1144 function common_broadcast_notice($notice, $remote=false)
1145 {
1146
1147     // Check to see if notice should go to Twitter
1148     $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1149     if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1150
1151         // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1152
1153         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1154             (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1155
1156             $result = common_twitter_broadcast($notice, $flink);
1157
1158             if (!$result) {
1159                 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1160             }
1161         }
1162     }
1163
1164     if (common_config('queue', 'enabled')) {
1165         // Do it later!
1166         return common_enqueue_notice($notice);
1167     } else {
1168         return common_real_broadcast($notice, $remote);
1169     }
1170 }
1171
1172 function common_twitter_broadcast($notice, $flink)
1173 {
1174     global $config;
1175     $success = true;
1176     $fuser = $flink->getForeignUser();
1177     $twitter_user = $fuser->nickname;
1178     $twitter_password = $flink->credentials;
1179     $uri = 'http://www.twitter.com/statuses/update.json';
1180
1181     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1182     $statustxt = preg_replace('/^@/', ' @', $notice->content);
1183
1184     $options = array(
1185                      CURLOPT_USERPWD         => "$twitter_user:$twitter_password",
1186                      CURLOPT_POST            => true,
1187                      CURLOPT_POSTFIELDS        => array(
1188                                                         'status'    => $statustxt,
1189                                                         'source'    => $config['integration']['source']
1190                                                         ),
1191                      CURLOPT_RETURNTRANSFER    => true,
1192                      CURLOPT_FAILONERROR        => true,
1193                      CURLOPT_HEADER            => false,
1194                      CURLOPT_FOLLOWLOCATION    => true,
1195                      CURLOPT_USERAGENT        => "Laconica",
1196                      CURLOPT_CONNECTTIMEOUT    => 120,  // XXX: Scary!!!! How long should this be?
1197                      CURLOPT_TIMEOUT            => 120,
1198
1199                      # Twitter is strict about accepting invalid "Expect" headers
1200                      CURLOPT_HTTPHEADER => array('Expect:')
1201                      );
1202
1203     $ch = curl_init($uri);
1204     curl_setopt_array($ch, $options);
1205     $data = curl_exec($ch);
1206     $errmsg = curl_error($ch);
1207
1208     if ($errmsg) {
1209         common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1210                      __FILE__);
1211         $success = false;
1212     }
1213
1214     curl_close($ch);
1215
1216     if (!$data) {
1217         common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1218                      __FILE__);
1219         $success = false;
1220     }
1221
1222     // Twitter should return a status
1223     $status = json_decode($data);
1224
1225     if (!$status->id) {
1226         common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1227                      __FILE__);
1228         $success = false;
1229     }
1230
1231     return $success;
1232 }
1233
1234 // Stick the notice on the queue
1235
1236 function common_enqueue_notice($notice)
1237 {
1238     foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1239         $qi = new Queue_item();
1240         $qi->notice_id = $notice->id;
1241         $qi->transport = $transport;
1242         $qi->created = $notice->created;
1243         $result = $qi->insert();
1244         if (!$result) {
1245             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1246             common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1247             return false;
1248         }
1249         common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1250     }
1251     return $result;
1252 }
1253
1254 function common_dequeue_notice($notice)
1255 {
1256     $qi = Queue_item::staticGet($notice->id);
1257     if ($qi) {
1258         $result = $qi->delete();
1259         if (!$result) {
1260             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1261             common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1262             return false;
1263         }
1264         common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1265         return $result;
1266     } else {
1267         return false;
1268     }
1269 }
1270
1271 function common_real_broadcast($notice, $remote=false)
1272 {
1273     $success = true;
1274     if (!$remote) {
1275         // Make sure we have the OMB stuff
1276         require_once(INSTALLDIR.'/lib/omb.php');
1277         $success = omb_broadcast_remote_subscribers($notice);
1278         if (!$success) {
1279             common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1280         }
1281     }
1282     if ($success) {
1283         require_once(INSTALLDIR.'/lib/jabber.php');
1284         $success = jabber_broadcast_notice($notice);
1285         if (!$success) {
1286             common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1287         }
1288     }
1289     if ($success) {
1290         require_once(INSTALLDIR.'/lib/mail.php');
1291         $success = mail_broadcast_notice_sms($notice);
1292         if (!$success) {
1293             common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1294         }
1295     }
1296     if ($success) {
1297         $success = jabber_public_notice($notice);
1298         if (!$success) {
1299             common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1300         }
1301     }
1302     // XXX: broadcast notices to other IM
1303     return $success;
1304 }
1305
1306 function common_broadcast_profile($profile)
1307 {
1308     // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1309     require_once(INSTALLDIR.'/lib/omb.php');
1310     omb_broadcast_profile($profile);
1311     // XXX: Other broadcasts...?
1312     return true;
1313 }
1314
1315 function common_profile_url($nickname)
1316 {
1317     return common_local_url('showstream', array('nickname' => $nickname));
1318 }
1319
1320 // Should make up a reasonable root URL
1321
1322 function common_root_url()
1323 {
1324     return common_path('');
1325 }
1326
1327 // returns $bytes bytes of random data as a hexadecimal string
1328 // "good" here is a goal and not a guarantee
1329
1330 function common_good_rand($bytes)
1331 {
1332     // XXX: use random.org...?
1333     if (file_exists('/dev/urandom')) {
1334         return common_urandom($bytes);
1335     } else { // FIXME: this is probably not good enough
1336         return common_mtrand($bytes);
1337     }
1338 }
1339
1340 function common_urandom($bytes)
1341 {
1342     $h = fopen('/dev/urandom', 'rb');
1343     // should not block
1344     $src = fread($h, $bytes);
1345     fclose($h);
1346     $enc = '';
1347     for ($i = 0; $i < $bytes; $i++) {
1348         $enc .= sprintf("%02x", (ord($src[$i])));
1349     }
1350     return $enc;
1351 }
1352
1353 function common_mtrand($bytes)
1354 {
1355     $enc = '';
1356     for ($i = 0; $i < $bytes; $i++) {
1357         $enc .= sprintf("%02x", mt_rand(0, 255));
1358     }
1359     return $enc;
1360 }
1361
1362 function common_set_returnto($url)
1363 {
1364     common_ensure_session();
1365     $_SESSION['returnto'] = $url;
1366 }
1367
1368 function common_get_returnto()
1369 {
1370     common_ensure_session();
1371     return $_SESSION['returnto'];
1372 }
1373
1374 function common_timestamp()
1375 {
1376     return date('YmdHis');
1377 }
1378
1379 function common_ensure_syslog()
1380 {
1381     static $initialized = false;
1382     if (!$initialized) {
1383         global $config;
1384         openlog($config['syslog']['appname'], 0, LOG_USER);
1385         $initialized = true;
1386     }
1387 }
1388
1389 function common_log($priority, $msg, $filename=null)
1390 {
1391     $logfile = common_config('site', 'logfile');
1392     if ($logfile) {
1393         $log = fopen($logfile, "a");
1394         if ($log) {
1395             static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1396                                               'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1397             $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1398             fwrite($log, $output);
1399             fclose($log);
1400         }
1401     } else {
1402         common_ensure_syslog();
1403         syslog($priority, $msg);
1404     }
1405 }
1406
1407 function common_debug($msg, $filename=null)
1408 {
1409     if ($filename) {
1410         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1411     } else {
1412         common_log(LOG_DEBUG, $msg);
1413     }
1414 }
1415
1416 function common_log_db_error(&$object, $verb, $filename=null)
1417 {
1418     $objstr = common_log_objstring($object);
1419     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1420     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1421 }
1422
1423 function common_log_objstring(&$object)
1424 {
1425     if (is_null($object)) {
1426         return "null";
1427     }
1428     $arr = $object->toArray();
1429     $fields = array();
1430     foreach ($arr as $k => $v) {
1431         $fields[] = "$k='$v'";
1432     }
1433     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1434     return $objstring;
1435 }
1436
1437 function common_valid_http_url($url)
1438 {
1439     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1440 }
1441
1442 function common_valid_tag($tag)
1443 {
1444     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1445         return (Validate::email($matches[1]) ||
1446                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1447     }
1448     return false;
1449 }
1450
1451 /* Following functions are copied from MediaWiki GlobalFunctions.php
1452  * and written by Evan Prodromou. */
1453
1454 function common_accept_to_prefs($accept, $def = '*/*')
1455 {
1456     // No arg means accept anything (per HTTP spec)
1457     if(!$accept) {
1458         return array($def => 1);
1459     }
1460
1461     $prefs = array();
1462
1463     $parts = explode(',', $accept);
1464
1465     foreach($parts as $part) {
1466         // FIXME: doesn't deal with params like 'text/html; level=1'
1467         @list($value, $qpart) = explode(';', $part);
1468         $match = array();
1469         if(!isset($qpart)) {
1470             $prefs[$value] = 1;
1471         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1472             $prefs[$value] = $match[1];
1473         }
1474     }
1475
1476     return $prefs;
1477 }
1478
1479 function common_mime_type_match($type, $avail)
1480 {
1481     if(array_key_exists($type, $avail)) {
1482         return $type;
1483     } else {
1484         $parts = explode('/', $type);
1485         if(array_key_exists($parts[0] . '/*', $avail)) {
1486             return $parts[0] . '/*';
1487         } elseif(array_key_exists('*/*', $avail)) {
1488             return '*/*';
1489         } else {
1490             return null;
1491         }
1492     }
1493 }
1494
1495 function common_negotiate_type($cprefs, $sprefs)
1496 {
1497     $combine = array();
1498
1499     foreach(array_keys($sprefs) as $type) {
1500         $parts = explode('/', $type);
1501         if($parts[1] != '*') {
1502             $ckey = common_mime_type_match($type, $cprefs);
1503             if($ckey) {
1504                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1505             }
1506         }
1507     }
1508
1509     foreach(array_keys($cprefs) as $type) {
1510         $parts = explode('/', $type);
1511         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1512             $skey = common_mime_type_match($type, $sprefs);
1513             if($skey) {
1514                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1515             }
1516         }
1517     }
1518
1519     $bestq = 0;
1520     $besttype = "text/html";
1521
1522     foreach(array_keys($combine) as $type) {
1523         if($combine[$type] > $bestq) {
1524             $besttype = $type;
1525             $bestq = $combine[$type];
1526         }
1527     }
1528
1529     return $besttype;
1530 }
1531
1532 function common_config($main, $sub)
1533 {
1534     global $config;
1535     return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1536 }
1537
1538 function common_copy_args($from)
1539 {
1540     $to = array();
1541     $strip = get_magic_quotes_gpc();
1542     foreach ($from as $k => $v) {
1543         $to[$k] = ($strip) ? stripslashes($v) : $v;
1544     }
1545     return $to;
1546 }
1547
1548 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1549 // This is used before handing a request off to OAuthRequest::from_request.
1550 function common_remove_magic_from_request()
1551 {
1552     if(get_magic_quotes_gpc()) {
1553         $_POST=array_map('stripslashes',$_POST);
1554         $_GET=array_map('stripslashes',$_GET);
1555     }
1556 }
1557
1558 function common_user_uri(&$user)
1559 {
1560     return common_local_url('userbyid', array('id' => $user->id));
1561 }
1562
1563 function common_notice_uri(&$notice)
1564 {
1565     return common_local_url('shownotice',
1566                             array('notice' => $notice->id));
1567 }
1568
1569 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1570
1571 function common_confirmation_code($bits)
1572 {
1573     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1574     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1575     $chars = ceil($bits/5);
1576     $code = '';
1577     for ($i = 0; $i < $chars; $i++) {
1578         // XXX: convert to string and back
1579         $num = hexdec(common_good_rand(1));
1580         // XXX: randomness is too precious to throw away almost
1581         // 40% of the bits we get!
1582         $code .= $codechars[$num%32];
1583     }
1584     return $code;
1585 }
1586
1587 // convert markup to HTML
1588
1589 function common_markup_to_html($c)
1590 {
1591     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1592     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1593     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1594     return Markdown($c);
1595 }
1596
1597 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
1598 {
1599     $avatar = $profile->getAvatar($size);
1600     if ($avatar) {
1601         return common_avatar_display_url($avatar);
1602     } else {
1603         return common_default_avatar($size);
1604     }
1605 }
1606
1607 function common_profile_uri($profile)
1608 {
1609     if (!$profile) {
1610         return null;
1611     }
1612     $user = User::staticGet($profile->id);
1613     if ($user) {
1614         return $user->uri;
1615     }
1616
1617     $remote = Remote_profile::staticGet($profile->id);
1618     if ($remote) {
1619         return $remote->uri;
1620     }
1621     // XXX: this is a very bad profile!
1622     return null;
1623 }
1624
1625 function common_canonical_sms($sms)
1626 {
1627     // strip non-digits
1628     preg_replace('/\D/', '', $sms);
1629     return $sms;
1630 }
1631
1632 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1633 {
1634     switch ($errno) {
1635      case E_USER_ERROR:
1636         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1637         exit(1);
1638         break;
1639
1640      case E_USER_WARNING:
1641         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1642         break;
1643
1644      case E_USER_NOTICE:
1645         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1646         break;
1647     }
1648
1649     // FIXME: show error page if we're on the Web
1650     /* Don't execute PHP internal error handler */
1651     return true;
1652 }
1653
1654 function common_session_token()
1655 {
1656     common_ensure_session();
1657     if (!array_key_exists('token', $_SESSION)) {
1658         $_SESSION['token'] = common_good_rand(64);
1659     }
1660     return $_SESSION['token'];
1661 }
1662
1663 function common_nudge_response()
1664 {
1665     common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
1666 }
1667
1668 function common_cache_key($extra)
1669 {
1670     return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1671 }
1672
1673 function common_keyize($str)
1674 {
1675     $str = strtolower($str);
1676     $str = preg_replace('/\s/', '_', $str);
1677     return $str;
1678 }
1679
1680 function common_memcache()
1681 {
1682     static $cache = null;
1683     if (!common_config('memcached', 'enabled')) {
1684         return null;
1685     } else {
1686         if (!$cache) {
1687             $cache = new Memcache();
1688             $servers = common_config('memcached', 'server');
1689             if (is_array($servers)) {
1690                 foreach($servers as $server) {
1691                     $cache->addServer($server);
1692                 }
1693             } else {
1694                 $cache->addServer($servers);
1695             }
1696         }
1697         return $cache;
1698     }
1699 }
1700
1701 function common_compatible_license($from, $to)
1702 {
1703     // XXX: better compatibility check needed here!
1704     return ($from == $to);
1705 }