Issues (1963)

html/inc/util.inc (45 issues)

1
<?php
2
// This file is part of BOINC.
3
// http://boinc.berkeley.edu
4
// Copyright (C) 2021 University of California
5
//
6
// BOINC is free software; you can redistribute it and/or modify it
7
// under the terms of the GNU Lesser General Public License
8
// as published by the Free Software Foundation,
9
// either version 3 of the License, or (at your option) any later version.
10
//
11
// BOINC 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.
14
// See the GNU Lesser General Public License for more details.
15
//
16
// You should have received a copy of the GNU Lesser General Public License
17
// along with BOINC.  If not, see <http://www.gnu.org/licenses/>.
18
19
// Utility functions for BOINC web pages
20
// Stuff that's not web-specific (e.g. that's used in non-web scripts)
21
// should go in util_basic.inc
22
23
require_once("../inc/util_basic.inc");
24
require_once("../project/project.inc");
25
require_once("../inc/countries.inc");
26
require_once("../inc/db.inc");
27
require_once("../inc/boinc_db.inc");
28
require_once("../inc/translation.inc");
29
require_once("../inc/profile.inc");
30
require_once("../inc/bootstrap.inc");
31
32
function master_url() {
33
    return parse_config(get_config() , "<master_url>");
34
}
35
function recaptcha_public_key() {
36
    return parse_config(get_config(), "<recaptcha_public_key>");
37
}
38
function recaptcha_private_key() {
39
    return parse_config(get_config(), "<recaptcha_private_key>");
40
}
41
42
// Set parameters to defaults if not defined in config.xml
43
44
$x = parse_config(get_config(), "<user_country>");
45
define('USER_COUNTRY', ($x===null)?1:(int)$x);
46
47
$x = parse_config(get_config(), "<user_url>");
48
define('USER_URL', ($x===null)?1:(int)$x);
49
50
// Set parameters to defaults if not defined in project.inc
51
52
if (defined('TIMEZONE')) {
53
    date_default_timezone_set(TIMEZONE);
54
} else {
55
    date_default_timezone_set('UTC');
56
}
57
if (!defined('DISABLE_PROFILES')) {
58
    define('DISABLE_PROFILES', false);
59
}
60
if (!defined('DISABLE_FORUMS')) {
61
    define('DISABLE_FORUMS', false);
62
}
63
if (!defined('DISABLE_TEAMS')) {
64
    define('DISABLE_TEAMS', false);
65
}
66
if (!defined('DISABLE_BADGES')) {
67
    define('DISABLE_BADGES', false);
68
}
69
if (!defined('BADGE_HEIGHT_SMALL')) {
70
    define('BADGE_HEIGHT_SMALL', 20);
71
}
72
if (!defined('BADGE_HEIGHT_MEDIUM')) {
73
    define('BADGE_HEIGHT_MEDIUM', 24);
74
}
75
if (!defined('BADGE_HEIGHT_LARGE')) {
76
    define('BADGE_HEIGHT_LARGE', 56);
77
}
78
if (!defined('LDAP_HOST')) {
79
    define('LDAP_HOST', null);
80
}
81
if (!defined('POSTAL_CODE')) {
82
    define('POSTAL_CODE', false);
83
}
84
if (!defined('NO_COMPUTING')) {
85
    define('NO_COMPUTING', false);
86
}
87
if (!defined('NO_HOSTS')) {
88
    define('NO_HOSTS', false);
89
}
90
if (!defined('NO_STATS')) {
91
    define('NO_STATS', false);
92
}
93
if (!defined('NO_GLOBAL_PREFS')) {
94
    define('NO_GLOBAL_PREFS', false);
95
}
96
97
// the 'home page' of the logged-in user.
98
// go here after login, account creation, team operations, etc.
99
//
100
if (!defined('HOME_PAGE')) {
101
    define('HOME_PAGE', 'home.php');
102
}
103
104
// the page showing another user ('userid' arg).
105
// Link to here wherever we show a user name.
106
//
107
if (!defined('SHOW_USER_PAGE')) {
108
    define('SHOW_USER_PAGE', 'show_user.php');
109
}
110
111
if (!defined('POST_MAX_LINKS')) {
112
    define('POST_MAX_LINKS', 0);
113
}
114
115
// support dark mode if user has selected it
116
if (!defined('DARK_MODE')) {
117
    define('DARK_MODE', true);
118
}
119
if (!defined('VALIDATE_EMAIL_TO_POST')) {
120
    define('VALIDATE_EMAIL_TO_POST', false);
121
}
122
if (!defined('UNIQUE_USER_NAME')) {
123
    define('UNIQUE_USER_NAME', false);
124
}
125
126
// don't allow anything between .php and ? in URL
127
//
128
if (array_key_exists("PATH_INFO", $_SERVER)) {
129
    die("bad URL");
130
}
131
132
// sleep this long on any login failure
133
// (slow the rate of hacker attacks)
134
//
135
define('LOGIN_FAIL_SLEEP_SEC', 5);
136
137
$caching = false;
138
    // if set, we're writing to a file rather than to client
