We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

util.php 41.3 KB
Newer Older
1
<?php
Evan Prodromou's avatar
Evan Prodromou committed
2
/*
3
 * Laconica - a distributed open-source microblogging tool
4
 * Copyright (C) 2008, 2009, Control Yourself, Inc.
Evan Prodromou's avatar
Evan Prodromou committed
5
 *
6 7 8 9
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
Evan Prodromou's avatar
Evan Prodromou committed
10
 *
11 12 13 14
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
Evan Prodromou's avatar
Evan Prodromou committed
15
 *
16 17 18 19
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

20
/* XXX: break up into separate modules (HTTP, user, files) */
21

22
// Show a server error
23

24 25
function common_server_error($msg, $code=500)
{
26 27
    $err = new ServerErrorAction($msg, $code);
    $err->showPage();
28 29
}

30
// Show a user error
31 32
function common_user_error($msg, $code=400)
{
33 34
    $err = new ClientErrorAction($msg, $code);
    $err->showPage();
35 36
}

37 38
function common_init_locale($language=null)
{
39 40 41 42 43 44
    if(!$language) {
        $language = common_language();
    }
    putenv('LANGUAGE='.$language);
    putenv('LANG='.$language);
    return setlocale(LC_ALL, $language . ".utf8",
45 46 47 48
                     $language . ".UTF8",
                     $language . ".utf-8",
                     $language . ".UTF-8",
                     $language);
49 50
}

51 52
function common_init_language()
{
53 54 55 56 57 58 59 60 61 62 63
    mb_internal_encoding('UTF-8');
    $language = common_language();
    // So we don't have to make people install the gettext locales
    $locale_set = common_init_locale($language);
    bindtextdomain("laconica", common_config('site','locale_path'));
    bind_textdomain_codeset("laconica", "UTF-8");
    textdomain("laconica");
    setlocale(LC_CTYPE, 'C');
    if(!$locale_set) {
        common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
    }
64 65
}

66 67
function common_timezone()
{
68 69 70 71 72 73
    if (common_logged_in()) {
        $user = common_current_user();
        if ($user->timezone) {
            return $user->timezone;
        }
    }
74

75
    return common_config('site', 'timezone');
76 77
}

78 79
function common_language()
{
80

81 82
    // If there is a user logged in and they've set a language preference
    // then return that one...
83
    if (_have_config() && common_logged_in()) {
84 85 86 87 88
        $user = common_current_user();
        $user_language = $user->language;
        if ($user_language)
          return $user_language;
    }
89

90 91 92 93 94 95 96 97
    // Otherwise, find the best match for the languages requested by the
    // user's browser...
    $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
    if (!empty($httplang)) {
        $language = client_prefered_language($httplang);
        if ($language)
          return $language;
    }
98

99 100
    // Finally, if none of the above worked, use the site's default...
    return common_config('site', 'language');
101
}
102
// salted, hashed passwords are stored in the DB
103

104 105
function common_munge_password($password, $id)
{
106
    return md5($password . $id);
107 108
}

109
// check if a username exists and has matching password
110 111
function common_check_user($nickname, $password)
{
112 113 114 115 116
    // NEVER allow blank passwords, even if they match the DB
    if (mb_strlen($password) == 0) {
        return false;
    }
    $user = User::staticGet('nickname', $nickname);
117
    if (is_null($user) || $user === false) {
118 119 120 121 122 123 124 125 126 127 128 129
        return false;
    } else {
        if (0 == strcmp(common_munge_password($password, $user->id),
                        $user->password)) {
            return $user;
        } else {
            return false;
        }
    }
}

// is the current user logged in?
130 131
function common_logged_in()
{
132
    return (!is_null(common_current_user()));
133 134
}

135 136
function common_have_session()
{
137
    return (0 != strcmp(session_id(), ''));
138 139
}

