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

util.php 42.9 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
    $c = null;
143
    if (array_key_exists(session_name(), $_COOKIE)) {
Evan Prodromou's avatar
Evan Prodromou committed
144 145
        $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
    $regex = '#'.
415
    '(?:^|[\s\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
416
    '(?P<url>'.
417 418 419
        '(?:'.
            '(?:'. //Known protocols
                '(?:'.
420
                    '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
421
                    '|'.
422 423 424 425 426 427 428 429 430
                    '(?:(?:mailto|aim|tel|xmpp):)'.
                ')'.
                '(?:[\pN\pL\-\_\+]+(?::[\pN\pL\-\_\+]+)?\@)?'. //user:pass@
                '(?:'.
                    '(?:'.
                        '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
                    ')|(?:'.
                        '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
                    ')'.
431
                ')'.
432 433
            ')'.
            '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'. //IPv4
434
            '|(?:'. //IPv6
435
                '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?'.
436
            ')|(?:'. //DNS
437
                '(?:[\pN\pL\-\_\+]+(?:\:[\pN\pL\-\_\+]+)?\@)?'. //user:pass@
438 439
                '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
                //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
440
                '(?: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|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZW|local|loc|onion)'.
441
            ')(?![\pN\pL\-\_])'.
442
        ')'.
443
        '(?:'.
444
            '(?:\:\d+)?'. //:port
445 446 447
            '(?:/[\pN\pL$\[\]\,\!\(\)\.\-\_\+\/\=\&\;]*)?'. // /path
            '(?:\?[\pN\pL\$\[\]\,\!\(\)\.\-\_\+\/\=\&\;\/]*)?'. // ?query string
            '(?:\#[\pN\pL$\[\]\,\!\(\)\.\-\_\+\/\=\&\;\/\?\#]*)?'. // #fragment
448
        ')(?<![\?\.\,\#\,])'.
449
    ')'.
450
    '#ixu';
451 452
    preg_match_all($regex,$text,$matches);
    //print_r($matches);
453
    return preg_replace_callback($regex, curry(callback_helper,$callback,$notice_id) ,$text);
454 455
}

456
function callback_helper($matches, $callback, $notice_id) {
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    $url=$matches['url'];
    $left = strpos($matches[0],$url);
    $right = $left+strlen($url);
    
    $groupSymbolSets=array(
        array(
            'left'=>'(',
            'right'=>')'
        ),
        array(
            'left'=>'[',
            'right'=>']'
        ),
        array(
            'left'=>'{',
            'right'=>'}'
        )
    );
    $cannotEndWith=array('.','?',',','#');
    $original_url=$url;
    do{
        $original_url=$url;
        foreach($groupSymbolSets as $groupSymbolSet){
            if(substr($url,-1)==$groupSymbolSet['right']){
                $group_left_count = substr_count($url,$groupSymbolSet['left']);
                $group_right_count = substr_count($url,$groupSymbolSet['right']);
                if($group_left_count<$group_right_count){
                    $right-=1;
                    $url=substr($url,0,-1);
                }
            }
        }
        if(in_array(substr($url,-1),$cannotEndWith)){
            $right-=1;
            $url=substr($url,0,-1);
        }
    }while($original_url!=$url);
    
    
496
    
497
    if(empty($notice_id)){
498
        $result = call_user_func_array($callback,$url);
499
    }else{
500
        $result = call_user_func_array($callback, array($url,$notice_id) );
501
    }
502
    return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
503
}
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
function curry($fn) {
    //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
    $args = func_get_args();
    array_shift($args);
    $id = uniqid('_partial');
    $GLOBALS[$id] = array($fn, $args);
    return create_function(
        '',
        '
        $args = func_get_args();
        return call_user_func_array(
        $GLOBALS["'.$id.'"][0],
        array_merge(
            $args,
            $GLOBALS["'.$id.'"][1]));
    ');
521 522 523
}

function common_linkify($url) {
Evan Prodromou's avatar
Evan Prodromou committed
524 525 526
    // It comes in special'd, so we unspecial it before passing to the stringifying
    // functions
    $url = htmlspecialchars_decode($url);
527

528 529 530 531 532
   if(strpos($url, '@')!==false && strpos($url, ':')===false){
       //url is an email address without the mailto: protocol
       return XMLStringer::estring('a', array('href' => "mailto:$url", 'rel' => 'external'), $url);
   }

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

535 536 537 538 539 540
    $longurl_data = File_redirection::where($url);
    if (is_array($longurl_data)) {
        $longurl = $longurl_data['url'];
    } elseif (is_string($longurl_data)) {
        $longurl = $longurl_data;
    } else {
541
        throw new ServerException("Can't linkify url '$url'");
542
    }
543

544
    $attrs = array('href' => $canon, 'rel' => 'external');
545

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
    $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;
        }
    }

