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