140 141
function common_ensure_session()
{
Evan Prodromou's avatar
Evan Prodromou committed
142 143 144 145
    $c = null;
    if (array_key_exists(session_name, $_COOKIE)) {
        $c = $_COOKIE[session_name()];
    }
146
    if (!common_have_session()) {
147 148 149
        if (common_config('sessions', 'handle')) {
            Session::setSaveHandler();
        }
150
        @session_start();
Evan Prodromou's avatar
Evan Prodromou committed
151 152 153 154 155 156 157
        if (!isset($_SESSION['started'])) {
            $_SESSION['started'] = time();
            if (!empty($c)) {
                common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
                           ' is set but started value is null');
            }
        }
158
    }
159 160
}

161 162 163 164
// Three kinds of arguments:
// 1) a user object
// 2) a nickname
// 3) null to clear
165

166
// Initialize to false; set to null if none found
167 168 169

$_cur = false;

170 171
function common_set_user($user)
{
172 173 174

    global $_cur;

175 176 177 178 179 180 181 182 183 184 185 186 187 188
    if (is_null($user) && common_have_session()) {
        $_cur = null;
        unset($_SESSION['userid']);
        return true;
    } else if (is_string($user)) {
        $nickname = $user;
        $user = User::staticGet('nickname', $nickname);
    } else if (!($user instanceof User)) {
        return false;
    }

    if ($user) {
        common_ensure_session();
        $_SESSION['userid'] = $user->id;
189
        $_cur = $user;
190 191 192
        return $_cur;
    }
    return false;
193 194
}

195 196
function common_set_cookie($key, $value, $expiration=0)
{
197 198
    $path = common_config('site', 'path');
    $server = common_config('site', 'server');
199

200 201 202 203 204 205 206 207 208 209
    if ($path && ($path != '/')) {
        $cookiepath = '/' . $path . '/';
    } else {
        $cookiepath = '/';
    }
    return setcookie($key,
                     $value,
                     $expiration,
                     $cookiepath,
                     $server);
210 211 212
}

define('REMEMBERME', 'rememberme');
213
define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
214

215 216
function common_rememberme($user=null)
{
217 218 219 220 221 222 223
    if (!$user) {
        $user = common_current_user();
        if (!$user) {
            common_debug('No current user to remember', __FILE__);
            return false;
        }
    }
224

225
    $rm = new Remember_me();
226

227 228
    $rm->code = common_good_rand(16);
    $rm->user_id = $user->id;
229

230
    // Wrap the insert in some good ol' fashioned transaction code
231 232 233

    $rm->query('BEGIN');

234
    $result = $rm->insert();
235

236 237 238 239
    if (!$result) {
        common_log_db_error($rm, 'INSERT', __FILE__);
        common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
        return false;
240 241
    }

242 243
    $rm->query('COMMIT');

244
    common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
245 246 247

    $cookieval = $rm->user_id . ':' . $rm->code;

248
    common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
249

250
    common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
251

252
    return true;
253 254
}

255 256
function common_remembered_user()
{
257

258
    $user = null;
259

260
    $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
261

262 263
    if (!$packed) {
        return null;
264 265 266 267 268
    }

    list($id, $code) = explode(':', $packed);

    if (!$id || !$code) {
269
        common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
270
        common_forgetme();
271
        return null;
272 273 274 275 276
    }

    $rm = Remember_me::staticGet($code);

    if (!$rm) {
277
        common_log(LOG_WARNING, 'No such remember code: ' . $code);
278
        common_forgetme();
279
        return null;
280 281 282
    }

    if ($rm->user_id != $id) {
283
        common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
284
        common_forgetme();
285
        return null;
286 287 288 289 290
    }

    $user = User::staticGet($rm->user_id);

    if (!$user) {
291
        common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
292
        common_forgetme();
293
        return null;
294 295
    }

296
    // successful!
297 298 299 300
    $result = $rm->delete();

    if (!$result) {
        common_log_db_error($rm, 'DELETE', __FILE__);
301
        common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
302
        common_forgetme();
303
        return null;
304 305 306 307
    }

    common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);

308
    common_set_user($user);
309 310
    common_real_login(false);

311 312
    // We issue a new cookie, so they can log in
    // automatically again after this session
313 314 315

    common_rememberme($user);