562 563 564 565 566 567 568
    // 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.
569

570 571 572 573
    $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();
574

575
    if (!empty($file->file_id)) {
576 577 578
        $is_attachment = true;
        $attachment_id = $file->file_id;

579 580 581 582 583
        $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();

584 585 586 587 588 589 590 591 592
        if (!empty($file2)) {
            $has_thumb = true;
        }
    }

    // Add clippy
    if ($is_attachment) {
        $attrs['class'] = 'attachment';
        if ($has_thumb) {
593 594
            $attrs['class'] = 'attachment thumbnail';
        }
595
        $attrs['id'] = "attachment-{$attachment_id}";
596
    }
597

598
    return XMLStringer::estring('a', $attrs, $url);
599 600
}

601 602
function common_shorten_links($text)
{
603
    if (mb_strlen($text) <= 140) return $text;
604
    return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
605 606
}

607 608
function common_xml_safe_str($str)
{
609 610
    // Neutralize control codes and surrogates
	return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
611 612
}

613 614
function common_tag_link($tag)
{
615 616
    $canonical = common_canonical_tag($tag);
    $url = common_local_url('tag', array('tag' => $canonical));
617 618 619 620 621
    $xs = new XMLStringer();
    $xs->elementStart('span', 'tag');
    $xs->element('a', array('href' => $url,
                            'rel' => 'tag'),
                 $tag);
622
    $xs->elementEnd('span');
623
    return $xs->getString();
624 625
}

626 627
function common_canonical_tag($tag)
{
628 629
  $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
  return str_replace(array('-', '_', '.'), '', $tag);
Mike Cochrane's avatar
Mike Cochrane committed
630 631
}

632 633
function common_valid_profile_tag($str)
{
634
    return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
635 636
}

637 638
function common_at_link($sender_id, $nickname)
{
639 640 641
    $sender = Profile::staticGet($sender_id);
    $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
    if ($recipient) {
642 643 644 645 646 647
        $user = User::staticGet('id', $recipient->id);
        if ($user) {
            $url = common_local_url('userbyid', array('id' => $user->id));
        } else {
            $url = $recipient->profileurl;
        }
648
        $xs = new XMLStringer(false);
649 650 651 652 653
        $attrs = array('href' => $url,
                       'class' => 'url');
        if (!empty($recipient->fullname)) {
            $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
        }
654
        $xs->elementStart('span', 'vcard');
655
        $xs->elementStart('a', $attrs);
656 657 658 659
        $xs->element('span', 'fn nickname', $nickname);
        $xs->elementEnd('a');
        $xs->elementEnd('span');
        return $xs->getString();
660 661 662
    } else {
        return $nickname;
    }
663 664
}

665 666 667
function common_group_link($sender_id, $nickname)
{
    $sender = Profile::staticGet($sender_id);
668
    $group = User_group::getForNickname($nickname);
669
    if ($group && $sender->isMember($group)) {
670 671 672 673 674
        $attrs = array('href' => $group->permalink(),
                       'class' => 'url');
        if (!empty($group->fullname)) {
            $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
        }
675 676
        $xs = new XMLStringer();
        $xs->elementStart('span', 'vcard');
677
        $xs->elementStart('a', $attrs);
678 679 680 681
        $xs->element('span', 'fn nickname', $nickname);
        $xs->elementEnd('a');
        $xs->elementEnd('span');
        return $xs->getString();
682 683 684 685 686
    } else {
        return $nickname;
    }
}

687 688
function common_at_hash_link($sender_id, $tag)
{
689 690 691 692 693 694 695 696 697
    $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));
698 699 700 701 702 703 704
        $xs = new XMLStringer();
        $xs->elementStart('span', 'tag');
        $xs->element('a', array('href' => $url,
                                'rel' => $tag),
                     $tag);
        $xs->elementEnd('span');
        return $xs->getString();
705 706 707 708 709
    } else {
        return $tag;
    }
}

