]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
656374516182ba15d5faacec5a5860b19fad78f1
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, 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     return common_config('site', 'timezone');
76 }
77
78 function common_language()
79 {
80
81     // If there is a user logged in and they've set a language preference
82     // then return that one...
83     if (_have_config() && common_logged_in()) {
84         $user = common_current_user();
85         $user_language = $user->language;
86         if ($user_language)
87           return $user_language;
88     }
89
90     // Otherwise, find the best match for the languages requested by the
91     // user's browser...
92     $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
93     if (!empty($httplang)) {
94         $language = client_prefered_language($httplang);
95         if ($language)
96           return $language;
97     }
98
99     // Finally, if none of the above worked, use the site's default...
100     return common_config('site', 'language');
101 }
102 // salted, hashed passwords are stored in the DB
103
104 function common_munge_password($password, $id)
105 {
106     return md5($password . $id);
107 }
108
109 // check if a username exists and has matching password
110 function common_check_user($nickname, $password)
111 {
112     // NEVER allow blank passwords, even if they match the DB
113     if (mb_strlen($password) == 0) {
114         return false;
115     }
116     $user = User::staticGet('nickname', $nickname);
117     if (is_null($user)) {
118         return false;
119     } else {
120         if (0 == strcmp(common_munge_password($password, $user->id),
121                         $user->password)) {
122             return $user;
123         } else {
124             return false;
125         }
126     }
127 }
128
129 // is the current user logged in?
130 function common_logged_in()
131 {
132     return (!is_null(common_current_user()));
133 }
134
135 function common_have_session()
136 {
137     return (0 != strcmp(session_id(), ''));
138 }
139
140 function common_ensure_session()
141 {
142     $c = null;
143     if (array_key_exists(session_name, $_COOKIE)) {
144         $c = $_COOKIE[session_name()];
145     }
146     if (!common_have_session()) {
147         if (common_config('sessions', 'handle')) {
148             common_log(LOG_INFO, "Using our own session handler");
149             Session::setSaveHandler();
150         }
151         @session_start();
152         if (!isset($_SESSION['started'])) {
153             $_SESSION['started'] = time();
154             if (!empty($c)) {
155                 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
156                            ' is set but started value is null');
157             }
158         }
159     }
160 }
161
162 // Three kinds of arguments:
163 // 1) a user object
164 // 2) a nickname
165 // 3) null to clear
166
167 // Initialize to false; set to null if none found
168
169 $_cur = false;
170
171 function common_set_user($user)
172 {
173
174     global $_cur;
175
176     if (is_null($user) && common_have_session()) {
177         $_cur = null;
178         unset($_SESSION['userid']);
179         return true;
180     } else if (is_string($user)) {
181         $nickname = $user;
182         $user = User::staticGet('nickname', $nickname);
183     } else if (!($user instanceof User)) {
184         return false;
185     }
186
187     if ($user) {
188         common_ensure_session();
189         $_SESSION['userid'] = $user->id;
190         $_cur = $user;
191         return $_cur;
192     }
193     return false;
194 }
195
196 function common_set_cookie($key, $value, $expiration=0)
197 {
198     $path = common_config('site', 'path');
199     $server = common_config('site', 'server');
200
201     if ($path && ($path != '/')) {
202         $cookiepath = '/' . $path . '/';
203     } else {
204         $cookiepath = '/';
205     }
206     return setcookie($key,
207                      $value,
208                      $expiration,
209                      $cookiepath,
210                      $server);
211 }
212
213 define('REMEMBERME', 'rememberme');
214 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
215
216 function common_rememberme($user=null)
217 {
218     if (!$user) {
219         $user = common_current_user();
220         if (!$user) {
221             common_debug('No current user to remember', __FILE__);
222             return false;
223         }
224     }
225
226     $rm = new Remember_me();
227
228     $rm->code = common_good_rand(16);
229     $rm->user_id = $user->id;
230
231     // Wrap the insert in some good ol' fashioned transaction code
232
233     $rm->query('BEGIN');
234
235     $result = $rm->insert();
236
237     if (!$result) {
238         common_log_db_error($rm, 'INSERT', __FILE__);
239         common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
240         return false;
241     }
242
243     $rm->query('COMMIT');
244
245     common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
246
247     $cookieval = $rm->user_id . ':' . $rm->code;
248
249     common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
250
251     common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
252
253     return true;
254 }
255
256 function common_remembered_user()
257 {
258
259     $user = null;
260
261     $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
262
263     if (!$packed) {
264         return null;
265     }
266
267     list($id, $code) = explode(':', $packed);
268
269     if (!$id || !$code) {
270         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
271         common_forgetme();
272         return null;
273     }
274
275     $rm = Remember_me::staticGet($code);
276
277     if (!$rm) {
278         common_log(LOG_WARNING, 'No such remember code: ' . $code);
279         common_forgetme();
280         return null;
281     }
282
283     if ($rm->user_id != $id) {
284         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
285         common_forgetme();
286         return null;
287     }
288
289     $user = User::staticGet($rm->user_id);
290
291     if (!$user) {
292         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
293         common_forgetme();
294         return null;
295     }
296
297     // successful!
298     $result = $rm->delete();
299
300     if (!$result) {
301         common_log_db_error($rm, 'DELETE', __FILE__);
302         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
303         common_forgetme();
304         return null;
305     }
306
307     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
308
309     common_set_user($user);
310     common_real_login(false);
311
312     // We issue a new cookie, so they can log in
313     // automatically again after this session
314
315     common_rememberme($user);
316
317     return $user;
318 }
319
320 // must be called with a valid user!
321
322 function common_forgetme()
323 {
324     common_set_cookie(REMEMBERME, '', 0);
325 }
326
327 // who is the current user?
328 function common_current_user()
329 {
330     global $_cur;
331
332     if (!_have_config()) {
333         return null;
334     }
335
336     if ($_cur === false) {
337
338         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
339             common_ensure_session();
340             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
341             if ($id) {
342                 $_cur = User::staticGet($id);
343                 return $_cur;
344             }
345         }
346
347         // that didn't work; try to remember; will init $_cur to null on failure
348         $_cur = common_remembered_user();
349
350         if ($_cur) {
351             common_debug("Got User " . $_cur->nickname);
352             common_debug("Faking session on remembered user");
353             // XXX: Is this necessary?
354             $_SESSION['userid'] = $_cur->id;
355         }
356     }
357
358     return $_cur;
359 }
360
361 // Logins that are 'remembered' aren't 'real' -- they're subject to
362 // cookie-stealing. So, we don't let them do certain things. New reg,
363 // OpenID, and password logins _are_ real.
364
365 function common_real_login($real=true)
366 {
367     common_ensure_session();
368     $_SESSION['real_login'] = $real;
369 }
370
371 function common_is_real_login()
372 {
373     return common_logged_in() && $_SESSION['real_login'];
374 }
375
376 // get canonical version of nickname for comparison
377 function common_canonical_nickname($nickname)
378 {
379     // XXX: UTF-8 canonicalization (like combining chars)
380     return strtolower($nickname);
381 }
382
383 // get canonical version of email for comparison
384 function common_canonical_email($email)
385 {
386     // XXX: canonicalize UTF-8
387     // XXX: lcase the domain part
388     return $email;
389 }
390
391 function common_render_content($text, $notice)
392 {
393     $r = common_render_text($text);
394     $id = $notice->profile_id;
395     $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
396     $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
397     $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
398     $r = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
399     return $r;
400 }
401
402 function common_render_text($text)
403 {
404     $r = htmlspecialchars($text);
405
406     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
407     $r = common_replace_urls_callback($r, 'common_linkify');
408     $r = preg_replace('/(^|\(|\[|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
409     // XXX: machine tags
410     return $r;
411 }
412
413 function common_replace_urls_callback($text, $callback, $notice_id = null) {
414     // Start off with a regex
415     $regex = '#'.
416     '(?:'.
417         '(?:'.
418             '(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|xmpp|irc)://'.
419             '|'.
420             '(?:mailto|aim|tel):'.
421         ')'.
422         '[^.\s]+\.[^\s]+'.
423         '|'.
424         '(?:[^.\s/:]+\.)+'.
425         '(?:museum|travel|[a-z]{2,4})'.
426         '(?:[:/][^\s]*)?'.
427     ')'.
428     '#ix';
429     preg_match_all($regex, $text, $matches);
430
431     // Then clean up what the regex left behind
432     $offset = 0;
433     foreach($matches[0] as $orig_url) {
434         $url = htmlspecialchars_decode($orig_url);
435
436         // Make sure we didn't pick up an email address
437         if (preg_match('#^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$#i', $url)) continue;
438
439         // Remove surrounding punctuation
440         $url = trim($url, '.?!,;:\'"`([<');
441
442         // Remove surrounding parens and the like
443         preg_match('/[)\]>]+$/', $url, $trailing);
444         if (isset($trailing[0])) {
445             preg_match_all('/[(\[<]/', $url, $opened);
446             preg_match_all('/[)\]>]/', $url, $closed);
447             $unopened = count($closed[0]) - count($opened[0]);
448
449             // Make sure not to take off more closing parens than there are at the end
450             $unopened = ($unopened > mb_strlen($trailing[0])) ? mb_strlen($trailing[0]):$unopened;
451
452             $url = ($unopened > 0) ? mb_substr($url, 0, $unopened * -1):$url;
453         }
454
455         // Remove trailing punctuation again (in case there were some inside parens)
456         $url = rtrim($url, '.?!,;:\'"`');
457
458         // Make sure we didn't capture part of the next sentence
459         preg_match('#((?:[^.\s/]+\.)+)(museum|travel|[a-z]{2,4})#i', $url, $url_parts);
460
461         // Were the parts capitalized any?
462         $last_part = (mb_strtolower($url_parts[2]) !== $url_parts[2]) ? true:false;
463         $prev_part = (mb_strtolower($url_parts[1]) !== $url_parts[1]) ? true:false;
464
465         // If the first part wasn't cap'd but the last part was, we captured too much
466         if ((!$prev_part && $last_part)) {
467             $url = mb_substr($url, 0 , mb_strpos($url, '.'.$url_parts['2'], 0));
468         }
469
470         // Capture the new TLD
471         preg_match('#((?:[^.\s/]+\.)+)(museum|travel|[a-z]{2,4})#i', $url, $url_parts);
472
473         $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');
474
475         if (!in_array($url_parts[2], $tlds)) continue;
476
477         // Make sure we didn't capture a hash tag
478         if (strpos($url, '#') === 0) continue;
479
480         // Put the url back the way we found it.
481         $url = (mb_strpos($orig_url, htmlspecialchars($url)) === FALSE) ? $url:htmlspecialchars($url);
482
483         // Call user specified func
484         if (empty($notice_id)) {
485             $modified_url = call_user_func($callback, $url);
486         } else {
487             $modified_url = call_user_func($callback, array($url, $notice_id));
488         }
489
490         // Replace it!
491         $start = mb_strpos($text, $url, $offset);
492         $text = mb_substr($text, 0, $start).$modified_url.mb_substr($text, $start + mb_strlen($url), mb_strlen($text));
493         $offset = $start + mb_strlen($modified_url);
494     }
495
496     return $text;
497 }
498
499 function common_linkify($url) {
500     // It comes in special'd, so we unspecial it before passing to the stringifying
501     // functions
502     $url = htmlspecialchars_decode($url);
503     $display = File_redirection::_canonUrl($url);
504     $longurl_data = File_redirection::where($url);
505     if (is_array($longurl_data)) {
506         $longurl = $longurl_data['url'];
507     } elseif (is_string($longurl_data)) {
508         $longurl = $longurl_data;
509     } else {
510         die('impossible to linkify');
511     }
512
513     $attrs = array('href' => $longurl, 'rel' => 'external');
514
515     $is_attachment = false;
516     $attachment_id = null;
517     $has_thumb = false;
518
519     // Check to see whether there's a filename associated with this URL.
520     // If there is, it's an upload and qualifies as an attachment
521
522     $localfile = File::staticGet('url', $longurl);
523
524     if (!empty($localfile)) {
525         if (isset($localfile->filename)) {
526             $is_attachment = true;
527             $attachment_id = $localfile->id;
528         }
529     }
530
531 // if this URL is an attachment, then we set class='attachment' and id='attahcment-ID'
532 // where ID is the id of the attachment for the given URL.
533 //
534 // we need a better test telling what can be shown as an attachment
535 // we're currently picking up oembeds only.
536 // I think the best option is another file_view table in the db
537 // and associated dbobject.
538
539     $query = "select file_oembed.file_id as file_id from file join file_oembed on file.id = file_oembed.file_id where file.url='$longurl'";
540     $file = new File;
541     $file->query($query);
542     $file->fetch();
543
544     if (!empty($file->file_id)) {
545         $is_attachment = true;
546         $attachment_id = $file->file_id;
547
548         $query = "select file_thumbnail.file_id as file_id from file join file_thumbnail on file.id = file_thumbnail.file_id where file.url='$longurl'";
549         $file2 = new File;
550         $file2->query($query);
551         $file2->fetch();
552
553         if (!empty($file2)) {
554             $has_thumb = true;
555         }
556     }
557
558     // Add clippy
559     if ($is_attachment) {
560         $attrs['class'] = 'attachment';
561         if ($has_thumb) {
562             $attrs['class'] = 'attachment thumbnail';
563         }
564         $attrs['id'] = "attachment-{$attachment_id}";
565     }
566
567     return XMLStringer::estring('a', $attrs, $display);
568 }
569
570 function common_shorten_links($text)
571 {
572     if (mb_strlen($text) <= 140) return $text;
573     return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
574 }
575
576 function common_xml_safe_str($str)
577 {
578     // Neutralize control codes and surrogates
579         return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
580 }
581
582 function common_tag_link($tag)
583 {
584     $canonical = common_canonical_tag($tag);
585     $url = common_local_url('tag', array('tag' => $canonical));
586     $xs = new XMLStringer();
587     $xs->elementStart('span', 'tag');
588     $xs->element('a', array('href' => $url,
589                             'rel' => 'tag'),
590                  $tag);
591     $xs->elementEnd('span');
592     return $xs->getString();
593 }
594
595 function common_canonical_tag($tag)
596 {
597     return strtolower(str_replace(array('-', '_', '.'), '', $tag));
598 }
599
600 function common_valid_profile_tag($str)
601 {
602     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
603 }
604
605 function common_at_link($sender_id, $nickname)
606 {
607     $sender = Profile::staticGet($sender_id);
608     $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
609     if ($recipient) {
610         $user = User::staticGet('id', $recipient->id);
611         if ($user) {
612             $url = common_local_url('userbyid', array('id' => $user->id));
613         } else {
614             $url = $recipient->profileurl;
615         }
616         $xs = new XMLStringer(false);
617         $attrs = array('href' => $url,
618                        'class' => 'url');
619         if (!empty($recipient->fullname)) {
620             $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
621         }
622         $xs->elementStart('span', 'vcard');
623         $xs->elementStart('a', $attrs);
624         $xs->element('span', 'fn nickname', $nickname);
625         $xs->elementEnd('a');
626         $xs->elementEnd('span');
627         return $xs->getString();
628     } else {
629         return $nickname;
630     }
631 }
632
633 function common_group_link($sender_id, $nickname)
634 {
635     $sender = Profile::staticGet($sender_id);
636     $group = User_group::getForNickname($nickname);
637     if ($group && $sender->isMember($group)) {
638         $attrs = array('href' => $group->permalink(),
639                        'class' => 'url');
640         if (!empty($group->fullname)) {
641             $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
642         }
643         $xs = new XMLStringer();
644         $xs->elementStart('span', 'vcard');
645         $xs->elementStart('a', $attrs);
646         $xs->element('span', 'fn nickname', $nickname);
647         $xs->elementEnd('a');
648         $xs->elementEnd('span');
649         return $xs->getString();
650     } else {
651         return $nickname;
652     }
653 }
654
655 function common_at_hash_link($sender_id, $tag)
656 {
657     $user = User::staticGet($sender_id);
658     if (!$user) {
659         return $tag;
660     }
661     $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
662     if ($tagged) {
663         $url = common_local_url('subscriptions',
664                                 array('nickname' => $user->nickname,
665                                       'tag' => $tag));
666         $xs = new XMLStringer();
667         $xs->elementStart('span', 'tag');
668         $xs->element('a', array('href' => $url,
669                                 'rel' => $tag),
670                      $tag);
671         $xs->elementEnd('span');
672         return $xs->getString();
673     } else {
674         return $tag;
675     }
676 }
677
678 function common_relative_profile($sender, $nickname, $dt=null)
679 {
680     // Try to find profiles this profile is subscribed to that have this nickname
681     $recipient = new Profile();
682     // XXX: use a join instead of a subquery
683     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
684     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
685     if ($recipient->find(true)) {
686         // XXX: should probably differentiate between profiles with
687         // the same name by date of most recent update
688         return $recipient;
689     }
690     // Try to find profiles that listen to this profile and that have this nickname
691     $recipient = new Profile();
692     // XXX: use a join instead of a subquery
693     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
694     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
695     if ($recipient->find(true)) {
696         // XXX: should probably differentiate between profiles with
697         // the same name by date of most recent update
698         return $recipient;
699     }
700     // If this is a local user, try to find a local user with that nickname.
701     $sender = User::staticGet($sender->id);
702     if ($sender) {
703         $recipient_user = User::staticGet('nickname', $nickname);
704         if ($recipient_user) {
705             return $recipient_user->getProfile();
706         }
707     }
708     // Otherwise, no links. @messages from local users to remote users,
709     // or from remote users to other remote users, are just
710     // outside our ability to make intelligent guesses about
711     return null;
712 }
713
714 function common_local_url($action, $args=null, $params=null, $fragment=null)
715 {
716     static $sensitive = array('login', 'register', 'passwordsettings',
717                               'twittersettings', 'finishopenidlogin',
718                               'finishaddopenid', 'api');
719
720     $r = Router::get();
721     $path = $r->build($action, $args, $params, $fragment);
722
723     $ssl = in_array($action, $sensitive);
724
725     if (common_config('site','fancy')) {
726         $url = common_path(mb_substr($path, 1), $ssl);
727     } else {
728         if (mb_strpos($path, '/index.php') === 0) {
729             $url = common_path(mb_substr($path, 1), $ssl);
730         } else {
731             $url = common_path('index.php'.$path, $ssl);
732         }
733     }
734     return $url;
735 }
736
737 function common_path($relative, $ssl=false)
738 {
739     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
740
741     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
742         || common_config('site', 'ssl') === 'always') {
743         $proto = 'https';
744         if (is_string(common_config('site', 'sslserver')) &&
745             mb_strlen(common_config('site', 'sslserver')) > 0) {
746             $serverpart = common_config('site', 'sslserver');
747         } else {
748             $serverpart = common_config('site', 'server');
749         }
750     } else {
751         $proto = 'http';
752         $serverpart = common_config('site', 'server');
753     }
754
755     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
756 }
757
758 function common_date_string($dt)
759 {
760     // XXX: do some sexy date formatting
761     // return date(DATE_RFC822, $dt);
762     $t = strtotime($dt);
763     $now = time();
764     $diff = $now - $t;
765
766     if ($now < $t) { // that shouldn't happen!
767         return common_exact_date($dt);
768     } else if ($diff < 60) {
769         return _('a few seconds ago');
770     } else if ($diff < 92) {
771         return _('about a minute ago');
772     } else if ($diff < 3300) {
773         return sprintf(_('about %d minutes ago'), round($diff/60));
774     } else if ($diff < 5400) {
775         return _('about an hour ago');
776     } else if ($diff < 22 * 3600) {
777         return sprintf(_('about %d hours ago'), round($diff/3600));
778     } else if ($diff < 37 * 3600) {
779         return _('about a day ago');
780     } else if ($diff < 24 * 24 * 3600) {
781         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
782     } else if ($diff < 46 * 24 * 3600) {
783         return _('about a month ago');
784     } else if ($diff < 330 * 24 * 3600) {
785         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
786     } else if ($diff < 480 * 24 * 3600) {
787         return _('about a year ago');
788     } else {
789         return common_exact_date($dt);
790     }
791 }
792
793 function common_exact_date($dt)
794 {
795     static $_utc;
796     static $_siteTz;
797
798     if (!$_utc) {
799         $_utc = new DateTimeZone('UTC');
800         $_siteTz = new DateTimeZone(common_timezone());
801     }
802
803     $dateStr = date('d F Y H:i:s', strtotime($dt));
804     $d = new DateTime($dateStr, $_utc);
805     $d->setTimezone($_siteTz);
806     return $d->format(DATE_RFC850);
807 }
808
809 function common_date_w3dtf($dt)
810 {
811     $dateStr = date('d F Y H:i:s', strtotime($dt));
812     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
813     $d->setTimezone(new DateTimeZone(common_timezone()));
814     return $d->format(DATE_W3C);
815 }
816
817 function common_date_rfc2822($dt)
818 {
819     $dateStr = date('d F Y H:i:s', strtotime($dt));
820     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
821     $d->setTimezone(new DateTimeZone(common_timezone()));
822     return $d->format('r');
823 }
824
825 function common_date_iso8601($dt)
826 {
827     $dateStr = date('d F Y H:i:s', strtotime($dt));
828     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
829     $d->setTimezone(new DateTimeZone(common_timezone()));
830     return $d->format('c');
831 }
832
833 function common_sql_now()
834 {
835     return common_sql_date(time());
836 }
837
838 function common_sql_date($datetime)
839 {
840     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
841 }
842
843 function common_redirect($url, $code=307)
844 {
845     static $status = array(301 => "Moved Permanently",
846                            302 => "Found",
847                            303 => "See Other",
848                            307 => "Temporary Redirect");
849
850     header('HTTP/1.1 '.$code.' '.$status[$code]);
851     header("Location: $url");
852
853     $xo = new XMLOutputter();
854     $xo->startXML('a',
855                   '-//W3C//DTD XHTML 1.0 Strict//EN',
856                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
857     $xo->element('a', array('href' => $url), $url);
858     $xo->endXML();
859     exit;
860 }
861
862 function common_broadcast_notice($notice, $remote=false)
863 {
864     return common_enqueue_notice($notice);
865 }
866
867 // Stick the notice on the queue
868
869 function common_enqueue_notice($notice)
870 {
871     static $localTransports = array('omb',
872                                     'twitter',
873                                     'facebook',
874                                     'ping');
875     static $allTransports = array('sms');
876
877     $transports = $allTransports;
878
879     $xmpp = common_config('xmpp', 'enabled');
880
881     if ($xmpp) {
882         $transports[] = 'jabber';
883     }
884
885     if ($notice->is_local == NOTICE_LOCAL_PUBLIC ||
886         $notice->is_local == NOTICE_LOCAL_NONPUBLIC) {
887         $transports = array_merge($transports, $localTransports);
888         if ($xmpp) {
889             $transports[] = 'public';
890         }
891     }
892
893     $qm = QueueManager::get();
894
895     foreach ($transports as $transport)
896     {
897         $qm->enqueue($notice, $transport);
898     }
899
900     return true;
901 }
902
903 function common_broadcast_profile($profile)
904 {
905     // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
906     require_once(INSTALLDIR.'/lib/omb.php');
907     omb_broadcast_profile($profile);
908     // XXX: Other broadcasts...?
909     return true;
910 }
911
912 function common_profile_url($nickname)
913 {
914     return common_local_url('showstream', array('nickname' => $nickname));
915 }
916
917 // Should make up a reasonable root URL
918
919 function common_root_url($ssl=false)
920 {
921     return common_path('', $ssl);
922 }
923
924 // returns $bytes bytes of random data as a hexadecimal string
925 // "good" here is a goal and not a guarantee
926
927 function common_good_rand($bytes)
928 {
929     // XXX: use random.org...?
930     if (@file_exists('/dev/urandom')) {
931         return common_urandom($bytes);
932     } else { // FIXME: this is probably not good enough
933         return common_mtrand($bytes);
934     }
935 }
936
937 function common_urandom($bytes)
938 {
939     $h = fopen('/dev/urandom', 'rb');
940     // should not block
941     $src = fread($h, $bytes);
942     fclose($h);
943     $enc = '';
944     for ($i = 0; $i < $bytes; $i++) {
945         $enc .= sprintf("%02x", (ord($src[$i])));
946     }
947     return $enc;
948 }
949
950 function common_mtrand($bytes)
951 {
952     $enc = '';
953     for ($i = 0; $i < $bytes; $i++) {
954         $enc .= sprintf("%02x", mt_rand(0, 255));
955     }
956     return $enc;
957 }
958
959 function common_set_returnto($url)
960 {
961     common_ensure_session();
962     $_SESSION['returnto'] = $url;
963 }
964
965 function common_get_returnto()
966 {
967     common_ensure_session();
968     return $_SESSION['returnto'];
969 }
970
971 function common_timestamp()
972 {
973     return date('YmdHis');
974 }
975
976 function common_ensure_syslog()
977 {
978     static $initialized = false;
979     if (!$initialized) {
980         openlog(common_config('syslog', 'appname'), 0, LOG_USER);
981         $initialized = true;
982     }
983 }
984
985 function common_log($priority, $msg, $filename=null)
986 {
987     $logfile = common_config('site', 'logfile');
988     if ($logfile) {
989         $log = fopen($logfile, "a");
990         if ($log) {
991             static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
992                                               'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
993             $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
994             fwrite($log, $output);
995             fclose($log);
996         }
997     } else {
998         common_ensure_syslog();
999         syslog($priority, $msg);
1000     }
1001 }
1002
1003 function common_debug($msg, $filename=null)
1004 {
1005     if ($filename) {
1006         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1007     } else {
1008         common_log(LOG_DEBUG, $msg);
1009     }
1010 }
1011
1012 function common_log_db_error(&$object, $verb, $filename=null)
1013 {
1014     $objstr = common_log_objstring($object);
1015     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1016     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1017 }
1018
1019 function common_log_objstring(&$object)
1020 {
1021     if (is_null($object)) {
1022         return "null";
1023     }
1024     $arr = $object->toArray();
1025     $fields = array();
1026     foreach ($arr as $k => $v) {
1027         $fields[] = "$k='$v'";
1028     }
1029     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1030     return $objstring;
1031 }
1032
1033 function common_valid_http_url($url)
1034 {
1035     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1036 }
1037
1038 function common_valid_tag($tag)
1039 {
1040     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1041         return (Validate::email($matches[1]) ||
1042                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1043     }
1044     return false;
1045 }
1046
1047 /* Following functions are copied from MediaWiki GlobalFunctions.php
1048  * and written by Evan Prodromou. */
1049
1050 function common_accept_to_prefs($accept, $def = '*/*')
1051 {
1052     // No arg means accept anything (per HTTP spec)
1053     if(!$accept) {
1054         return array($def => 1);
1055     }
1056
1057     $prefs = array();
1058
1059     $parts = explode(',', $accept);
1060
1061     foreach($parts as $part) {
1062         // FIXME: doesn't deal with params like 'text/html; level=1'
1063         @list($value, $qpart) = explode(';', trim($part));
1064         $match = array();
1065         if(!isset($qpart)) {
1066             $prefs[$value] = 1;
1067         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1068             $prefs[$value] = $match[1];
1069         }
1070     }
1071
1072     return $prefs;
1073 }
1074
1075 function common_mime_type_match($type, $avail)
1076 {
1077     if(array_key_exists($type, $avail)) {
1078         return $type;
1079     } else {
1080         $parts = explode('/', $type);
1081         if(array_key_exists($parts[0] . '/*', $avail)) {
1082             return $parts[0] . '/*';
1083         } elseif(array_key_exists('*/*', $avail)) {
1084             return '*/*';
1085         } else {
1086             return null;
1087         }
1088     }
1089 }
1090
1091 function common_negotiate_type($cprefs, $sprefs)
1092 {
1093     $combine = array();
1094
1095     foreach(array_keys($sprefs) as $type) {
1096         $parts = explode('/', $type);
1097         if($parts[1] != '*') {
1098             $ckey = common_mime_type_match($type, $cprefs);
1099             if($ckey) {
1100                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1101             }
1102         }
1103     }
1104
1105     foreach(array_keys($cprefs) as $type) {
1106         $parts = explode('/', $type);
1107         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1108             $skey = common_mime_type_match($type, $sprefs);
1109             if($skey) {
1110                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1111             }
1112         }
1113     }
1114
1115     $bestq = 0;
1116     $besttype = 'text/html';
1117
1118     foreach(array_keys($combine) as $type) {
1119         if($combine[$type] > $bestq) {
1120             $besttype = $type;
1121             $bestq = $combine[$type];
1122         }
1123     }
1124
1125     if ('text/html' === $besttype) {
1126         return "text/html; charset=utf-8";
1127     }
1128     return $besttype;
1129 }
1130
1131 function common_config($main, $sub)
1132 {
1133     global $config;
1134     return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1135 }
1136
1137 function common_copy_args($from)
1138 {
1139     $to = array();
1140     $strip = get_magic_quotes_gpc();
1141     foreach ($from as $k => $v) {
1142         $to[$k] = ($strip) ? stripslashes($v) : $v;
1143     }
1144     return $to;
1145 }
1146
1147 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1148 // This is used before handing a request off to OAuthRequest::from_request.
1149 function common_remove_magic_from_request()
1150 {
1151     if(get_magic_quotes_gpc()) {
1152         $_POST=array_map('stripslashes',$_POST);
1153         $_GET=array_map('stripslashes',$_GET);
1154     }
1155 }
1156
1157 function common_user_uri(&$user)
1158 {
1159     return common_local_url('userbyid', array('id' => $user->id));
1160 }
1161
1162 function common_notice_uri(&$notice)
1163 {
1164     return common_local_url('shownotice',
1165                             array('notice' => $notice->id));
1166 }
1167
1168 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1169
1170 function common_confirmation_code($bits)
1171 {
1172     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1173     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1174     $chars = ceil($bits/5);
1175     $code = '';
1176     for ($i = 0; $i < $chars; $i++) {
1177         // XXX: convert to string and back
1178         $num = hexdec(common_good_rand(1));
1179         // XXX: randomness is too precious to throw away almost
1180         // 40% of the bits we get!
1181         $code .= $codechars[$num%32];
1182     }
1183     return $code;
1184 }
1185
1186 // convert markup to HTML
1187
1188 function common_markup_to_html($c)
1189 {
1190     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1191     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1192     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1193     return Markdown($c);
1194 }
1195
1196 function common_profile_uri($profile)
1197 {
1198     if (!$profile) {
1199         return null;
1200     }
1201     $user = User::staticGet($profile->id);
1202     if ($user) {
1203         return $user->uri;
1204     }
1205
1206     $remote = Remote_profile::staticGet($profile->id);
1207     if ($remote) {
1208         return $remote->uri;
1209     }
1210     // XXX: this is a very bad profile!
1211     return null;
1212 }
1213
1214 function common_canonical_sms($sms)
1215 {
1216     // strip non-digits
1217     preg_replace('/\D/', '', $sms);
1218     return $sms;
1219 }
1220
1221 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1222 {
1223     switch ($errno) {
1224      case E_USER_ERROR:
1225         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1226         exit(1);
1227         break;
1228
1229      case E_USER_WARNING:
1230         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1231         break;
1232
1233      case E_USER_NOTICE:
1234         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1235         break;
1236     }
1237
1238     // FIXME: show error page if we're on the Web
1239     /* Don't execute PHP internal error handler */
1240     return true;
1241 }
1242
1243 function common_session_token()
1244 {
1245     common_ensure_session();
1246     if (!array_key_exists('token', $_SESSION)) {
1247         $_SESSION['token'] = common_good_rand(64);
1248     }
1249     return $_SESSION['token'];
1250 }
1251
1252 function common_cache_key($extra)
1253 {
1254     $base_key = common_config('memcached', 'base');
1255
1256     if (empty($base_key)) {
1257         $base_key = common_keyize(common_config('site', 'name'));
1258     }
1259
1260     return 'laconica:' . $base_key . ':' . $extra;
1261 }
1262
1263 function common_keyize($str)
1264 {
1265     $str = strtolower($str);
1266     $str = preg_replace('/\s/', '_', $str);
1267     return $str;
1268 }
1269
1270 function common_memcache()
1271 {
1272     static $cache = null;
1273     if (!common_config('memcached', 'enabled')) {
1274         return null;
1275     } else {
1276         if (!$cache) {
1277             $cache = new Memcache();
1278             $servers = common_config('memcached', 'server');
1279             if (is_array($servers)) {
1280                 foreach($servers as $server) {
1281                     $cache->addServer($server);
1282                 }
1283             } else {
1284                 $cache->addServer($servers);
1285             }
1286         }
1287         return $cache;
1288     }
1289 }
1290
1291 function common_compatible_license($from, $to)
1292 {
1293     // XXX: better compatibility check needed here!
1294     return ($from == $to);
1295 }
1296
1297 /**
1298  * returns a quoted table name, if required according to config
1299  */
1300 function common_database_tablename($tablename)
1301 {
1302
1303   if(common_config('db','quote_identifiers')) {
1304       $tablename = '"'. $tablename .'"';
1305   }
1306   //table prefixes could be added here later
1307   return $tablename;
1308 }
1309
1310 function common_shorten_url($long_url)
1311 {
1312     $user = common_current_user();
1313     if (empty($user)) {
1314         // common current user does not find a user when called from the XMPP daemon
1315         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1316         $svc = 'ur1.ca';
1317     } else {
1318         $svc = $user->urlshorteningservice;
1319     }
1320
1321     $curlh = curl_init();
1322     curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
1323     curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
1324     curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
1325
1326     switch($svc) {
1327      case 'ur1.ca':
1328         require_once INSTALLDIR.'/lib/Shorturl_api.php';
1329         $short_url_service = new LilUrl;
1330         $short_url = $short_url_service->shorten($long_url);
1331         break;
1332
1333      case '2tu.us':
1334         $short_url_service = new TightUrl;
1335         require_once INSTALLDIR.'/lib/Shorturl_api.php';
1336         $short_url = $short_url_service->shorten($long_url);
1337         break;
1338
1339      case 'ptiturl.com':
1340         require_once INSTALLDIR.'/lib/Shorturl_api.php';
1341         $short_url_service = new PtitUrl;
1342         $short_url = $short_url_service->shorten($long_url);
1343         break;
1344
1345      case 'bit.ly':
1346         curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($long_url));
1347         $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
1348         break;
1349
1350      case 'is.gd':
1351         curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($long_url));
1352         $short_url = curl_exec($curlh);
1353         break;
1354      case 'snipr.com':
1355         curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($long_url));
1356         $short_url = curl_exec($curlh);
1357         break;
1358      case 'metamark.net':
1359         curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($long_url));
1360         $short_url = curl_exec($curlh);
1361         break;
1362      case 'tinyurl.com':
1363         curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($long_url));
1364         $short_url = curl_exec($curlh);
1365         break;
1366      default:
1367         $short_url = false;
1368     }
1369
1370     curl_close($curlh);
1371
1372     return $short_url;
1373 }
1374
1375 function common_client_ip()
1376 {
1377     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1378         return null;
1379     }
1380
1381     if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
1382         if ($_SERVER['HTTP_CLIENT_IP']) {
1383             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1384         } else {
1385             $proxy = $_SERVER['REMOTE_ADDR'];
1386         }
1387         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1388     } else {
1389         if ($_SERVER['HTTP_CLIENT_IP']) {
1390             $ip = $_SERVER['HTTP_CLIENT_IP'];
1391         } else {
1392             $ip = $_SERVER['REMOTE_ADDR'];
1393         }
1394     }
1395
1396     return array($ip, $proxy);
1397 }