316
    return $user;
317 318
}

319
// must be called with a valid user!
320

321 322
function common_forgetme()
{
323
    common_set_cookie(REMEMBERME, '', 0);
324 325
}

326
// who is the current user?
327 328
function common_current_user()
{
329 330
    global $_cur;

331 332 333 334
    if (!_have_config()) {
        return null;
    }

335 336 337 338 339 340 341 342 343 344 345
    if ($_cur === false) {

        if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
            common_ensure_session();
            $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
            if ($id) {
                $_cur = User::staticGet($id);
                return $_cur;
            }
        }

346
        // that didn't work; try to remember; will init $_cur to null on failure
347 348 349 350 351
        $_cur = common_remembered_user();

        if ($_cur) {
            common_debug("Got User " . $_cur->nickname);
            common_debug("Faking session on remembered user");
352
            // XXX: Is this necessary?
353 354 355 356
            $_SESSION['userid'] = $_cur->id;
        }
    }

357
    return $_cur;
358 359
}

360 361 362
// Logins that are 'remembered' aren't 'real' -- they're subject to
// cookie-stealing. So, we don't let them do certain things. New reg,
// OpenID, and password logins _are_ real.
363

364 365
function common_real_login($real=true)
{
366 367
    common_ensure_session();
    $_SESSION['real_login'] = $real;
368 369
}

370 371
function common_is_real_login()
{
372
    return common_logged_in() && $_SESSION['real_login'];
373 374
}

375
// get canonical version of nickname for comparison
376 377
function common_canonical_nickname($nickname)
{
378 379
    // XXX: UTF-8 canonicalization (like combining chars)
    return strtolower($nickname);
380 381
}

382
// get canonical version of email for comparison
383 384
function common_canonical_email($email)
{
385 386 387
    // XXX: canonicalize UTF-8
    // XXX: lcase the domain part
    return $email;
388 389
}

390 391
function common_render_content($text, $notice)
{
392 393 394 395 396
    $r = common_render_text($text);
    $id = $notice->profile_id;
    $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
    $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
    $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
397
    $r = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
398
    return $r;
399 400
}