710 711
function common_relative_profile($sender, $nickname, $dt=null)
{
712 713 714 715
    // 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');
716
    $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
Evan Prodromou's avatar
TRUE  
Evan Prodromou committed
717
    if ($recipient->find(true)) {
718 719 720 721 722 723 724 725
        // 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');
726
    $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
Evan Prodromou's avatar
TRUE  
Evan Prodromou committed
727
    if ($recipient->find(true)) {
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        // 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;
744 745
}

746
function common_local_url($action, $args=null, $params=null, $fragment=null)
747
{
748 749
    static $sensitive = array('login', 'register', 'passwordsettings',
                              'twittersettings', 'finishopenidlogin',
750
                              'finishaddopenid', 'api');
751

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

755 756
    $ssl = in_array($action, $sensitive);

757
    if (common_config('site','fancy')) {
758
        $url = common_path(mb_substr($path, 1), $ssl);
759
    } else {
760
        if (mb_strpos($path, '/index.php') === 0) {
761
            $url = common_path(mb_substr($path, 1), $ssl);
762
        } else {
763
            $url = common_path('index.php'.$path, $ssl);
764
        }
765 766 767 768
    }
    return $url;
}

769
function common_path($relative, $ssl=false)
770
{
771
    $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787

    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;
788 789
}

790 791
function common_date_string($dt)
{
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    // 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
823 824
}

825 826
function common_exact_date($dt)
{
Mike Cochrane's avatar
Mike Cochrane committed
827 828 829 830 831 832 833 834
    static $_utc;
    static $_siteTz;

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

835 836 837 838
    $dateStr = date('d F Y H:i:s', strtotime($dt));
    $d = new DateTime($dateStr, $_utc);
    $d->setTimezone($_siteTz);
    return $d->format(DATE_RFC850);
839 840
}

841 842
function common_date_w3dtf($dt)
{
843 844 845 846
    $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);
847 848
}

849 850
function common_date_rfc2822($dt)
{
851 852 853 854
    $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
855 856
}

857 858
function common_date_iso8601($dt)
{
859 860 861 862
    $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
863 864
}

865 866
function common_sql_now()
{
867 868 869 870 871 872
    return common_sql_date(time());
}

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

875 876
function common_redirect($url, $code=307)
{
877 878 879 880
    static $status = array(301 => "Moved Permanently",
                           302 => "Found",
                           303 => "See Other",
                           307 => "Temporary Redirect");
Evan Prodromou's avatar
Evan Prodromou committed
881

882
    header('HTTP/1.1 '.$code.' '.$status[$code]);
883 884
    header("Location: $url");

Evan Prodromou's avatar
Evan Prodromou committed
885 886 887 888
    $xo = new XMLOutputter();
    $xo->startXML('a',
                  '-//W3C//DTD XHTML 1.0 Strict//EN',
                  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
889
    $xo->element('a', array('href' => $url), $url);
Evan Prodromou's avatar
Evan Prodromou committed
890
    $xo->endXML();
891
    exit;
892 893
}

894 895
function common_broadcast_notice($notice, $remote=false)
{
896
    return common_enqueue_notice($notice);
897 898
}

899
// Stick the notice on the queue
900

901 902
function common_enqueue_notice($notice)
{
903 904 905 906
    static $localTransports = array('omb',
                                    'twitter',
                                    'facebook',
                                    'ping');
907
    static $allTransports = array('sms');
908

909
    $transports = $allTransports;
910

911 912 913 914 915 916
    $xmpp = common_config('xmpp', 'enabled');

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

917 918
    if ($notice->is_local == Notice::LOCAL_PUBLIC ||
        $notice->is_local == Notice::LOCAL_NONPUBLIC) {
919
        $transports = array_merge($transports, $localTransports);
920 921 922
        if ($xmpp) {
            $transports[] = 'public';
        }
923
    }
924

925
    $qm = QueueManager::get();
926

927 928 929
    foreach ($transports as $transport)
    {
        $qm->enqueue($notice, $transport);
930
    }
931

932
    return true;
933 934
}

935 936
function common_broadcast_profile($profile)
{
937 938 939 940 941
    // 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;
942
}
943

944 945
function common_profile_url($nickname)
{
946
    return common_local_url('showstream', array('nickname' => $nickname));
947 948
}

949
// Should make up a reasonable root URL
950

951
function common_root_url($ssl=false)
952
{
953
    return common_path('', $ssl);
954 955
}

956 957
// 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
958

959 960
function common_good_rand($bytes)
{
961
    // XXX: use random.org...?
962
    if (@file_exists('/dev/urandom')) {
963 964 965 966
        return common_urandom($bytes);
    } else { // FIXME: this is probably not good enough
        return common_mtrand($bytes);
    }
Evan Prodromou's avatar
Evan Prodromou committed
967 968
}

969 970
function common_urandom($bytes)
{
971 972 973 974 975 976 977 978 979
    $h = fopen('/dev/urandom', 'rb');
    // should not block
    $src = fread($h, $bytes);
    fclose($h);
    $enc = '';
    for ($i = 0; $i < $bytes; $i++) {
        $enc .= sprintf("%02x", (ord($src[$i])));
    }
    return $enc;
Evan Prodromou's avatar
Evan Prodromou committed
980 981
}

982 983
function common_mtrand($bytes)
{
984 985 986 987