139
$did_page_head = false;
140
141
define('KILO', 1024);
142
define('MEGA', 1024*KILO);
143
define('GIGA', 1024*MEGA);
144
define('TERA', 1024*GIGA);
145
146
// return true if this page is HTTPS
147
//
148
function is_https() {
149
    return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'];
150
}
151
152
function secure_url_base() {
153
    if (defined('SECURE_URL_BASE')) return SECURE_URL_BASE;
154
    return URL_BASE;
155
}
156
157
function url_base() {
158
    return is_https()?secure_url_base():URL_BASE;
159
}
160
161
function send_cookie($name, $value, $permanent, $ops=false) {
162
    // the following allows independent login for projects on the same server
163
    //
164
    $url = parse_url(master_url());
165
    $path = $url['path'];
166
    if ($ops) {
167
        $path = substr($path, 0, -1);
168
        $path .= "_ops/";
169
    }
170
    $expire = $permanent?time()+3600*24*365:0;
171
    setcookie($name, $value, $expire, $path,
172
        '',
173
        is_https(),     // if this page is secure, make cookie secure
174
        true            // httponly; no JS access
175
    );
176
}
177
178
function clear_cookie($name, $ops=false) {
179
    $url = parse_url(master_url());
180
    $path = $url['path'];
181
    if ($ops) {
182
        $path = substr($path, 0, -1);
183
        $path .= "_ops/";
184
    }
185
    setcookie($name, '', time()-3600, $path);
186
}
187
188
$g_logged_in_user = null;
189
$got_logged_in_user = false;
190
191
function get_logged_in_user($must_be_logged_in=true) {
192
    global $g_logged_in_user, $got_logged_in_user;
193
    if ($got_logged_in_user) {
194
        // this could have been called earlier with $must_be_logged_in false
195
        if ($must_be_logged_in) {
196
            if ($g_logged_in_user) return $g_logged_in_user;
197
        } else {
198
            return $g_logged_in_user;
199
        }
200
    }
201
202
    if (web_stopped()) return null;
203
204
    $authenticator = null;
205
    if (isset($_COOKIE['auth'])) $authenticator = $_COOKIE['auth'];
206
207
    if ($authenticator) {
208
        $authenticator = BoincDb::escape_string($authenticator);
209
        $g_logged_in_user = BoincUser::lookup("authenticator='$authenticator'");
210
    }
211
    if ($must_be_logged_in && !$g_logged_in_user) {
212
        $next_url = '';
213
        if (array_key_exists('REQUEST_URI', $_SERVER)) {
214
            $next_url = $_SERVER['REQUEST_URI'];
215
            $n = strrpos($next_url, "/");
216
            if ($n) {
217
                $next_url = substr($next_url, $n+1);
218
            }
219
        }
220
        $next_url = urlencode($next_url);
221
        Header("Location: ".url_base()."login_form.php?next_url=$next_url");
0 ignored issues
show
Calls to inbuilt PHP functions must be lowercase; expected "header" but found "Header"
Loading history...
222
        exit;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
223
    }
224
    $got_logged_in_user = true;
225
    return $g_logged_in_user;
226
}
227
228
function show_login_info($prefix="") {
229
    $user = get_logged_in_user(false);
0 ignored issues
show
Are you sure the assignment to $user is correct as get_logged_in_user(false) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
230
    if ($user) {
231
        $url_tokens = url_tokens($user->authenticator);
232
        echo "<nobr>$user->name &middot; <a href=".$prefix."logout.php?$url_tokens>".tra("log out")."</a></nobr>";
233
    } else {
234
        echo "<a href=".$prefix."login_form.php>".tra("log in")."</a>";
235
    }
236
}
237
238
$cache_control_extra="";
239
$is_login_page = false;
240
241
// Call this to start pages.
242
// Outputs some HTML boilerplate,
243
// then calls project_banner() (in html/project/project.inc)
244
// to output whatever you want at the top of your web pages.
245
//
246
// Page_head() is overridable so that projects that want to integrate BOINC
247
// with an existing web framework can more easily do so.
248
// To do so, define page_head() in html/project/project.inc
249
//
250
if (!function_exists("page_head")){
251
function page_head(
252
    $title,
253
        // page title. Put in <title>, used as title for browser tab.
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
254
    $body_attrs=null,
255
        // <body XXXX>
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
256
        // e.g. Javascript to put focus in an input field
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
257
        // (onload="document.form.foo.focus()")
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
258
        // or to jump to a particular post (onload="jumpToUnread();")
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
259
    $is_main = false,
260
        // if set, include schedulers.txt.
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
261
        // also pass to project_banner() in case you want a different
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
262
        // header for your main page.
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
263
    $url_prefix="",
264
        // prepend this to links.
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
265
        // Use for web pages not in the top directory
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
266
    $head_extra=null
267
        // extra stuff to put in <head>. E.g.:
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
268
        // reCAPTCHA code (create_profile.php)
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
269
        // bbcode javascript (forums)
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
270
) {
271
    global $caching, $cache_control_extra, $did_page_head;
272
    global $is_login_page, $fixed_navbar;
273
274
    if ($did_page_head) {
275
        return;
276
    }
277
278
    $did_page_head = true;
279
    $url_base = url_base();
280
281
    $rssname = "RSS 2.0";
282
    $rsslink = $url_base."rss_main.php";
283
284
    if (!$caching) {
285
        header("Content-type: text/html; charset=utf-8");
286
        header("Expires: Mon, 26 Jul 1997 05:00:00 UTC");
287
            // Date in the past
288
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " UTC");
289
            // always modified
290
        header("Cache-Control: $cache_control_extra no-cache, must-revalidate, post-check=0, pre-check=0");
291
            // for HTTP/1.1
292
        header("Pragma: no-cache");
293
            // for HTTP/1.0
294
    }
295
296
    echo '<!DOCTYPE html>
297
        <html lang="en">
298
        <head>
299
    ';
300
    echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>';
301
302
    if (defined('GLOBAL_HEAD_EXTRA')) {
303
        echo GLOBAL_HEAD_EXTRA;
304
    }
305
    echo '
306
        <meta name="viewport" content="width=device-width, initial-scale=1">
307
    ';
308
    if ($head_extra) {
309
        echo "\n$head_extra\n";
310
    }
311
    if ($is_main && (!defined('NO_COMPUTING')||!NO_COMPUTING)) {
0 ignored issues
show
Expected 1 space before logical operator; 0 found
Loading history...
Expected 1 space after logical operator; 0 found
Loading history...
312
        readfile("schedulers.txt");
313
    }
314
315
    $t = $title?$title:PROJECT;
316
    echo "<title>$t</title>\n";
317
    echo '
318
        <meta charset="utf-8">
319
    ';
320
    if (DARK_MODE) {
321
        echo <<<EOT
0 ignored issues
show
Use of heredoc and nowdoc syntax ("<<<") is not allowed; use standard strings or inline HTML instead
Loading history...
322
<script>
323
  if (window.matchMedia('(prefers-color-scheme: dark)').media === 'not all') {
324
      console.log("foobar");
325
    document.documentElement.style.display = 'none';
326
    document.head.insertAdjacentHTML(
327
        'beforeend',
328
        '<link rel="stylesheet" href="sample_bootstrap.min.css" onload="document.documentElement.style.display = \'\'"><link rel="stylesheet" href="custom.css">'
329
    );
330
  }
331
</script>
332
<link rel="stylesheet" href="bootstrap_darkly.min.css" media="(prefers-color-scheme: dark)">
333
<link rel="stylesheet" href="custom_dark.css" media="(prefers-color-scheme: dark)">
334
<link rel="stylesheet" href="sample_bootstrap.min.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)">
335
<link rel="stylesheet" href="custom.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)">
336
EOT;
337
    } else {
338
        echo '
339
            <link type="text/css" rel="stylesheet" href="'.secure_url_base().'/bootstrap.min.css" media="all">
340
        ';
341
    }
342
    if (defined('STYLESHEET')) {
343
        $stylesheet = $url_base.STYLESHEET;
344
        echo "
345
            <link rel=stylesheet type=\"text/css\" href=\"$stylesheet\">
346
        ";
347
    }
348
    if (defined('STYLESHEET2')) {
349
        $stylesheet2 = $url_base.STYLESHEET2;
350
        echo "
351
            <link rel=stylesheet type=\"text/css\" href=\"$stylesheet2\">
352
        ";
353
    }
354
355
    if (defined("SHORTCUT_ICON")) {
356
        echo '<link rel="icon" type="image/x-icon" href="'.SHORTCUT_ICON.'"/>
357
';
358
    }
359
360
    echo "
361
        <link rel=alternate type=\"application/rss+xml\" title=\"$rssname\" href=\"$rsslink\">
362
        </head>
363
    ";
364
    if ($fixed_navbar) {
365
        $body_attrs .= ' style="padding-top:70px"';
366
    }
367
    echo "<body $body_attrs>";
368
    echo '<div class="container-fluid">
369
    ';
370
371
    switch($title) {    //kludge
372
    case tra("Log in"):
373
    case tra("Create an account"):
374
    case tra("Server status page"):
375
        $is_login_page = true;
376
        break;
377
    default:
0 ignored issues
show
DEFAULT keyword must be indented 4 spaces from SWITCH keyword
Loading history...
Comment required for empty DEFAULT case
Loading history...
378
        break;
379
    }
380
    project_banner($title, $url_prefix, $is_main);
381
}
382
}
383
384
// See the comments for page_head()
385
//
386
if (!function_exists("page_tail")){
387
function page_tail(
388
    $show_date=false,
389
        // true for pages that are generated periodically rather than on the fly
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
390
    $url_prefix="",
391
        // use for pages not at top level
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
392
    $is_main=false
393
        // passed to project_footer;
0 ignored issues
show
Multi-line function declaration not indented correctly; expected 4 spaces but found 8
Loading history...
394
) {
395
    echo "<br>\n";
396
    project_footer($is_main, $show_date, $url_prefix);
397
    echo '
398
        <script src="'.secure_url_base().'/bootstrap.min.js"></script>
399
        </div>
400
        </body>
401
        </html>
402
    ';
403
}
404
}
405
406
function db_error_page() {
407
    page_head("Database error");
408
    echo tra("A database error occurred while handling your request; please try again later.");
409
    page_tail();
410
}
411
412
function error_page($msg) {
413
    global $generating_xml;
414
    if ($generating_xml) {
415
        xml_error(-1, $msg);
416
    }
417
    page_head(tra("Unable to handle request"));
418
    echo $msg;
419
    page_tail();
420
    exit();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
421
}
422
423
// convert time interval in seconds to a string of the form
424
// 'D days h hours m min s sec'.
425
426
function time_diff($x, $res=3) {
427
    $x = (int)$x;
428
    $days    = (int)($x/86400);
429
    $hours   = (int)(($x-$days*86400)/3600);
430
    $minutes = (int)(($x-$days*86400-$hours*3600)/60);
431
    $seconds = $x % 60;
432
433
    $s = "";
434
    if ($days) {
435
        $s .= "$days ".tra("days")." ";
436
    }
437
    if ($res>0 && ($hours || strlen($s))) {
438
        $s .= "$hours ".tra("hours")." ";
439
    }
440
    if ($res>1 && ($minutes || strlen($s))) {
441
        $s .= "$minutes ".tra("min")." ";
442
    }
443
    if ($res>2) {
444
        $s .= "$seconds ".tra("sec")." ";
445
    }
446
    return $s;
447
}
448
449
450
function date_str($x) {
451
    if ($x == 0) return "---";
452
    return gmdate('j M Y', (int)$x);
453
}
454
455
function time_str($x) {
456
    if ($x == 0) return "---";
457
    return gmdate('j M Y, G:i:s', (int)$x) . " UTC";
458
}
459
460
function local_time_str($x) {
461
    if ($x == 0) return "---";
462
    return date('j M Y, H:i T', (int)$x);
463
}
464
465
function pretty_time_str($x) {
466
    return time_str($x);
467
}
468
469
function start_table_str($class="", $style="") {
470
    $s = $style?'style="'.$style.'"':'';
471
    return '<div class="table">
472
      <table '.$s.' width="100%" class="table table-condensed '.$class.'" >
473
    ';
474
}
475
476
function start_table($class="", $style="") {
477
    echo start_table_str($class, $style);
478
}
479
480
function end_table_str() {
481
    return '</table>
482
        </div>
483
    ';
484
}
485
486
function end_table() {
487
    echo end_table_str();
488
}
489
490
// Table header row with unlimited number of columns
491
492
function table_header() {
493
    echo "<tr>\n";
494
    $c = 'class="bg-primary"';
495
    for ($i = 0; $i < func_num_args(); $i++) {
496
        if (is_array(func_get_arg($i))) {
497
            $col = func_get_arg($i);
498
            echo "<th $c ".$col[1].">".$col[0]."</th>\n";
499
        } else {
500
            echo "<th $c>".func_get_arg($i)."</th>\n";
501
        }
502
    }
503
    echo "</tr>\n";
504
}
505
506
// Table row with unlimited number of columns
507
508
function table_row() {
509
    echo "<tr>\n";
510
    for ($i = 0; $i < func_num_args(); $i++) {
511
        if (is_array(func_get_arg($i))) {
512
            $col = func_get_arg($i);
513
            echo "<td ".$col[1].">".$col[0]."</td>\n";
514
        } else {
515
            echo "<td>".func_get_arg($i)."</td>\n";
516
        }
517
    }
518
    echo "</tr>\n";
519
}
520
521
function row1($x, $ncols=2, $class="heading") {
522
    if ($class == "heading") {
523
        echo "<tr><th class=\"bg-primary\" colspan=\"$ncols\">$x</th></tr>\n";
524
    } else {
525
        echo "<tr><td class=\"$class\" colspan=\"$ncols\">$x</td></tr>\n";
526
    }
527
}
528
529
define('NAME_ATTRS', 'class="text-right " style="padding-right:12px"');
530
define('VALUE_ATTRS', 'style="padding-left:12px"');
531
define('VALUE_ATTRS_ERR', 'class="danger" style="padding-left:12px"');
532
533
// a table row with 2 columns, with the left on right-aligned
534
535
function row2($x, $y, $show_error=false, $lwidth='40%') {
536
    if ($x==="") $x="<br>";
537
    if ($y==="") $y="<br>";
538
    $attrs = $show_error?VALUE_ATTRS_ERR:VALUE_ATTRS;
539
    echo "<tr>
540
        <td width=\"$lwidth\" ".NAME_ATTRS.">$x</td>
541
        <td $attrs >$y</td>
542
        </tr>
543
    ";
544
}
545
546
// output the first part of row2();
547
// then write the content, followed by </td></tr>
548
549
function row2_init($x, $lwidth='40%') {
550
    echo sprintf('<tr>
551
        <td width="%s" %s>%s</td>
552
        <td %s>',
553
        $lwidth, NAME_ATTRS, $x, VALUE_ATTRS
554
    );
555
}
556
557
function row2_plain($x, $y) {
558
    echo "<tr><td>$x</td><td>$y</td></tr>\n";
559
}
560
561
function rowify($string) {
562
    echo "<tr><td>$string</td></tr>";
563
}
564
565
function row_array($x, $attrs=null) {
566
    echo "<tr>\n";
567
    $i = 0;
568
    foreach ($x as $h) {
569
        $a = $attrs?$attrs[$i]:"";
570
        echo "<td $a>$h</td>\n";
571
        $i++;
572
    }
573
    echo "</tr>\n";
574
}
575
576
define ('ALIGN_RIGHT', 'style="text-align:right;"');
577
578
function row_heading_array($x, $attrs=null, $class='bg-primary') {
579
    echo "<tr>";
580
    $i = 0;
581
    foreach ($x as $h) {
582
        $a = $attrs?$attrs[$i]:"";
583
        echo "<th $a class=\"$class\">$h</th>";
584
        $i++;
585
    }
586
    echo "</tr>\n";
587
}
588
589
function row_heading($x, $class='bg-primary') {
590
    echo sprintf('<tr><th class="%s" colspan=99>%s</th></tr>
591
        ', $class, $x
592
    );
593
}
594
595
function url_tokens($auth) {
596
    $now = time();
597
    $ttok = md5((string)$now.$auth);
598
    return "&amp;tnow=$now&amp;ttok=$ttok";
599
}
600
601
function form_tokens($auth) {
602
    $now = time();
603
    $ttok = md5((string)$now.$auth);
604
    return "<input type=\"hidden\" name=\"tnow\" value=\"$now\">
605
        <input type=\"hidden\" name=\"ttok\" value=\"$ttok\">
606
    ";
607
}
608
609
function valid_tokens($auth) {
610
    $tnow = get_str('tnow', true);
611
    $ttok = get_str('ttok', true);
612
    if (!$tnow) {
613
      if (isset($_POST['tnow'])) {
614
          $tnow = $_POST['tnow'];
615
      }
616
    }
617
    if (!$ttok) {
618
      if (isset($_POST['ttok'])) {
619
          $ttok = $_POST['ttok'];
620
      }
621
    }
622
    if (!$tnow) return false;
623
    if (!$ttok) return false;
624
    $t = md5((string)$tnow.$auth);
625
    if ($t != $ttok) return false;
626
    if (time() > $tnow + 86400) return false;
627
    return true;
628
}
629
630
function check_tokens($auth) {
631
    if (valid_tokens($auth)) return;
632
    error_page(
633
        tra("Link has timed out. Please click Back, refresh the page, and try again.")
634
    );
635
}
636
637
// Generates a legal filename from a parameter string.
638
639
function get_legal_filename($name) {
640
    return strtr($name, array(','=>'', ' '=>'_'));
641
}
642
643
// Returns a string containing as many words
644
// (being collections of characters separated by the character $delimiter)
645
// as possible such that the total string length is <= $chars characters long.
646
// If $ellipsis is true, then an ellipsis is added to any sentence which
647
// is cut short.
648
649
function sub_sentence($sentence, $delimiter, $max_chars, $ellipsis=false) {
650
    $words = explode($delimiter, $sentence);
651
    $total_chars = 0;
652
    $trunc = false;
653
    $result = "";
654
655
    foreach ($words as $word) {
656
        if (strlen($result) + strlen($word) > $max_chars) {
657
            $trunc = true;
658
            break;
659
        }
660
        if ($result) {
661
            $result .= " $word";
662
        } else {
663
            $result = $word;
664
        }
665
    }
666
667
    if ($ellipsis && $trunc) {
668
        $result .= "...";
669
    }
670
671
    return $result;
672
}
673
674
// use this for user RAC and result credit
675
//
676
function format_credit($x) {
677
    return number_format($x, 2);
678
}
679
680
// use this when credit is likely to be large, e.g. team RAC
681
//
682
function format_credit_large($x) {
683
    return number_format($x, 0);
684
}
685
686
function host_link($hostid) {
687
    if ($hostid) {
688
        return "<a href=\"show_host_detail.php?hostid=$hostid\">$hostid</a>";
689
    } else {
690
        return "---";
691
    }
692
}
693
694
function open_output_buffer() {
695
    ob_start();
696
    ob_implicit_flush(0);
697
}
698
699
function close_output_buffer($filename) {
700
    $fh = fopen($filename, "w");
701
    $page = ob_get_contents();
702
    ob_end_clean();
703
    fwrite($fh, $page);
704
    fclose($fh);
705
}
706
707
function bbcode_info() {
708
    return "<br><a href=bbcode.php target=new><small>".tra("Use BBCode tags to format your text")."</small></a>\n";
709
}
710
711
// strip slashes if magic quotes in effect
712
function undo_magic_quotes($x) {
713
    if (version_compare(PHP_VERSION, '5.4.0') < 0 && get_magic_quotes_gpc()) {
714
        return stripslashes($x);
715
    }
716
    return $x;
717
}
718
719
// check for bogus GET args
720
//
721
function check_get_args($args) {
722
    foreach ($_GET as $key => $val) {
723
        if (!in_array($key, $args)) {
724
            Header("Location: extra_arg_$key.html");
0 ignored issues
show
Calls to inbuilt PHP functions must be lowercase; expected "header" but found "Header"
Loading history...
725
            die;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
726
        }
727
    }
728
}
729
730
// returns null if the arg is optional and missing
731
//
732
function get_int($name, $optional=false) {
733
    $x=null;
734
    if (isset($_GET[$name])) $x = $_GET[$name];
735
    if (!is_numeric($x)) {
736
        if ($optional) {
737
            if ($x) {
738
                Header("Location: non_num_arg.html");
0 ignored issues
show
Calls to inbuilt PHP functions must be lowercase; expected "header" but found "Header"
Loading history...
739
                die;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
740
            }
741
            return null;
742
        } else {
743
            Header("Location: missing_arg_$name.html");
0 ignored issues
show
Calls to inbuilt PHP functions must be lowercase; expected "header" but found "Header"
Loading history...
744
            die;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
745
        }
746
    }
747
    return (int)$x;
748
}
749
750
// returns null if the arg is optional and missing
751
//
752
function post_num($name, $optional=false) {
753
    $x = null;
754
    if (isset($_POST[$name])) $x = $_POST[$name];
755
    if (!is_numeric($x)) {
756
        if ($optional) {
757
            return null;
758
        } else {
759
            error_page("missing or bad parameter: $name; supplied: ".htmlspecialchars($x));
760
        }
761
    }
762
    return (double)$x;
763
}
764
765
// returns null if the arg is optional and missing
766
//
767
function post_int($name, $optional=false) {
768
    $x = post_num($name, $optional);
769
    if (is_null($x)) return null;
770
    $y = (int)$x;
771
    if ($x != $y) {
772
        error_page("param $name must be an integer");
773
    }
774
    return $y;
775
}
776
777
function get_array($name) {
778
    if (isset($_GET[$name])) {
779
        return $_GET[$name];
780
    } else {
781
        return array();
782
    }
783
}
784
785
function get_str($name, $optional=false) {
786
    if (isset($_GET[$name])) {
787
        $x = $_GET[$name];
788
    } else {
789
        if (!$optional) {
790
            error_page("missing or bad parameter: $name");
791
        }
792
        $x = null;
793
    }
794
    return undo_magic_quotes($x);
795
}
796
797
function post_str($name, $optional=false) {
798
    if (isset($_POST[$name])) {
799
        $x = $_POST[$name];
800
    } else {
801
        if (!$optional) {
802
            error_page("missing or bad parameter: $name");
803
        }
804
        $x = null;
805
    }
806
    return undo_magic_quotes($x);
807
}
808
809
function post_arr($name, $optional=false) {
810
    if (isset($_POST[$name]) && is_array($_POST[$name])) {
811
        $x = $_POST[$name];
812
    } else {
813
        if (!$optional) {
814
            error_page("missing or bad parameter: $name");
815
        }
816
        $x = null;
817
    }
818
    return $x;
819
}
820
821
function is_ascii($str) {
822
    // the mb_* functions are not included by default
823
    // return (mb_detect_encoding($passwd) -= 'ASCII');
824
825
    for ($i=0; $i<strlen($str); $i++) {
0 ignored issues
show
Coding Style Performance introduced by
The use of strlen() inside a loop condition is not allowed; assign the return value to a variable and use the variable in the loop condition instead
Loading history...
826
        $c = ord(substr($str, $i));
827
        if ($c < 32 || $c > 127) return false;
828
    }
829
    return true;
830
}
831
832
// This function replaces some often made mistakes while entering numbers
833
// and gives back an error if there are false characters
834
// It will also be checked if the value is within certain borders
835
// @param string &$value reference to the value that should be verified
836
// @param double $low the lowest number of value if verified
837
// @param double $high the highest number of value if verified
838
// @return bool true if $value is numeric and within the defined borders,
839
//   false if $value is not numeric, no changes were made in this case
840
//
841
function verify_numeric(&$value, $low, $high = false) {
842
    $number = trim($value);
843
    $number = str_replace('o', '0', $number);
844
    $number = str_replace('O', '0', $number);
845
    $number = str_replace('x', '', $number); //if someone enters '0x100'
846
    $number = str_replace(',', '.', $number); // replace the german decimal separator
847
    // if no value was entered and this is ok
848
    //
849
    if ($number=='' && !$low) return true;
850
851
    // the supplied value contains alphabetic characters
852
    //
853
    if (!is_numeric($number)) return false;
854
855
    if ($number < $low) return false;
856
857
    if ($high) {
858
        if ($number > $high) return false;
859
    }
860
    $value = (double)$number;
861
    return true;
862
}
863
864
// Generate a "select" element from an array of values
865
//
866
function select_from_array($name, $array, $selection=null, $width=240) {
867
    $out = '<select style="color:#000;"class="form-control input-sm" style="width:'.$width.'px" name="'.$name.'">"';
868
869
    foreach ($array as $key => $value) {
870
        if ($value) {
871
            $out .= "<option ";
872
            if ($key == $selection) {
873
                $out .= "selected ";
874
            }
875
            $out .= "value=\"".$key."\">".$value."</option>\n";
876
        }
877
    }
878
    $out .= "</select>\n";
879
    return $out;
880
}
881
882
// Convert to entities, while preserving already-encoded entities.
883
// Do NOT use if $str contains valid HTML tags.
884
//
885
function boinc_htmlentities($str) {
886
    $str = html_entity_decode($str, ENT_COMPAT, "UTF-8");
887
    $str = htmlentities($str, ENT_COMPAT, "UTF-8");
888
    return $str;
889
}
890
891
function strip_bbcode($string){
892
    return preg_replace("/((\[.+\])+?)(.+?)((\[\/.+\])+?)/","",$string);
893
}
894
895
function current_url() {
896
    $url = is_https()?'https':'http';
897
    $url .= "://";
898
    $url .= $_SERVER['SERVER_NAME'];
899
    $url .= ":".$_SERVER['SERVER_PORT'];
900
    if (isset($_SERVER['REQUEST_URI'])) {
901
        $url .= $_SERVER['REQUEST_URI'];
902
    } else {
903
        if ($_SERVER['QUERY_STRING']) {
904
            $url .= "?".$_SERVER['QUERY_STRING'];
905
        }
906
    }
907
    return $url;
908
}
909
910
// return style for a button
911
// the colors for bootstrap's btn-success are almost illegible;
912
// the green is too light.  Use a darker green.
913
//
914
function button_style($color='green', $font_size=null) {
915
    $fs = '';
916
    if ($font_size) {
917
        $fs = sprintf('; font-size:%dpx', $font_size);
918
    }
919
    $c = 'seagreen';
920
    if ($color == 'blue') $c = 'steelblue';
921
    return sprintf(
922
        'style="background-color:%s; color:white; text-decoration:none%s"',
923
        $c, $fs
924
    );
925
}
926
// Show a link formatted to look like a button.
927
// url: the destination of the lin
928
// text: The text to display on the button
929
// desc: tooltip text (show on hover)
930
// class: class of the button, e.g. btn
931
// extra: Additional text in href tag
932
//
933
function button_text($url, $text, $desc=null, $class=null, $extra='') {
934
    if (!$desc) {
935
        $desc = $text;
936
    }
937
    if (!$extra && !$class) {
938
        $extra = button_style();
939
    }
940
    if (!$class) {
941
        $class = "btn btn-sm";
942
    }
943
    return sprintf(' <a href="%s" title="%s" class="btn %s" %s>%s</a>',
944
        $url, $desc, $class, $extra, $text
945
    );
946
}
947
948
function button_text_small($url, $text, $desc=null) {
949
    return button_text($url, $text, $desc, "btn btn-xs", button_style());
950
}
951
952
function show_button($url, $text, $desc=null, $class=null, $extra=null) {
953
    echo button_text($url, $text, $desc, $class, $extra);
954
}
955
956
// for places with a bunch of buttons, like forum posts
957
//
958
function show_button_small($url, $text, $desc=null) {
959
    echo button_text_small($url, $text, $desc);
960
}
961
962
// used for showing icons
963
//
964
function show_image($src, $title, $alt, $height=null) {
965
    $h = "";
966
    if ($height) {
967
        $h = "height=\"$height\"";
968
    }
969
    echo "<img class=\"icon\" border=\"0\" title=\"$title\" alt=\"$alt\" src=\"$src\" $h>";
970
}
971
972
function show_project_down() {
973
    global $did_page_head;
974
    if (!$did_page_head) {
975
        page_head(tra("Project down for maintenance"));
976
    }
977
    echo tra(
978
        "%1 is temporarily shut down for maintenance.  Please try again later.",
979
        PROJECT
980
    );
981
    page_tail();
982
    exit();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
983
}
984
985
function check_web_stopped() {
986
    global $generating_xml;
987
    if (web_stopped()) {
988
        if ($generating_xml) {
989
            xml_error(-183);
990
        } else {
991
            show_project_down();
992
        }
993
    }
994
}
995
996
// Connects to database server and selects database as noted in config.xml
997
// If only read-only access is necessary,
998
// tries instead to connect to <replica_db_host> if tag exists.
999
// DEPRECATED - use boinc_db.inc
1000
//
1001
function db_init($try_replica=false) {
1002
    check_web_stopped();
1003
    $retval = db_init_aux($try_replica);
1004
    if ($retval == 1) {
1005
        echo tra("Unable to connect to database - please try again later");
1006
        exit();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1007
    }
1008
    if ($retval == 2) {
1009
        echo tra("Unable to select database - please try again later");
1010
        exit();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1011
    }
1012
    return 0;
1013
}
1014
1015
// Functions to sanitize GET and POST args
1016
1017
// "next_url" arguments (must be local, not full URLs)
1018
//
1019
function sanitize_local_url($x) {
1020
    if (!$x) return $x;
1021
    $x = trim($x, "/");
1022
    if (strstr($x, "/")) return "";
1023
    if (strstr($x, "<")) return "";
1024
    if (strstr($x, "\"")) return "";
1025
    return $x;
1026
}
1027
1028
function sanitize_user_url($x) {
1029
    // if protocol is given, must be http: or https:
1030
    $y = explode('//', $x);
1031
    switch (count($y)) {
1032
    case 1:
1033
        $z = $x;
1034
        break;
1035
    case 2:
1036
        $z = $y[1];
1037
        if (strtolower($y[0]) == 'http:') break;
1038
        if (strtolower($y[0]) == 'https:') break;
1039
        return '';
1040
    default: return '';
0 ignored issues
show
DEFAULT keyword must be indented 4 spaces from SWITCH keyword
Loading history...
Blank lines are not allowed after DEFAULT statements
Loading history...
1041
    }
1042
    // everything else must be alphanumeric, or -_/.#?&=
1043
    if (preg_match('/^[-_.\/#?&=a-zA-Z0-9]*$/', $z)) {
1044
        return $x;
1045
    }
1046
    return '';
1047
}
1048
1049
// strip HTML tags
1050
//
1051
function sanitize_tags($x) {
1052
    if (!$x) return $x;
1053
    return strip_tags($x);
1054
}
1055
1056
function sanitize_numeric($x) {
1057
    if (!$x || !is_numeric($x)) {
1058
        return '';
1059
    }
1060
    return $x;
1061
}
1062
1063
function sanitize_email($x) {
1064
    if (!$x) return $x;
1065
    if (function_exists('filter_var')) {
1066
        return filter_var($x, FILTER_SANITIZE_EMAIL);
1067
    } else {
1068
        return strip_tags($x);
1069
    }
1070
}
1071
1072
// pages like top_hosts.php, team_members.php etc. have a textual
1073
// "sort_by" argument.
1074
// Check this to avoid XSS vulnerability
1075
//
1076
function sanitize_sort_by($x) {
1077
    switch($x) {
1078
    case 'expavg_credit':
1079
    case 'total_credit':
1080
        return;
1081
    default:
0 ignored issues
show
DEFAULT keyword must be indented 4 spaces from SWITCH keyword
Loading history...
DEFAULT case must have a breaking statement
Loading history...
1082
        error_page('bad sort_by');
1083
    }
1084
}
1085
1086
function flops_to_credit($f) {
1087
    return $f*(200/86400e9);
1088
}
1089
1090
function credit_to_gflop_hours($c) {
1091
    return $c/(200/24);
1092
}
1093
1094
function do_download($path) {
1095
    $name=basename($path);
1096
    header('Content-Description: File Transfer');
1097
    header('Content-Type: application/octet-stream');
1098
    header('Content-Disposition: attachment; filename='.$name);
1099
    header('Content-Transfer-Encoding: binary');
1100
    header('Expires: 0');
1101
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1102
    header('Pragma: public');
1103
    header('Content-Length: ' . filesize($path));
1104
    flush();
1105
    readfile($path);
1106
}
1107
1108
// if have SSL but not using it, redirect
1109
//
1110
function redirect_to_secure_url() {
1111
    if (defined('SECURE_URL_BASE')
1112
        && strstr(SECURE_URL_BASE, "https://")
1113
        && !is_https()
1114
    ) {
1115
        Header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
0 ignored issues
show
Calls to inbuilt PHP functions must be lowercase; expected "header" but found "Header"
Loading history...
1116
        exit;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1117
    }
1118
}
1119
1120
if (php_sapi_name() != "cli") {
1121
    redirect_to_secure_url();
1122
}
1123
1124
function badges_string($is_user, $item, $height) {
1125
    if (DISABLE_BADGES) return null;
1126
    if ($is_user) {
1127
        $bus = BoincBadgeUser::enum("user_id=$item->id");
1128
    } else {
1129
        $bus = BoincBadgeTeam::enum("team_id=$item->id");
1130
    }
1131
    if (!$bus) return null;
1132
    $x = "";
1133
    foreach ($bus as $bu) {
1134
        $badge = BoincBadge::lookup_id($bu->badge_id);
1135
        $x .= "<img title=\"$badge->title\" valign=top height=$height src=$badge->image_url> ";
1136
    }
1137
    return $x;
1138
}
1139
1140
function show_badges_row($is_user, $item) {
1141
    if (BADGE_HEIGHT_LARGE == 0) return;
0 ignored issues
show
The condition BADGE_HEIGHT_LARGE == 0 is always false.
Loading history...
1142
    $x = badges_string($is_user, $item, BADGE_HEIGHT_LARGE);
1143
    if ($x) {
1144
        row2("Badges", $x);
1145
    }
1146
}
1147
1148
// If this request is from a BOINC client, return its version as MMmmRR.
1149
// Otherwise return 0.
1150
// Format of user agent string is "BOINC client (windows_x86_64 7.3.17)"
1151
//
1152
function boinc_client_version(){
1153
    if (!array_key_exists('HTTP_USER_AGENT', $_SERVER)) return 0;
1154
    $x = $_SERVER['HTTP_USER_AGENT'];
1155
    $e =  "/BOINC client [^ ]* (\d+).(\d+).(\d+)\)/";
0 ignored issues
show
Expected 1 space after "="; 2 found
Loading history...
1156
    if (preg_match($e, $x, $matches)) {
1157
        return $matches[1]*10000 + $matches[2]*100 + $matches[3];
1158
    }
1159
    return 0;
1160
}
1161
1162
// output a script for counting chars left in text field
1163
//
1164
function text_counter_script() {
1165
    echo "<script type=\"text/javascript\">
1166
        function text_counter(field, countfield, maxlimit) {
1167
            if (field.value.length > maxlimit) {
1168
                field.value =field.value.substring(0, maxlimit);
1169
            } else {
1170
                countfield.value = maxlimit - field.value.length
1171
            }
1172
        }
1173
        </script>
1174
    ";
1175
}
1176
1177
// return HTML for a textarea with chars-remaining counter.
1178
// Call text_counter_script() before using this.
1179
//
1180
function textarea_with_counter($name, $maxlen, $text) {
1181
    $rem_name = $name."_remaining";
1182
    return "<textarea name=\"$name\" class=\"form-control\" rows=3 id=\"$name\" onkeydown=\"text_counter(this.form.$name, this.form.$rem_name, $maxlen);\"
1183
        onkeyup=\"text_counter(this.form.$name, this.form.$rem_name, $maxlen);\">".$text."</textarea>
1184
        <br><input name=\"$rem_name\" type=\"text\" id=\"$rem_name\" value=\"".($maxlen-strlen($text))."\" size=\"3\" maxlength=\"3\" readonly> ".tra("characters remaining")
1185
    ;
0 ignored issues
show
Space found before semicolon; expected ");" but found ")
;"
Loading history...
1186
}
1187
1188
// convert number MMmmrr to string MM.mm.rr
1189
//
1190
function version_string_maj_min_rel($v) {
1191
    $maj = (int)($v/10000);
1192
    $v -= $maj*10000;
1193
    $min = (int)($v/100);
1194
    $v -= $min*100;
1195
    return sprintf("%d.%d.%d", $maj, $min, $v);
1196
}
1197
1198
function google_search_form($url) {
1199
    echo "
1200
        <nobr>
1201
        <form method=get action=\"https://google.com/search\">
1202
        <input type=hidden name=domains value=\"$url\">
1203
        <input type=hidden name=sitesearch value=\"$url\">
1204
        <input name=q size=20>
1205
        <input type=submit value=".tra("Search").">
1206
        </form>
1207
        </nobr>
1208
    ";
1209
}
1210
1211
// use the following around text with long lines,
1212
// to limit the width and make it more readable.
1213
//
1214
function text_start($width=640) {
1215
    echo sprintf("<div style=\"max-width: %dpx;\">\n", $width);
1216
}
1217
function text_end() {
1218
    echo "</div>\n";
1219
}
1220
1221
// express a size in terms of TB, GB etc.
1222
//
1223
function size_string($x) {
1224
    if ($x > TERA) {
1225
        return number_format($x/TERA, 2)." TB";
1226
    }
1227
    if ($x > GIGA) {
1228
        return number_format($x/GIGA, 2)." GB";
1229
    }
1230
    if ($x > MEGA) {
1231
        return number_format($x/MEGA, 2)." MB";
1232
    }
1233
    if ($x > KILO) {
1234
        return number_format($x/KILO, 2)." KB";
1235
    }
1236
    return "$x bytes";
1237
}
1238
1239
function cert_filename() {
1240
    return defined("CERT_FILENAME")?CERT_FILENAME:"cert1.php";
1241
}
1242
1243
// if user hasn't validated their email addr, tell them to
1244
//
1245
function check_validated_email($user) {
1246
    if (!$user->email_validated) {
1247
        page_head("Please validate your email address");
1248
        echo "
1249
            To post here, please
1250
            <a href=validate_email_addr.php>validate your email address<a>.
1251
        ";
1252
        page_tail();
1253
        exit;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1254
    }
1255
}
1256
1257
?>
1258