401 402
function common_render_text($text)
{
403
    $r = htmlspecialchars($text);
404

405
    $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
406
    $r = common_replace_urls_callback($r, 'common_linkify');
Brenda Wallace's avatar
Brenda Wallace committed
407
    $r = preg_replace('/(^|\(|\[|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
408 409
    // XXX: machine tags
    return $r;
Evan Prodromou's avatar
Evan Prodromou committed
410 411
}

412
function common_replace_urls_callback($text, $callback, $notice_id = null) {
413
    // Start off with a regex
414 415 416 417 418 419 420 421 422 423 424 425 426 427
    $regex = '#'.
    '(?:'.
        '(?:'.
            '(?: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]*)?'.
    ')'.
    '#ix';
428
    preg_match_all($regex, $text, $matches);
429

430 431
    // Then clean up what the regex left behind
    $offset = 0;
432 433
    foreach($matches[0] as $orig_url) {
        $url = htmlspecialchars_decode($orig_url);
434

435 436
        // Make sure we didn't pick up an email address
        if (preg_match('#^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$#i', $url)) continue;
437

438 439
        // Remove surrounding punctuation
        $url = trim($url, '.?!,;:\'"`([<');
440 441 442 443 444 445 446 447 448 449 450 451 452

        // Remove surrounding parens and the like
        preg_match('/[)\]>]+$/', $url, $trailing);
        if (isset($trailing[0])) {
            preg_match_all('/[(\[<]/', $url, $opened);
            preg_match_all('/[)\]>]/', $url, $closed);
            $unopened = count($closed[0]) - count($opened[0]);

            // Make sure not to take off more closing parens than there are at the end
            $unopened = ($unopened > mb_strlen($trailing[0])) ? mb_strlen($trailing[0]):$unopened;

            $url = ($unopened > 0) ? mb_substr($url, 0, $unopened * -1):$url;
        }
453

454 455
        // Remove trailing punctuation again (in case there were some inside parens)
        $url = rtrim($url, '.?!,;:\'"`');
456

457 458
        // Make sure we didn't capture part of the next sentence
        preg_match('#((?:[^.\s/]+\.)+)(museum|travel|[a-z]{2,4})#i', $url, $url_parts);
459

460 461 462
        // Were the parts capitalized any?
        $last_part = (mb_strtolower($url_parts[2]) !== $url_parts[2]) ? true:false;
        $prev_part = (mb_strtolower($url_parts[1]) !== $url_parts[1]) ? true:false;
463

464 465
        // If the first part wasn't cap'd but the last part was, we captured too much
        if ((!$prev_part && $last_part)) {
466
            $url = mb_substr($url, 0 , mb_strpos($url, '.'.$url_parts['2'], 0));
467
        }
468

469 470
        // Capture the new TLD
        preg_match('#((?:[^.\s/]+\.)+)(museum|travel|[a-z]{2,4})#i', $url, $url_parts);
471

472 473 474
        $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');

        if (!in_array($url_parts[2], $tlds)) continue;
475

476 477 478
        // Make sure we didn't capture a hash tag
        if (strpos($url, '#') === 0) continue;

479 480 481
        // Put the url back the way we found it.
        $url = (mb_strpos($orig_url, htmlspecialchars($url)) === FALSE) ? $url:htmlspecialchars($url);

482
        // Call user specified func
483
        if (empty($notice_id)) {
484
            $modified_url = call_user_func($callback, $url);
485 486
        } else {
            $modified_url = call_user_func($callback, array($url, $notice_id));
487
        }
488

489 490
        // Replace it!
        $start = mb_strpos($text, $url, $offset);
491
        $text = mb_substr($text, 0, $start).$modified_url.mb_substr($text, $start + mb_strlen($url), mb_strlen($text));
492
        $offset = $start + mb_strlen($modified_url);
493
    }
494

495 496 497 498
    return $text;
}

function common_linkify($url) {
Evan Prodromou's avatar
Evan Prodromou committed
499 500 501
    // It comes in special'd, so we unspecial it before passing to the stringifying
    // functions
    $url = htmlspecialchars_decode($url);
502 503 504

    $canon = File_redirection::_canonUrl($url);

505 506 507 508 509 510
    $longurl_data = File_redirection::where($url);
    if (is_array($longurl_data)) {
        $longurl = $longurl_data['url'];
    } elseif (is_string($longurl_data)) {
        $longurl = $longurl_data;
    } else {
511
        throw new ServerException("Can't linkify url '$url'");
512
    }
513

514
    $attrs = array('href' => $canon, 'rel' => 'external');
515

516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    $is_attachment = false;
    $attachment_id = null;
    $has_thumb = false;

    // Check to see whether there's a filename associated with this URL.
    // If there is, it's an upload and qualifies as an attachment

    $localfile = File::staticGet('url', $longurl);

    if (!empty($localfile)) {
        if (isset($localfile->filename)) {
            $is_attachment = true;
            $attachment_id = $localfile->id;
        }
    }

532 533 534 535 536 537 538
    // if this URL is an attachment, then we set class='attachment' and id='attahcment-ID'
    // where ID is the id of the attachment for the given URL.
    //
    // we need a better test telling what can be shown as an attachment
    // we're currently picking up oembeds only.
    // I think the best option is another file_view table in the db
    // and associated dbobject.
539

540 541 542 543
    $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'";
    $file = new File;
    $file->query($query);
    $file->fetch();
544

545
    if (!empty($file->file_id)) {
546 547 548
        $is_attachment = true;
        $attachment_id = $file->file_id;

549 550 551 552 553
        $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'";
        $file2 = new File;
        $file2->query($query);
        $file2->fetch();

554 555 556 557 558 559 560 561 562
        if (!empty($file2)) {
            $has_thumb = true;
        }
    }

    // Add clippy
    if ($is_attachment) {
        $attrs['class'] = 'attachment';
        if ($has_thumb) {
563 564
            $attrs['class'] = 'attachment thumbnail';
        }
565
        $attrs['id'] = "attachment-{$attachment_id}";
566
    }
567

568
    return XMLStringer::estring('a', $attrs, $url);
569 570
}

571 572
function common_shorten_links($text)
{
573
    if (mb_strlen($text) <= 140) return $text;
574
    return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
575 576
}

577 578
function common_xml_safe_str($str)
{
579 580
    // Neutralize control codes and surrogates
	return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
581 582
}

583 584
function common_tag_link($tag)
{
585 586
    $canonical = common_canonical_tag($tag);
    $url = common_local_url('tag', array('tag' => $canonical));
587 588 589 590 591
    $xs = new XMLStringer();
    $xs->elementStart('span', 'tag');
    $xs->element('a', array('href' => $url,
                            'rel' => 'tag'),
                 $tag);
592
    $xs->elementEnd('span');
593
    return $xs->getString();
594 595
}

596 597
function common_canonical_tag($tag)
{
598
    return strtolower(str_replace(array('-', '_', '.'), '', $tag));
Mike Cochrane's avatar
Mike Cochrane committed
599 600
}

601 602
function common_valid_profile_tag($str)
{
603
    return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
604 605
}

606 607
function common_at_link($sender_id, $nickname)
{
608 609 610
    $sender = Profile::staticGet($sender_id);
    $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
    if ($recipient) {
611 612 613 614 615 616
        $user = User::staticGet('id', $recipient->id);
        if ($user) {
            $url = common_local_url('userbyid', array('id' => $user->id));
        } else {
            $url = $recipient->profileurl;
        }
617
        $xs = new XMLStringer(false);
618 619 620 621 622
        $attrs = array('href' => $url,
                       'class' => 'url');
        if (!empty($recipient->fullname)) {
            $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
        }
623
        $xs->elementStart('span', 'vcard');
624
        $xs->elementStart('a', $attrs);
625 626 627 628
        $xs->element('span', 'fn nickname', $nickname);
        $xs->elementEnd('a');
        $xs->elementEnd('span');
        return $xs->getString();
629 630 631
    } else {
        return $nickname;
    }
632 633
}

634 635 636
function common_group_link($sender_id, $nickname)
{
    $sender = Profile::staticGet($sender_id);
637
    $group = User_group::getForNickname($nickname);
638
    if ($group && $sender->isMember($group)) {
639 640 641 642 643
        $attrs = array('href' => $group->permalink(),
                       'class' => 'url');
        if (!empty($group->fullname)) {
            $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
        }
644 645
        $xs = new XMLStringer();
        $xs->elementStart('span', 'vcard');
646
        $xs->elementStart('a', $attrs);
647 648 649 650
        $xs->element('span', 'fn nickname', $nickname);
        $xs->elementEnd('a');
        $xs->elementEnd('span');
        return $xs->getString();
651 652 653 654 655
    } else {
        return $nickname;
    }
}

656 657
function common_at_hash_link($sender_id, $tag)
{
658 659 660 661 662 663 664 665 666
    $user = User::staticGet($sender_id);
    if (!$user) {
        return $tag;
    }
    $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
    if ($tagged) {
        $url = common_local_url('subscriptions',
                                array('nickname' => $user->nickname,
                                      'tag' => $tag));
667 668 669 670 671 672 673
        $xs = new XMLStringer();
        $xs->elementStart('span', 'tag');
        $xs->element('a', array('href' => $url,
                                'rel' => $tag),
                     $tag);
        $xs->elementEnd('span');
        return $xs->getString();
674 675 676 677 678
    } else {
        return $tag;
    }
}

679 680
function common_relative_profile($sender, $nickname, $dt=null)
{
681 682 683 684
    // Try to find profiles this profile is subscribed to that have this nickname
    $recipient = new Profile();
    // XXX: use a join instead of a subquery
    $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
685
    $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
Evan Prodromou's avatar
TRUE  
Evan Prodromou committed
686
    if ($recipient->find(true)) {
687 688 689 690 691 692 693 694
        // XXX: should probably differentiate between profiles with
        // the same name by date of most recent update
        return $recipient;
    }
    // Try to find profiles that listen to this profile and that have this nickname
    $recipient = new Profile();
    // XXX: use a join instead of a subquery
    $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
695
    $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
Evan Prodromou's avatar
TRUE  
Evan Prodromou committed
696
    if ($recipient->find(true)) {
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
        // XXX: should probably differentiate between profiles with
        // the same name by date of most recent update
        return $recipient;
    }
    // If this is a local user, try to find a local user with that nickname.
    $sender = User::staticGet($sender->id);
    if ($sender) {
        $recipient_user = User::staticGet('nickname', $nickname);
        if ($recipient_user) {
            return $recipient_user->getProfile();
        }
    }
    // Otherwise, no links. @messages from local users to remote users,
    // or from remote users to other remote users, are just
    // outside our ability to make intelligent guesses about
    return null;
713 714
}

715
function common_local_url($action, $args=null, $params=null, $fragment=null)
716
{
717 718
    static $sensitive = array('login', 'register', 'passwordsettings',
                              'twittersettings', 'finishopenidlogin',
719
                              'finishaddopenid', 'api');
720

Evan Prodromou's avatar
Evan Prodromou committed
721
    $r = Router::get();
722
    $path = $r->build($action, $args, $params, $fragment);
723

724 725
    $ssl = in_array($action, $sensitive);

726
    if (common_config('site','fancy')) {
727
        $url = common_path(mb_substr($path, 1), $ssl);
728
    } else {
729
        if (mb_strpos($path, '/index.php') === 0) {
730
            $url = common_path(mb_substr($path, 1), $ssl);
731
        } else {
732
            $url = common_path('index.php'.$path, $ssl);
733
        }
734 735 736 737
    }
    return $url;
}

738
function common_path($relative, $ssl=false)
739
{
740
    $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756

    if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
        || common_config('site', 'ssl') === 'always') {
        $proto = 'https';
        if (is_string(common_config('site', 'sslserver')) &&
            mb_strlen(common_config('site', 'sslserver')) > 0) {
            $serverpart = common_config('site', 'sslserver');
        } else {
            $serverpart = common_config('site', 'server');
        }
    } else {
        $proto = 'http';
        $serverpart = common_config('site', 'server');
    }

    return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
757 758
}

