]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
First pass at delivery of group messages
[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     $r = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/e', "\\1'!'.common_group_link($id, '\\2')", $r);
428     return $r;
429 }
430
431 function common_render_text($text)
432 {
433     $r = htmlspecialchars($text);
434
435     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
436     $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
437     $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
438     // XXX: machine tags
439     return $r;
440 }
441
442 function common_render_uri_thingy($matches)
443 {
444     $uri = $matches[0];
445     $trailer = '';
446
447     // Some heuristics for extracting URIs from surrounding punctuation
448     // Strip from trailing text...
449     if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
450         $uri = $matches[1];
451         $trailer = $matches[2];
452     }
453
454     $pairs = array(
455                    ']' => '[', // technically disallowed in URIs, but used in Java docs
456                    ')' => '(', // far too frequent in Wikipedia and MSDN
457                    );
458     $final = substr($uri, -1, 1);
459     if (isset($pairs[$final])) {
460         $openers = substr_count($uri, $pairs[$final]);
461         $closers = substr_count($uri, $final);
462         if ($closers > $openers) {
463             // Assume the paren was opened outside the URI
464             $uri = substr($uri, 0, -1);
465             $trailer = $final . $trailer;
466         }
467     }
468     if ($longurl = common_longurl($uri)) {
469         $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
470         $title = " title='$longurl'";
471     }
472     else $title = '';
473
474     return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
475 }
476
477 function common_longurl($short_url)
478 {
479     $long_url = common_shorten_link($short_url, true);
480     if ($long_url === $short_url) return false;
481     return $long_url;
482 }
483
484 function common_longurl2($uri)
485 {
486     $uri_e = urlencode($uri);
487     $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
488     if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
489     return stripslashes($longurl['long_url']);
490 }
491
492 function common_shorten_links($text)
493 {
494     if (mb_strlen($text) <= 140) return $text;
495     static $cache = array();
496     if (isset($cache[$text])) return $cache[$text];
497     // \s = not a horizontal whitespace character (since PHP 5.2.4)
498     return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
499 }
500
501 function common_shorten_link($url, $reverse = false)
502 {
503     static $url_cache = array();
504     if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url;
505
506     $user = common_current_user();
507
508     $curlh = curl_init();
509     curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
510     curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
511     curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
512
513     switch($user->urlshorteningservice) {
514      case 'ur1.ca':
515         $short_url_service = new LilUrl;
516         $short_url = $short_url_service->shorten($url);
517         break;
518
519      case '2tu.us':
520         $short_url_service = new TightUrl;
521         $short_url = $short_url_service->shorten($url);
522         break;
523
524      case 'ptiturl.com':
525         $short_url_service = new PtitUrl;
526         $short_url = $short_url_service->shorten($url);
527         break;
528
529      case 'bit.ly':
530         curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url));
531         $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
532         break;
533
534      case 'is.gd':
535         curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url));
536         $short_url = curl_exec($curlh);
537         break;
538      case 'snipr.com':
539         curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url));
540         $short_url = curl_exec($curlh);
541         break;
542      case 'metamark.net':
543         curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url));
544         $short_url = curl_exec($curlh);
545         break;
546      case 'tinyurl.com':
547         curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url));
548         $short_url = curl_exec($curlh);
549         break;
550      default:
551         $short_url = false;
552     }
553
554     curl_close($curlh);
555
556     if ($short_url) {
557         $url_cache[(string)$short_url] = $url;
558         return (string)$short_url;
559     }
560     return $url;
561 }
562
563 function common_xml_safe_str($str)
564 {
565     $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
566
567     // Replace control, formatting, and surrogate characters with '*', ala Twitter
568     return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
569 }
570
571 function common_tag_link($tag)
572 {
573     $canonical = common_canonical_tag($tag);
574     $url = common_local_url('tag', array('tag' => $canonical));
575     return '<span class="tag"><a href="' . htmlspecialchars($url) . '" rel="tag">' . htmlspecialchars($tag) . '</a></span>';
576 }
577
578 function common_canonical_tag($tag)
579 {
580     return strtolower(str_replace(array('-', '_', '.'), '', $tag));
581 }
582
583 function common_valid_profile_tag($str)
584 {
585     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
586 }
587
588 function common_at_link($sender_id, $nickname)
589 {
590     $sender = Profile::staticGet($sender_id);
591     $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
592     if ($recipient) {
593         return '<span class="vcard"><a href="'.htmlspecialchars($recipient->profileurl).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
594     } else {
595         return $nickname;
596     }
597 }
598
599 function common_group_link($sender_id, $nickname)
600 {
601     $sender = Profile::staticGet($sender_id);
602     $group = User_group::staticGet(common_canonical_nickname($nickname));
603     if ($group && $sender->isMember($group)) {
604         return '<span class="vcard"><a href="'.htmlspecialchars($group->permalink()).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
605     } else {
606         return $nickname;
607     }
608 }
609
610 function common_at_hash_link($sender_id, $tag)
611 {
612     $user = User::staticGet($sender_id);
613     if (!$user) {
614         return $tag;
615     }
616     $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
617     if ($tagged) {
618         $url = common_local_url('subscriptions',
619                                 array('nickname' => $user->nickname,
620                                       'tag' => $tag));
621         return '<span class="tag"><a href="'.htmlspecialchars($url).'" rel="tag">'.$tag.'</a></span>';
622     } else {
623         return $tag;
624     }
625 }
626
627 function common_relative_profile($sender, $nickname, $dt=null)
628 {
629     // Try to find profiles this profile is subscribed to that have this nickname
630     $recipient = new Profile();
631     // XXX: use a join instead of a subquery
632     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
633     $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
634     if ($recipient->find(true)) {
635         // XXX: should probably differentiate between profiles with
636         // the same name by date of most recent update
637         return $recipient;
638     }
639     // Try to find profiles that listen to this profile and that have this nickname
640     $recipient = new Profile();
641     // XXX: use a join instead of a subquery
642     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
643     $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
644     if ($recipient->find(true)) {
645         // XXX: should probably differentiate between profiles with
646         // the same name by date of most recent update
647         return $recipient;
648     }
649     // If this is a local user, try to find a local user with that nickname.
650     $sender = User::staticGet($sender->id);
651     if ($sender) {
652         $recipient_user = User::staticGet('nickname', $nickname);
653         if ($recipient_user) {
654             return $recipient_user->getProfile();
655         }
656     }
657     // Otherwise, no links. @messages from local users to remote users,
658     // or from remote users to other remote users, are just
659     // outside our ability to make intelligent guesses about
660     return null;
661 }
662
663 // where should the avatar go for this user?
664
665 function common_avatar_filename($id, $extension, $size=null, $extra=null)
666 {
667     global $config;
668
669     if ($size) {
670         return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
671     } else {
672         return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
673     }
674 }
675
676 function common_avatar_path($filename)
677 {
678     global $config;
679     return INSTALLDIR . '/avatar/' . $filename;
680 }
681
682 function common_avatar_url($filename)
683 {
684     return common_path('avatar/'.$filename);
685 }
686
687 function common_avatar_display_url($avatar)
688 {
689     $server = common_config('avatar', 'server');
690     if ($server) {
691         return 'http://'.$server.'/'.$avatar->filename;
692     } else {
693         return $avatar->url;
694     }
695 }
696
697 function common_default_avatar($size)
698 {
699     static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
700                               AVATAR_STREAM_SIZE => 'stream',
701                               AVATAR_MINI_SIZE => 'mini');
702     return theme_path('default-avatar-'.$sizenames[$size].'.png');
703 }
704
705 function common_local_url($action, $args=null, $fragment=null)
706 {
707     $url = null;
708     if (common_config('site','fancy')) {
709         $url = common_fancy_url($action, $args);
710     } else {
711         $url = common_simple_url($action, $args);
712     }
713     if (!is_null($fragment)) {
714         $url .= '#'.$fragment;
715     }
716     return $url;
717 }
718
719 function common_fancy_url($action, $args=null)
720 {
721     switch (strtolower($action)) {
722      case 'public':
723         if ($args && isset($args['page'])) {
724             return common_path('?page=' . $args['page']);
725         } else {
726             return common_path('');
727         }
728      case 'featured':
729         if ($args && isset($args['page'])) {
730             return common_path('featured?page=' . $args['page']);
731         } else {
732             return common_path('featured');
733         }
734      case 'favorited':
735         if ($args && isset($args['page'])) {
736             return common_path('favorited?page=' . $args['page']);
737         } else {
738             return common_path('favorited');
739         }
740      case 'publicrss':
741         return common_path('rss');
742      case 'publicatom':
743         return common_path("api/statuses/public_timeline.atom");
744      case 'publicxrds':
745         return common_path('xrds');
746      case 'featuredrss':
747         return common_path('featuredrss');
748      case 'favoritedrss':
749         return common_path('favoritedrss');
750      case 'opensearch':
751         if ($args && $args['type']) {
752             return common_path('opensearch/'.$args['type']);
753         } else {
754             return common_path('opensearch/people');
755         }
756      case 'doc':
757         return common_path('doc/'.$args['title']);
758      case 'block':
759      case 'login':
760      case 'logout':
761      case 'subscribe':
762      case 'unsubscribe':
763      case 'invite':
764         return common_path('main/'.$action);
765      case 'tagother':
766         return common_path('main/tagother?id='.$args['id']);
767      case 'register':
768         if ($args && $args['code']) {
769             return common_path('main/register/'.$args['code']);
770         } else {
771             return common_path('main/register');
772         }
773      case 'remotesubscribe':
774         if ($args && $args['nickname']) {
775             return common_path('main/remote?nickname=' . $args['nickname']);
776         } else {
777             return common_path('main/remote');
778         }
779      case 'nudge':
780         return common_path($args['nickname'].'/nudge');
781      case 'openidlogin':
782         return common_path('main/openid');
783      case 'profilesettings':
784         return common_path('settings/profile');
785      case 'passwordsettings':
786         return common_path('settings/password');
787      case 'emailsettings':
788         return common_path('settings/email');
789      case 'openidsettings':
790         return common_path('settings/openid');
791      case 'smssettings':
792         return common_path('settings/sms');
793      case 'twittersettings':
794         return common_path('settings/twitter');
795      case 'othersettings':
796         return common_path('settings/other');
797      case 'deleteprofile':
798         return common_path('settings/delete');
799      case 'newnotice':
800         if ($args && $args['replyto']) {
801             return common_path('notice/new?replyto='.$args['replyto']);
802         } else {
803             return common_path('notice/new');
804         }
805      case 'shownotice':
806         return common_path('notice/'.$args['notice']);
807      case 'deletenotice':
808         if ($args && $args['notice']) {
809             return common_path('notice/delete/'.$args['notice']);
810         } else {
811             return common_path('notice/delete');
812         }
813      case 'microsummary':
814      case 'xrds':
815      case 'foaf':
816         return common_path($args['nickname'].'/'.$action);
817      case 'all':
818      case 'replies':
819      case 'inbox':
820      case 'outbox':
821         if ($args && isset($args['page'])) {
822             return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
823         } else {
824             return common_path($args['nickname'].'/'.$action);
825         }
826      case 'subscriptions':
827      case 'subscribers':
828         $nickname = $args['nickname'];
829         unset($args['nickname']);
830         if (isset($args['tag'])) {
831             $tag = $args['tag'];
832             unset($args['tag']);
833         }
834         $params = http_build_query($args);
835         if ($params) {
836             return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params);
837         } else {
838             return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : ''));
839         }
840      case 'allrss':
841         return common_path($args['nickname'].'/all/rss');
842      case 'repliesrss':
843         return common_path($args['nickname'].'/replies/rss');
844      case 'userrss':
845         if (isset($args['limit']))
846           return common_path($args['nickname'].'/rss?limit=' . $args['limit']);
847         return common_path($args['nickname'].'/rss');
848      case 'showstream':
849         if ($args && isset($args['page'])) {
850             return common_path($args['nickname'].'?page=' . $args['page']);
851         } else {
852             return common_path($args['nickname']);
853         }
854
855      case 'usertimeline':
856         return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
857      case 'confirmaddress':
858         return common_path('main/confirmaddress/'.$args['code']);
859      case 'userbyid':
860         return common_path('user/'.$args['id']);
861      case 'recoverpassword':
862         $path = 'main/recoverpassword';
863         if ($args['code']) {
864             $path .= '/' . $args['code'];
865         }
866         return common_path($path);
867      case 'imsettings':
868         return common_path('settings/im');
869      case 'avatarsettings':
870         return common_path('settings/avatar');
871      case 'peoplesearch':
872         return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
873      case 'noticesearch':
874         return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
875      case 'noticesearchrss':
876         return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
877      case 'avatarbynickname':
878         return common_path($args['nickname'].'/avatar/'.$args['size']);
879      case 'tag':
880         $path = 'tag/' . $args['tag'];
881         unset($args['tag']);
882         return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
883      case 'publictagcloud':
884         return common_path('tags');
885      case 'peopletag':
886         $path = 'peopletag/' . $args['tag'];
887         unset($args['tag']);
888         return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
889      case 'tags':
890         return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
891      case 'favor':
892         return common_path('main/favor');
893      case 'disfavor':
894         return common_path('main/disfavor');
895      case 'showfavorites':
896         if ($args && isset($args['page'])) {
897             return common_path($args['nickname'].'/favorites?page=' . $args['page']);
898         } else {
899             return common_path($args['nickname'].'/favorites');
900         }
901      case 'favoritesrss':
902         return common_path($args['nickname'].'/favorites/rss');
903      case 'showmessage':
904         return common_path('message/' . $args['message']);
905      case 'newmessage':
906         return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
907      case 'api':
908         // XXX: do fancy URLs for all the API methods
909         switch (strtolower($args['apiaction'])) {
910          case 'statuses':
911             switch (strtolower($args['method'])) {
912              case 'user_timeline.rss':
913                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
914              case 'user_timeline.atom':
915                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom');
916              case 'user_timeline.json':
917                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.json');
918              case 'user_timeline.xml':
919                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml');
920              default: return common_simple_url($action, $args);
921             }
922          default: return common_simple_url($action, $args);
923         }
924      case 'sup':
925         if ($args && isset($args['seconds'])) {
926             return common_path('main/sup?seconds='.$args['seconds']);
927         } else {
928             return common_path('main/sup');
929         }
930      case 'newgroup':
931         return common_path('group/new');
932      case 'showgroup':
933         return common_path('group/'.$args['nickname']);
934      case 'editgroup':
935         return common_path('group/'.$args['nickname'].'/edit');
936      case 'joingroup':
937         return common_path('group/'.$args['nickname'].'/join');
938      case 'leavegroup':
939         return common_path('group/'.$args['nickname'].'/leave');
940      case 'groupbyid':
941         return common_path('group/'.$args['id'].'/id');
942      case 'grouprss':
943         return common_path('group/'.$args['nickname'].'/rss');
944      case 'groupmembers':
945         return common_path('group/'.$args['nickname'].'/members');
946      case 'usergroups':
947         return common_path($args['nickname'].'/groups');
948      default:
949         return common_simple_url($action, $args);
950     }
951 }
952
953 function common_simple_url($action, $args=null)
954 {
955     global $config;
956     /* XXX: pretty URLs */
957     $extra = '';
958     if ($args) {
959         foreach ($args as $key => $value) {
960             $extra .= "&${key}=${value}";
961         }
962     }
963     return common_path("index.php?action=${action}${extra}");
964 }
965
966 function common_path($relative)
967 {
968     global $config;
969     $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
970     return "http://".$config['site']['server'].'/'.$pathpart.$relative;
971 }
972
973 function common_date_string($dt)
974 {
975     // XXX: do some sexy date formatting
976     // return date(DATE_RFC822, $dt);
977     $t = strtotime($dt);
978     $now = time();
979     $diff = $now - $t;
980
981     if ($now < $t) { // that shouldn't happen!
982         return common_exact_date($dt);
983     } else if ($diff < 60) {
984         return _('a few seconds ago');
985     } else if ($diff < 92) {
986         return _('about a minute ago');
987     } else if ($diff < 3300) {
988         return sprintf(_('about %d minutes ago'), round($diff/60));
989     } else if ($diff < 5400) {
990         return _('about an hour ago');
991     } else if ($diff < 22 * 3600) {
992         return sprintf(_('about %d hours ago'), round($diff/3600));
993     } else if ($diff < 37 * 3600) {
994         return _('about a day ago');
995     } else if ($diff < 24 * 24 * 3600) {
996         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
997     } else if ($diff < 46 * 24 * 3600) {
998         return _('about a month ago');
999     } else if ($diff < 330 * 24 * 3600) {
1000         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1001     } else if ($diff < 480 * 24 * 3600) {
1002         return _('about a year ago');
1003     } else {
1004         return common_exact_date($dt);
1005     }
1006 }
1007
1008 function common_exact_date($dt)
1009 {
1010     static $_utc;
1011     static $_siteTz;
1012
1013     if (!$_utc) {
1014         $_utc = new DateTimeZone('UTC');
1015         $_siteTz = new DateTimeZone(common_timezone());
1016     }
1017
1018     $dateStr = date('d F Y H:i:s', strtotime($dt));
1019     $d = new DateTime($dateStr, $_utc);
1020     $d->setTimezone($_siteTz);
1021     return $d->format(DATE_RFC850);
1022 }
1023
1024 function common_date_w3dtf($dt)
1025 {
1026     $dateStr = date('d F Y H:i:s', strtotime($dt));
1027     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1028     $d->setTimezone(new DateTimeZone(common_timezone()));
1029     return $d->format(DATE_W3C);
1030 }
1031
1032 function common_date_rfc2822($dt)
1033 {
1034     $dateStr = date('d F Y H:i:s', strtotime($dt));
1035     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1036     $d->setTimezone(new DateTimeZone(common_timezone()));
1037     return $d->format('r');
1038 }
1039
1040 function common_date_iso8601($dt)
1041 {
1042     $dateStr = date('d F Y H:i:s', strtotime($dt));
1043     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1044     $d->setTimezone(new DateTimeZone(common_timezone()));
1045     return $d->format('c');
1046 }
1047
1048 function common_sql_now()
1049 {
1050     return strftime('%Y-%m-%d %H:%M:%S', time());
1051 }
1052
1053 function common_redirect($url, $code=307)
1054 {
1055     static $status = array(301 => "Moved Permanently",
1056                            302 => "Found",
1057                            303 => "See Other",
1058                            307 => "Temporary Redirect");
1059
1060     header("Status: ${code} $status[$code]");
1061     header("Location: $url");
1062
1063     $xo = new XMLOutputter();
1064     $xo->startXML('a',
1065                   '-//W3C//DTD XHTML 1.0 Strict//EN',
1066                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1067     $xo->element('a', array('href' => $url), $url);
1068     $xo->endXML();
1069     exit;
1070 }
1071
1072 function common_save_replies($notice)
1073 {
1074     // Alternative reply format
1075     $tname = false;
1076     if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1077         $tname = $match[1];
1078     }
1079     // extract all @messages
1080     $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1081
1082     $names = array();
1083
1084     if ($cnt || $tname) {
1085         // XXX: is there another way to make an array copy?
1086         $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1087     }
1088
1089     $sender = Profile::staticGet($notice->profile_id);
1090
1091     $replied = array();
1092
1093     // store replied only for first @ (what user/notice what the reply directed,
1094     // we assume first @ is it)
1095
1096     for ($i=0; $i<count($names); $i++) {
1097         $nickname = $names[$i];
1098         $recipient = common_relative_profile($sender, $nickname, $notice->created);
1099         if (!$recipient) {
1100             continue;
1101         }
1102         if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self
1103             $reply_for = $recipient;
1104             $recipient_notice = $reply_for->getCurrentNotice();
1105             if ($recipient_notice) {
1106                 $orig = clone($notice);
1107                 $notice->reply_to = $recipient_notice->id;
1108                 $notice->update($orig);
1109             }
1110         }
1111         // Don't save replies from blocked profile to local user
1112         $recipient_user = User::staticGet('id', $recipient->id);
1113         if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1114             continue;
1115         }
1116         $reply = new Reply();
1117         $reply->notice_id = $notice->id;
1118         $reply->profile_id = $recipient->id;
1119         $id = $reply->insert();
1120         if (!$id) {
1121             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1122             common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1123             common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1124             return;
1125         } else {
1126             $replied[$recipient->id] = 1;
1127         }
1128     }
1129
1130     // Hash format replies, too
1131     $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match);
1132     if ($cnt) {
1133         foreach ($match[1] as $tag) {
1134             $tagged = Profile_tag::getTagged($sender->id, $tag);
1135             foreach ($tagged as $t) {
1136                 if (!$replied[$t->id]) {
1137                     // Don't save replies from blocked profile to local user
1138                     $t_user = User::staticGet('id', $t->id);
1139                     if ($t_user && $t_user->hasBlocked($sender)) {
1140                         continue;
1141                     }
1142                     $reply = new Reply();
1143                     $reply->notice_id = $notice->id;
1144                     $reply->profile_id = $t->id;
1145                     $id = $reply->insert();
1146                     if (!$id) {
1147                         common_log_db_error($reply, 'INSERT', __FILE__);
1148                         return;
1149                     }
1150                 }
1151             }
1152         }
1153     }
1154 }
1155
1156 function common_broadcast_notice($notice, $remote=false)
1157 {
1158
1159     // Check to see if notice should go to Twitter
1160     $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
1161     if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1162
1163         // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1164
1165         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1166             (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1167
1168             $result = common_twitter_broadcast($notice, $flink);
1169
1170             if (!$result) {
1171                 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1172             }
1173         }
1174     }
1175
1176     if (common_config('queue', 'enabled')) {
1177         // Do it later!
1178         return common_enqueue_notice($notice);
1179     } else {
1180         return common_real_broadcast($notice, $remote);
1181     }
1182 }
1183
1184 function common_twitter_broadcast($notice, $flink)
1185 {
1186     global $config;
1187     $success = true;
1188     $fuser = $flink->getForeignUser();
1189     $twitter_user = $fuser->nickname;
1190     $twitter_password = $flink->credentials;
1191     $uri = 'http://www.twitter.com/statuses/update.json';
1192
1193     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1194     $statustxt = preg_replace('/^@/', ' @', $notice->content);
1195
1196     $options = array(
1197                      CURLOPT_USERPWD         => "$twitter_user:$twitter_password",
1198                      CURLOPT_POST            => true,
1199                      CURLOPT_POSTFIELDS        => array(
1200                                                         'status'    => $statustxt,
1201                                                         'source'    => $config['integration']['source']
1202                                                         ),
1203                      CURLOPT_RETURNTRANSFER    => true,
1204                      CURLOPT_FAILONERROR        => true,
1205                      CURLOPT_HEADER            => false,
1206                      CURLOPT_FOLLOWLOCATION    => true,
1207                      CURLOPT_USERAGENT        => "Laconica",
1208                      CURLOPT_CONNECTTIMEOUT    => 120,  // XXX: Scary!!!! How long should this be?
1209                      CURLOPT_TIMEOUT            => 120,
1210
1211                      # Twitter is strict about accepting invalid "Expect" headers
1212                      CURLOPT_HTTPHEADER => array('Expect:')
1213                      );
1214
1215     $ch = curl_init($uri);
1216     curl_setopt_array($ch, $options);
1217     $data = curl_exec($ch);
1218     $errmsg = curl_error($ch);
1219
1220     if ($errmsg) {
1221         common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1222                      __FILE__);
1223         $success = false;
1224     }
1225
1226     curl_close($ch);
1227
1228     if (!$data) {
1229         common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1230                      __FILE__);
1231         $success = false;
1232     }
1233
1234     // Twitter should return a status
1235     $status = json_decode($data);
1236
1237     if (!$status->id) {
1238         common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1239                      __FILE__);
1240         $success = false;
1241     }
1242
1243     return $success;
1244 }
1245
1246 // Stick the notice on the queue
1247
1248 function common_enqueue_notice($notice)
1249 {
1250     foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1251         $qi = new Queue_item();
1252         $qi->notice_id = $notice->id;
1253         $qi->transport = $transport;
1254         $qi->created = $notice->created;
1255         $result = $qi->insert();
1256         if (!$result) {
1257             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1258             common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1259             return false;
1260         }
1261         common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1262     }
1263     return $result;
1264 }
1265
1266 function common_dequeue_notice($notice)
1267 {
1268     $qi = Queue_item::staticGet($notice->id);
1269     if ($qi) {
1270         $result = $qi->delete();
1271         if (!$result) {
1272             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1273             common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1274             return false;
1275         }
1276         common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1277         return $result;
1278     } else {
1279         return false;
1280     }
1281 }
1282
1283 function common_real_broadcast($notice, $remote=false)
1284 {
1285     $success = true;
1286     if (!$remote) {
1287         // Make sure we have the OMB stuff
1288         require_once(INSTALLDIR.'/lib/omb.php');
1289         $success = omb_broadcast_remote_subscribers($notice);
1290         if (!$success) {
1291             common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1292         }
1293     }
1294     if ($success) {
1295         require_once(INSTALLDIR.'/lib/jabber.php');
1296         $success = jabber_broadcast_notice($notice);
1297         if (!$success) {
1298             common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1299         }
1300     }
1301     if ($success) {
1302         require_once(INSTALLDIR.'/lib/mail.php');
1303         $success = mail_broadcast_notice_sms($notice);
1304         if (!$success) {
1305             common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1306         }
1307     }
1308     if ($success) {
1309         $success = jabber_public_notice($notice);
1310         if (!$success) {
1311             common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1312         }
1313     }
1314     // XXX: broadcast notices to other IM
1315     return $success;
1316 }
1317
1318 function common_broadcast_profile($profile)
1319 {
1320     // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1321     require_once(INSTALLDIR.'/lib/omb.php');
1322     omb_broadcast_profile($profile);
1323     // XXX: Other broadcasts...?
1324     return true;
1325 }
1326
1327 function common_profile_url($nickname)
1328 {
1329     return common_local_url('showstream', array('nickname' => $nickname));
1330 }
1331
1332 // Should make up a reasonable root URL
1333
1334 function common_root_url()
1335 {
1336     return common_path('');
1337 }
1338
1339 // returns $bytes bytes of random data as a hexadecimal string
1340 // "good" here is a goal and not a guarantee
1341
1342 function common_good_rand($bytes)
1343 {
1344     // XXX: use random.org...?
1345     if (file_exists('/dev/urandom')) {
1346         return common_urandom($bytes);
1347     } else { // FIXME: this is probably not good enough
1348         return common_mtrand($bytes);
1349     }
1350 }
1351
1352 function common_urandom($bytes)
1353 {
1354     $h = fopen('/dev/urandom', 'rb');
1355     // should not block
1356     $src = fread($h, $bytes);
1357     fclose($h);
1358     $enc = '';
1359     for ($i = 0; $i < $bytes; $i++) {
1360         $enc .= sprintf("%02x", (ord($src[$i])));
1361     }
1362     return $enc;
1363 }
1364
1365 function common_mtrand($bytes)
1366 {
1367     $enc = '';
1368     for ($i = 0; $i < $bytes; $i++) {
1369         $enc .= sprintf("%02x", mt_rand(0, 255));
1370     }
1371     return $enc;
1372 }
1373
1374 function common_set_returnto($url)
1375 {
1376     common_ensure_session();
1377     $_SESSION['returnto'] = $url;
1378 }
1379
1380 function common_get_returnto()
1381 {
1382     common_ensure_session();
1383     return $_SESSION['returnto'];
1384 }
1385
1386 function common_timestamp()
1387 {
1388     return date('YmdHis');
1389 }
1390
1391 function common_ensure_syslog()
1392 {
1393     static $initialized = false;
1394     if (!$initialized) {
1395         global $config;
1396         openlog($config['syslog']['appname'], 0, LOG_USER);
1397         $initialized = true;
1398     }
1399 }
1400
1401 function common_log($priority, $msg, $filename=null)
1402 {
1403     $logfile = common_config('site', 'logfile');
1404     if ($logfile) {
1405         $log = fopen($logfile, "a");
1406         if ($log) {
1407             static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1408                                               'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1409             $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1410             fwrite($log, $output);
1411             fclose($log);
1412         }
1413     } else {
1414         common_ensure_syslog();
1415         syslog($priority, $msg);
1416     }
1417 }
1418
1419 function common_debug($msg, $filename=null)
1420 {
1421     if ($filename) {
1422         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1423     } else {
1424         common_log(LOG_DEBUG, $msg);
1425     }
1426 }
1427
1428 function common_log_db_error(&$object, $verb, $filename=null)
1429 {
1430     $objstr = common_log_objstring($object);
1431     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1432     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1433 }
1434
1435 function common_log_objstring(&$object)
1436 {
1437     if (is_null($object)) {
1438         return "null";
1439     }
1440     $arr = $object->toArray();
1441     $fields = array();
1442     foreach ($arr as $k => $v) {
1443         $fields[] = "$k='$v'";
1444     }
1445     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1446     return $objstring;
1447 }
1448
1449 function common_valid_http_url($url)
1450 {
1451     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1452 }
1453
1454 function common_valid_tag($tag)
1455 {
1456     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1457         return (Validate::email($matches[1]) ||
1458                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1459     }
1460     return false;
1461 }
1462
1463 /* Following functions are copied from MediaWiki GlobalFunctions.php
1464  * and written by Evan Prodromou. */
1465
1466 function common_accept_to_prefs($accept, $def = '*/*')
1467 {
1468     // No arg means accept anything (per HTTP spec)
1469     if(!$accept) {
1470         return array($def => 1);
1471     }
1472
1473     $prefs = array();
1474
1475     $parts = explode(',', $accept);
1476
1477     foreach($parts as $part) {
1478         // FIXME: doesn't deal with params like 'text/html; level=1'
1479         @list($value, $qpart) = explode(';', $part);
1480         $match = array();
1481         if(!isset($qpart)) {
1482             $prefs[$value] = 1;
1483         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1484             $prefs[$value] = $match[1];
1485         }
1486     }
1487
1488     return $prefs;
1489 }
1490
1491 function common_mime_type_match($type, $avail)
1492 {
1493     if(array_key_exists($type, $avail)) {
1494         return $type;
1495     } else {
1496         $parts = explode('/', $type);
1497         if(array_key_exists($parts[0] . '/*', $avail)) {
1498             return $parts[0] . '/*';
1499         } elseif(array_key_exists('*/*', $avail)) {
1500             return '*/*';
1501         } else {
1502             return null;
1503         }
1504     }
1505 }
1506
1507 function common_negotiate_type($cprefs, $sprefs)
1508 {
1509     $combine = array();
1510
1511     foreach(array_keys($sprefs) as $type) {
1512         $parts = explode('/', $type);
1513         if($parts[1] != '*') {
1514             $ckey = common_mime_type_match($type, $cprefs);
1515             if($ckey) {
1516                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1517             }
1518         }
1519     }
1520
1521     foreach(array_keys($cprefs) as $type) {
1522         $parts = explode('/', $type);
1523         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1524             $skey = common_mime_type_match($type, $sprefs);
1525             if($skey) {
1526                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1527             }
1528         }
1529     }
1530
1531     $bestq = 0;
1532     $besttype = "text/html";
1533
1534     foreach(array_keys($combine) as $type) {
1535         if($combine[$type] > $bestq) {
1536             $besttype = $type;
1537             $bestq = $combine[$type];
1538         }
1539     }
1540
1541     return $besttype;
1542 }
1543
1544 function common_config($main, $sub)
1545 {
1546     global $config;
1547     return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1548 }
1549
1550 function common_copy_args($from)
1551 {
1552     $to = array();
1553     $strip = get_magic_quotes_gpc();
1554     foreach ($from as $k => $v) {
1555         $to[$k] = ($strip) ? stripslashes($v) : $v;
1556     }
1557     return $to;
1558 }
1559
1560 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1561 // This is used before handing a request off to OAuthRequest::from_request.
1562 function common_remove_magic_from_request()
1563 {
1564     if(get_magic_quotes_gpc()) {
1565         $_POST=array_map('stripslashes',$_POST);
1566         $_GET=array_map('stripslashes',$_GET);
1567     }
1568 }
1569
1570 function common_user_uri(&$user)
1571 {
1572     return common_local_url('userbyid', array('id' => $user->id));
1573 }
1574
1575 function common_notice_uri(&$notice)
1576 {
1577     return common_local_url('shownotice',
1578                             array('notice' => $notice->id));
1579 }
1580
1581 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1582
1583 function common_confirmation_code($bits)
1584 {
1585     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1586     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1587     $chars = ceil($bits/5);
1588     $code = '';
1589     for ($i = 0; $i < $chars; $i++) {
1590         // XXX: convert to string and back
1591         $num = hexdec(common_good_rand(1));
1592         // XXX: randomness is too precious to throw away almost
1593         // 40% of the bits we get!
1594         $code .= $codechars[$num%32];
1595     }
1596     return $code;
1597 }
1598
1599 // convert markup to HTML
1600
1601 function common_markup_to_html($c)
1602 {
1603     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1604     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1605     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1606     return Markdown($c);
1607 }
1608
1609 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE)
1610 {
1611     $avatar = $profile->getAvatar($size);
1612     if ($avatar) {
1613         return common_avatar_display_url($avatar);
1614     } else {
1615         return common_default_avatar($size);
1616     }
1617 }
1618
1619 function common_profile_uri($profile)
1620 {
1621     if (!$profile) {
1622         return null;
1623     }
1624     $user = User::staticGet($profile->id);
1625     if ($user) {
1626         return $user->uri;
1627     }
1628
1629     $remote = Remote_profile::staticGet($profile->id);
1630     if ($remote) {
1631         return $remote->uri;
1632     }
1633     // XXX: this is a very bad profile!
1634     return null;
1635 }
1636
1637 function common_canonical_sms($sms)
1638 {
1639     // strip non-digits
1640     preg_replace('/\D/', '', $sms);
1641     return $sms;
1642 }
1643
1644 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1645 {
1646     switch ($errno) {
1647      case E_USER_ERROR:
1648         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1649         exit(1);
1650         break;
1651
1652      case E_USER_WARNING:
1653         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1654         break;
1655
1656      case E_USER_NOTICE:
1657         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1658         break;
1659     }
1660
1661     // FIXME: show error page if we're on the Web
1662     /* Don't execute PHP internal error handler */
1663     return true;
1664 }
1665
1666 function common_session_token()
1667 {
1668     common_ensure_session();
1669     if (!array_key_exists('token', $_SESSION)) {
1670         $_SESSION['token'] = common_good_rand(64);
1671     }
1672     return $_SESSION['token'];
1673 }
1674
1675 function common_nudge_response()
1676 {
1677     common_element('p', array('id' => 'nudge_response'), _('Nudge sent!'));
1678 }
1679
1680 function common_cache_key($extra)
1681 {
1682     return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1683 }
1684
1685 function common_keyize($str)
1686 {
1687     $str = strtolower($str);
1688     $str = preg_replace('/\s/', '_', $str);
1689     return $str;
1690 }
1691
1692 function common_memcache()
1693 {
1694     static $cache = null;
1695     if (!common_config('memcached', 'enabled')) {
1696         return null;
1697     } else {
1698         if (!$cache) {
1699             $cache = new Memcache();
1700             $servers = common_config('memcached', 'server');
1701             if (is_array($servers)) {
1702                 foreach($servers as $server) {
1703                     $cache->addServer($server);
1704                 }
1705             } else {
1706                 $cache->addServer($servers);
1707             }
1708         }
1709         return $cache;
1710     }
1711 }
1712
1713 function common_compatible_license($from, $to)
1714 {
1715     // XXX: better compatibility check needed here!
1716     return ($from == $to);
1717 }