759 760
function common_date_string($dt)
{
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
    // XXX: do some sexy date formatting
    // return date(DATE_RFC822, $dt);
    $t = strtotime($dt);
    $now = time();
    $diff = $now - $t;

    if ($now < $t) { // that shouldn't happen!
        return common_exact_date($dt);
    } else if ($diff < 60) {
        return _('a few seconds ago');
    } else if ($diff < 92) {
        return _('about a minute ago');
    } else if ($diff < 3300) {
        return sprintf(_('about %d minutes ago'), round($diff/60));
    } else if ($diff < 5400) {
        return _('about an hour ago');
    } else if ($diff < 22 * 3600) {
        return sprintf(_('about %d hours ago'), round($diff/3600));
    } else if ($diff < 37 * 3600) {
        return _('about a day ago');
    } else if ($diff < 24 * 24 * 3600) {
        return sprintf(_('about %d days ago'), round($diff/(24*3600)));
    } else if ($diff < 46 * 24 * 3600) {
        return _('about a month ago');
    } else if ($diff < 330 * 24 * 3600) {
        return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
    } else if ($diff < 480 * 24 * 3600) {
        return _('about a year ago');
    } else {
        return common_exact_date($dt);
    }
Evan Prodromou's avatar
Evan Prodromou committed
792 793
}

794 795
function common_exact_date($dt)
{
Mike Cochrane's avatar
Mike Cochrane committed
796 797 798 799 800 801 802 803
    static $_utc;
    static $_siteTz;

    if (!$_utc) {
        $_utc = new DateTimeZone('UTC');
        $_siteTz = new DateTimeZone(common_timezone());
    }

804 805 806 807
    $dateStr = date('d F Y H:i:s', strtotime($dt));
    $d = new DateTime($dateStr, $_utc);
    $d->setTimezone($_siteTz);
    return $d->format(DATE_RFC850);
808 809
}

810 811
function common_date_w3dtf($dt)
{
812 813 814 815
    $dateStr = date('d F Y H:i:s', strtotime($dt));
    $d = new DateTime($dateStr, new DateTimeZone('UTC'));
    $d->setTimezone(new DateTimeZone(common_timezone()));
    return $d->format(DATE_W3C);
816 817
}

818 819
function common_date_rfc2822($dt)
{
820 821 822 823
    $dateStr = date('d F Y H:i:s', strtotime($dt));
    $d = new DateTime($dateStr, new DateTimeZone('UTC'));
    $d->setTimezone(new DateTimeZone(common_timezone()));
    return $d->format('r');
zach's avatar
zach committed
824 825
}

826 827
function common_date_iso8601($dt)
{
828 829 830 831
    $dateStr = date('d F Y H:i:s', strtotime($dt));
    $d = new DateTime($dateStr, new DateTimeZone('UTC'));
    $d->setTimezone(new DateTimeZone(common_timezone()));
    return $d->format('c');
zach's avatar
zach committed
832 833
}

834 835
function common_sql_now()
{
836 837 838 839 840 841
    return common_sql_date(time());
}

function common_sql_date($datetime)
{
    return strftime('%Y-%m-%d %H:%M:%S', $datetime);
842 843
}

844 845
function common_redirect($url, $code=307)
{
846 847 848 849
    static $status = array(301 => "Moved Permanently",
                           302 => "Found",
                           303 => "See Other",
                           307 => "Temporary Redirect");
Evan Prodromou's avatar
Evan Prodromou committed
850

851
    header('HTTP/1.1 '.$code.' '.$status[$code]);
852 853
    header("Location: $url");

Evan Prodromou's avatar
Evan Prodromou committed
854 855 856 857
    $xo = new XMLOutputter();
    $xo->startXML('a',
                  '-//W3C//DTD XHTML 1.0 Strict//EN',
                  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
858
    $xo->element('a', array('href' => $url), $url);
Evan Prodromou's avatar
Evan Prodromou committed
859
    $xo->endXML();
860
    exit;
861 862
}

863 864
function common_broadcast_notice($notice, $remote=false)
{
865
    return common_enqueue_notice($notice);
866 867
}

868
// Stick the notice on the queue
869

870 871
function common_enqueue_notice($notice)
{
872 873 874 875
    static $localTransports = array('omb',
                                    'twitter',
                                    'facebook',
                                    'ping');
876
    static $allTransports = array('sms');
877

878
    $transports = $allTransports;
879

880 881 882 883 884 885
    $xmpp = common_config('xmpp', 'enabled');

    if ($xmpp) {
        $transports[] = 'jabber';
    }

886 887 888
    if ($notice->is_local == NOTICE_LOCAL_PUBLIC ||
        $notice->is_local == NOTICE_LOCAL_NONPUBLIC) {
        $transports = array_merge($transports, $localTransports);
889 890 891
        if ($xmpp) {
            $transports[] = 'public';
        }
892
    }
893

894
    $qm = QueueManager::get();
895

896 897 898
    foreach ($transports as $transport)
    {
        $qm->enqueue($notice, $transport);
899
    }
900

901
    return true;
902 903
}

904 905
function common_broadcast_profile($profile)
{
906 907 908 909 910
    // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
    require_once(INSTALLDIR.'/lib/omb.php');
    omb_broadcast_profile($profile);
    // XXX: Other broadcasts...?
    return true;
911
}
912

913 914
function common_profile_url($nickname)
{
915
    return common_local_url('showstream', array('nickname' => $nickname));
916 917
}

918
// Should make up a reasonable root URL
919

920
function common_root_url($ssl=false)
921
{
922
    return common_path('', $ssl);
923 924
}

925 926
// returns $bytes bytes of random data as a hexadecimal string
// "good" here is a goal and not a guarantee
Evan Prodromou's avatar
Evan Prodromou committed
927