Completed
Push — development ( f93eb8...ffa1a0 )
by Thomas
20s
created

htdocs/lib/common.inc.php (8 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/****************************************************************************
3
 * For license information see LICENSE.md
4
 *
5
 * sets up all necessary variables and handle template and database-things
6
 * also useful functions
7
 *
8
 * parameter: lang       get/post/cookie   used language
9
 * style      get/post/cookie   used style
10
 ****************************************************************************/
11
12
use Oc\Util\CBench;
13
14
if (isset($opt['rootpath'])) {
15
    $rootpath = $opt['rootpath'];
16
} else {
17
    if (isset($rootpath)) {
18
        $opt['rootpath'] = $rootpath;
19
    } else {
20
        $rootpath = './';
21
        $opt['rootpath'] = $rootpath;
22
    }
23
}
24
25
// we are in HTML-mode ... maybe plain (for CLI scripts)
26
global $interface_output, $bScriptExecution;
27
$interface_output = 'html';
28
29
// set default CSS
30
tpl_set_var('css', 'main.css');
31
32
//detecting errors
33
$error = false;
34
35
if (!isset($rootpath)) {
36
    $rootpath = './';
37
}
38
require_once __DIR__ . '/clicompatbase.inc.php';
39
40
// enforce http or https?
41
if (isset($opt['gui']) && $opt['gui'] == GUI_HTML) {
42
    if ($opt['page']['https']['mode'] == HTTPS_DISABLED) {
43
        if ($opt['page']['https']['active']) {
44
            header('Location: http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
45
        }
46
        $opt['page']['force_https_login'] = false;
47 View Code Duplication
    } else {
48
        if ($opt['page']['https']['mode'] == HTTPS_ENFORCED) {
49
            if (!$opt['page']['https']['active']) {
50
                header('Location: https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
51
            }
52
            $opt['page']['force_https_login'] = true;
53
        }
54
    }
55
}
56
57
// load domain specific settings
58
load_domain_settings();
59
60
// load HTML specific includes
61
$cookie = new \Oc\Session\SessionDataCookie();
62
63
//by default, use start template
64
if (!isset($tplname)) {
65
    $tplname = 'start';
66
}
67
68
//restore cookievars[]
69
load_cookie_settings();
70
71
//language changed?
72
if (isset($_POST['lang'])) {
73
    $lang = $_POST['lang'];
74
}
75
if (isset($_GET['lang'])) {
76
    $lang = $_GET['lang'];
77
}
78
79
//are there files for this language?
80
if (!file_exists(__DIR__ . '/../lang/' . $lang . '/')) {
81
    die('Critical Error: The specified language does not exist!');
82
}
83
84
//style changed?
85
if (isset($_POST['style'])) {
86
    $style = $_POST['style'];
87
}
88
if (isset($_GET['style'])) {
89
    $style = $_GET['style'];
90
}
91
92
//does the style exist?
93 View Code Duplication
if (!file_exists(__DIR__ . '/../lang/' . $lang . '/' . $style . '/')) {
94
    $style = 'ocstyle';
95
}
96
97 View Code Duplication
if (!file_exists(__DIR__ . '/../lang/' . $lang . '/' . $style . '/')) {
98
    die('Critical Error: The specified style does not exist!');
99
}
100
101
//set up the language path
102
if (!isset($langpath)) {
103
    $langpath = __DIR__ . '/../lang/' . $lang;
104
}
105
106
//set up the style path
107
if (!isset($stylepath)) {
108
    $stylepath = $langpath . '/' . $style;
109
}
110
111
//load gettext translation
112
load_gettext();
113
114
//open a databse connection
115
db_connect();
116
117
require_once __DIR__ . '/auth.inc.php';
118
require_once __DIR__ . '/../lib2/translate.class.php';
119
120
//load language specific strings
121
require_once $langpath . '/expressions.inc.php';
122
123
//set up the defaults for the main template
124
require_once $stylepath . '/varset.inc.php';
125
126
if ($dblink === false) {
127
    //error while connecting to the database
128
    $error = true;
129
130
    //set up error report
131
    tpl_set_var('error_msg', htmlspecialchars(mysql_error(), ENT_COMPAT, 'UTF-8'));
132
    tpl_set_var('tplname', $tplname);
133
    $tplname = 'error';
134
} else {
135
    //user authenification from cookie
136
    auth_user();
137
    if ($usr == false) {
138
        //no user logged in
139
        if (isset($_POST['target'])) {
140
            $target = $_POST['target'];
141
        } elseif (isset($_REQUEST['target'])) {
142
            $target = $_REQUEST['target'];
143
        } elseif (isset($_GET['target'])) {
144
            $target = $_GET['target'];
145
        } else {
146
            $target = '{target}';
147
        }
148
        $sLoggedOut = mb_ereg_replace('{target}', $target, $sLoggedOut);
149
        tpl_set_var('loginbox', $sLoggedOut);
150
        tpl_set_var(
151
            'login_url',
152
            ($opt['page']['https']['force_login'] ? $opt['page']['absolute_https_url'] : '') . 'login.php'
153
        );
154
    } else {
155
        //user logged in
156
        $sTmpString = mb_ereg_replace('{username}', $usr['username'], $sLoggedIn);
157
        tpl_set_var('loginbox', $sTmpString);
158
        unset($sTmpString);
159
    }
160
}
161
162
// are we Ocprop?
163
$ocpropping = isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Ocprop/') !== false;
164
165
// zeitmessung
166
$bScriptExecution = new CBench;
167
$bScriptExecution->start();
168
169
function load_domain_settings()
170
{
171
    global $opt, $style;
172
173
    $domain = $opt['page']['domain'];
174
175
    if (isset($opt['domain'][$domain]['style'])) {
176
        $style = $opt['domain'][$domain]['style'];
177
    }
178 View Code Duplication
    if (isset($opt['domain'][$domain]['cookiedomain'])) {
179
        $opt['cookie']['domain'] = $opt['domain'][$domain]['cookiedomain'];
180
    }
181
182
    set_common_domain_config($opt);
183
}
184
185
// get the language from a given shortage
186
// on success return the name, otherwise false
187
function db_LanguageFromShort($langCode)
188
{
189
    global $dblink, $locale;
190
191
    //no databse connection?
192
    if ($dblink === false) {
193
        return false;
194
    }
195
196
    //select the right record
197
    $rs = sql(
198
        "SELECT IFNULL(`sys_trans_text`.`text`, `languages`.`name`) AS `text`
199
        FROM `languages`
200
        LEFT JOIN `sys_trans`
201
          ON `languages`.`trans_id`=`sys_trans`.`id`
202
        LEFT JOIN `sys_trans_text`
203
          ON `sys_trans`.`id`=`sys_trans_text`.`trans_id`
204
          AND `sys_trans_text`.`lang`='&1'
205
        WHERE `languages`.`short`='&2'",
206
        $locale,
207
        $langCode
208
    );
209
    if (mysql_num_rows($rs) > 0) {
210
        $record = sql_fetch_array($rs);
211
212
        //return the language
213
        return $record['text'];
214
    }
215
    //language not found
216
    return false;
217
}
218
219
//get the stored settings and authentification data from the cookie
220
function load_cookie_settings()
221
{
222
    global $cookie, $lang, $style;
223
224
    //speach
225
    if ($cookie->is_set('lang')) {
226
        $lang = $cookie->get('lang');
227
    }
228
229
    //style
230
    if ($cookie->is_set('style')) {
231
        $style = $cookie->get('style');
232
    }
233
}
234
235
//store the cookie vars
236
function write_cookie_settings()
237
{
238
    global $cookie, $lang, $style;
239
240
    //language
241
    $cookie->set('lang', $lang);
242
243
    //style
244
    $cookie->set('style', $style);
245
246
    //send cookie
247
    $cookie->header();
248
}
249
250
//returns the cookie value, otherwise false
251
function get_cookie_setting($name)
252
{
253
    global $cookie;
254
255
    if ($cookie->is_set($name)) {
256
        return $cookie->get($name);
257
    }
258
259
    return false;
260
}
261
262
//sets the cookie value
263
function set_cookie_setting($name, $value)
264
{
265
    global $cookie;
266
    $cookie->set($name, $value);
267
}
268
269
//set a template replacement
270
//set no_eval true to prevent this contents from php-parsing.
271
//Important when replacing something that the user has posted
272
//in HTML code and could contain \<\? php-Code \?\>
273
/**
274
 * @param string $name
275
 * @param mixed $value
276
 * @param mixed $no_eval
277
 */
278
function tpl_set_var($name, $value, $no_eval = true)
279
{
280
    global $vars, $no_eval_vars;
281
    $vars[$name] = $value;
282
    $no_eval_vars[$name] = $no_eval;
283
}
284
285
//get a template replacement, otherwise false
286
function tpl_get_var($name)
287
{
288
    global $vars;
289
290
    if (isset($vars[$name])) {
291
        return $vars[$name];
292
    }
293
294
    return false;
295
}
296
297
//clear all template vars
298
function tpl_clear_vars()
0 ignored issues
show
tpl_clear_vars uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
299
{
300
    unset($GLOBALS['vars']);
301
    unset($GLOBALS['no_eval_vars']);
302
}
303
304
/**
305
 * page function replaces {functionsbox} in main template
306
 *
307
 * @param $id
308
 * @param $html_code
309
 */
310
function tpl_set_page_function($id, $html_code)
311
{
312
    global $page_functions;
313
314
    $page_functions[$id] = $html_code;
315
}
316
317
function tpl_unset_page_function($id)
318
{
319
    global $page_functions;
320
321
    unset($page_functions[$id]);
322
}
323
324
function tpl_clear_page_functions()
0 ignored issues
show
tpl_clear_page_functions uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
325
{
326
    unset($GLOBALS['page_functions']);
327
}
328
329
/**
330
 * see OcSmarty::acceptsAndPurifiesHtmlInput
331
 */
332
function tpl_acceptsAndPurifiesHtmlInput()
333
{
334
    header('X-XSS-Protection: 0');
335
}
336
337
/**
338
 * read the templates and echo it to the user
339
 *
340
 * @param bool $dbDisconnect
341
 */
342
function tpl_BuildTemplate($dbDisconnect = true)
0 ignored issues
show
tpl_BuildTemplate uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
343
{
344
    global $sql_debug, $sqldbg_cmdNo;
345
346
    if (isset($sql_debug) && $sql_debug) {
347
        if (!isset($sqldbg_cmdNo) || $sqldbg_cmdNo == 0) {
348
            echo 'No SQL commands on this page.';
349
        }
350
        die();
0 ignored issues
show
Coding Style Compatibility introduced by
The function tpl_BuildTemplate() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
351
    }
352
353
    //template handling vars
354
    global $style, $stylepath, $tplname, $vars, $langpath, $locale, $opt, $oc_nodeid, $translate, $usr;
355
    //language specific expression
356
    global $error_pagenotexist;
357
    //only for debbuging
358
    global $b, $bScriptExecution;
359
    // country dropdown
360
    global $tpl_usercountries;
361
362
    tpl_set_var('screen_css_time', filemtime(__DIR__ . '/../resource2/' . $style . '/css/style_screen.css'));
363
    tpl_set_var(
364
        'screen_msie_css_time',
365
        filemtime(__DIR__ . '/../resource2/' . $style . '/css/style_screen_msie.css')
366
    );
367
    tpl_set_var('print_css_time', filemtime(__DIR__ . '/../resource2/' . $style . '/css/style_print.css'));
368
369
    if (isset($bScriptExecution)) {
370
        $bScriptExecution->stop();
371
        tpl_set_var('scripttime', sprintf('%1.3f', $bScriptExecution->diff()));
372
    } else {
373
        tpl_set_var('scripttime', sprintf('%1.3f', 0));
374
    }
375
376
    tpl_set_var('sponsorbottom', $opt['page']['sponsor']['bottom']);
377
378 View Code Duplication
    if (isset($opt['locale'][$locale]['page']['subtitle1'])) {
379
        $opt['page']['subtitle1'] = $opt['locale'][$locale]['page']['subtitle1'];
380
    }
381 View Code Duplication
    if (isset($opt['locale'][$locale]['page']['subtitle2'])) {
382
        $opt['page']['subtitle2'] = $opt['locale'][$locale]['page']['subtitle2'];
383
    }
384
    tpl_set_var('opt_page_subtitle1', $opt['page']['subtitle1']);
385
    tpl_set_var('opt_page_subtitle2', $opt['page']['subtitle2']);
386
    tpl_set_var('opt_page_title', $opt['page']['title']);
387
388
    if ($opt['logic']['license']['disclaimer']) {
389 View Code Duplication
        if (isset($opt['locale'][$locale]['page']['license_url'])) {
390
            $lurl = $opt['locale'][$locale]['page']['license_url'];
391
        } else {
392
            $lurl = $opt['locale']['EN']['page']['license_url'];
393
        }
394
395 View Code Duplication
        if (isset($opt['locale'][$locale]['page']['license'])) {
396
            $ltext = $opt['locale'][$locale]['page']['license'];
397
        } else {
398
            $ltext = $opt['locale']['EN']['page']['license'];
399
        }
400
401
        $ltext = mb_ereg_replace('%1', $lurl, $ltext);
402
        $ltext = mb_ereg_replace('{site}', $opt['page']['sitename'], $ltext);
403
404
        $ld = '<p class="sidebar-maintitle">' . $translate->t('Datalicense', '', '', 0) . '</p>' .
405
            '<div style="margin:20px 0 16px 0; width:100%; text-align:center;">' . $ltext . '</div>';
406
        tpl_set_var('license_disclaimer', $ld);
407
    } else {
408
        tpl_set_var('license_disclaimer', '');
409
    }
410
411
    $bTemplateBuild = new CBench;
412
    $bTemplateBuild->start();
413
414
    //set {functionsbox}
415
    global $page_functions, $functionsbox_start_tag, $functionsbox_middle_tag, $functionsbox_end_tag;
416
417
    if (isset($page_functions)) {
418
        $functionsbox = $functionsbox_start_tag;
419
        foreach ($page_functions as $func) {
420
            if ($functionsbox != $functionsbox_start_tag) {
421
                $functionsbox .= $functionsbox_middle_tag;
422
            }
423
            $functionsbox .= $func;
424
        }
425
        $functionsbox .= $functionsbox_end_tag;
426
427
        tpl_set_var('functionsbox', $functionsbox);
428
    }
429
430
    /* prepare user country selection
431
     */
432
    $tpl_usercountries = [];
433
    $rsUserCountries = sql(
434
        "SELECT `countries_options`.`country`,
435
                        IF(`countries_options`.`nodeId`='&1', 1, IF(`countries_options`.`nodeId`!=0, 2, 3)) AS `group`,
436
                        IFNULL(`sys_trans_text`.`text`, `countries`.`name`) AS `name`
437
                   FROM `countries_options`
438
             INNER JOIN `countries` ON `countries_options`.`country`=`countries`.`short`
439
              LEFT JOIN `sys_trans` ON `countries`.`trans_id`=`sys_trans`.`id`
440
              LEFT JOIN `sys_trans_text` ON `sys_trans`.`id`=`sys_trans_text`.`trans_id` AND `sys_trans_text`.`lang`='&2'
441
                  WHERE `countries_options`.`display`=1
442
               ORDER BY `group` ASC,
443
                        IFNULL(`sys_trans_text`.`text`, `countries`.`name`) ASC",
444
        $oc_nodeid,
445
        $locale
446
    );
447
    while ($rUserCountries = sql_fetch_assoc($rsUserCountries)) {
448
        $tpl_usercountries[] = $rUserCountries;
449
    }
450
    sql_free_result($rsUserCountries);
451
452
    //include language specific expressions, so that they are available in the template code
453
    include $langpath . '/expressions.inc.php';
454
455
    //load main template
456
    tpl_set_var('backgroundimage', '<div id="bg1">&nbsp;</div><div id="bg2">&nbsp;</div>');
457
    tpl_set_var('bodystyle', '');
458
459
    if (isset($_REQUEST['print']) && $_REQUEST['print'] == 'y') {
460
        $sCode = read_file($stylepath . '/main_print.tpl.php');
461
    } else {
462
        if (isset($_REQUEST['popup']) && $_REQUEST['popup'] == 'y') {
463
            $sCode = read_file($stylepath . '/popup.tpl.php');
464
        } else {
465
            $sCode = read_file($stylepath . '/main.tpl.php');
466
        }
467
    }
468
    $sCode = '?>' . $sCode;
469
470
    //does template exist?
471
    if (!file_exists($stylepath . '/' . $tplname . '.tpl.php')) {
472
        //set up the error template
473
        $error = true;
474
        tpl_set_var('error_msg', htmlspecialchars($error_pagenotexist, ENT_COMPAT, 'UTF-8'));
475
        tpl_set_var('tplname', $tplname);
476
        $tplname = 'error';
477
    }
478
479
    //read the template
480
    $sTemplate = read_file($stylepath . '/' . $tplname . '.tpl.php');
481
    $sCode = mb_ereg_replace('{template}', $sTemplate, $sCode);
482
483
    //process translations
484
    $sCode = tpl_do_translation($sCode);
485
486
    //process the template replacements
487
    $sCode = tpl_do_replace($sCode);
488
489
    // fixing path issue
490
    $sCode = str_replace('lib2/smarty/ocplugins/', 'src/OcLegacy/SmartyPlugins/', $sCode);
491
492
    //store the cookie
493
    write_cookie_settings();
494
495
    //send http-no-caching-header
496
    http_write_no_cache();
497
498
    // write UTF8-Header
499
    header('Content-type: text/html; charset=utf-8');
500
501
    //run the template code
502
    eval($sCode);
0 ignored issues
show
The function tpl_BuildTemplate() contains an eval expression.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
503
504
    //disconnect the database
505
    if ($dbDisconnect) {
506
        db_disconnect();
507
    }
508
}
509
510
function http_write_no_cache()
511
{
512
    // HTTP/1.1
513
    header('Cache-Control: no-store, no-cache, must-revalidate');
514
    header('Cache-Control: post-check=0, pre-check=0', false);
515
    // HTTP/1.0
516
    header('Pragma: no-cache');
517
    // Date in the past
518
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
519
    // always modified
520
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
521
}
522
523
//redirect to another site to display, i.e. to view a cache after logging
524
/**
525
 * @param string $page
526
 */
527
function tpl_redirect($page)
528
{
529
    global $absolute_server_URI;
530
531
    write_cookie_settings();
532
    http_write_no_cache();
533
534
    if (!preg_match('/^https?:/i', $page)) {
535
        header('Location: ' . $absolute_server_URI . $page);
536
    } else {
537
        header('Location: ' . $page);
538
    }
539
540
    exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function tpl_redirect() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
541
}
542
543
//process the template replacements
544
//no_eval_replace - if true, variables will be replaced that are
545
//                  marked as "no_eval"
546
/**
547
 * @param string $str
548
 * @return string
549
 */
550
function tpl_do_replace($str)
551
{
552
    global $vars, $no_eval_vars;
553
554
    if (is_array($vars)) {
555
        foreach ($vars as $varname => $varvalue) {
556
            if ($no_eval_vars[$varname] == false) {
557
                $str = mb_ereg_replace('{' . $varname . '}', $varvalue, $str);
558
            } else {
559
                $replave_var_name = 'tpl_replace_var_' . $varname;
560
561
                global $$replave_var_name;
562
                $$replave_var_name = $varvalue;
563
564
                //replace using php-echo
565
                $str = mb_ereg_replace(
566
                    '{' . $varname . '}',
567
                    '<?php global $' . $replave_var_name . '; echo $tpl_replace_var_' . $varname . '; ?>',
568
                    $str
569
                );
570
            }
571
        }
572
    }
573
574
    return $str;
575
}
576
577
/**
578
 * @param string $tplnameError
579
 * @param string $msg
580
 */
581
function tpl_errorMsg($tplnameError, $msg)
582
{
583
    global $tplname;
584
585
    $tplname = 'error';
586
    tpl_set_var('error_msg', $msg);
587
    tpl_set_var('tplname', $tplnameError);
588
589
    tpl_BuildTemplate();
590
    exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function tpl_errorMsg() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
591
}
592
593
594
function load_gettext()
0 ignored issues
show
load_gettext uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
595
{
596
    global $cookie, $opt, $locale;
597
598
    $locale = isset($_REQUEST['locale']) ? $_REQUEST['locale'] : $cookie->get('locale');
599
    if (!isset($opt['locale'][$locale])) {
600
        $locale = $opt['template']['default']['locale'];
601
    }
602
    $opt['template']['locale'] = $locale;
603
604
    $cookie->set('locale', $opt['template']['locale'], $opt['template']['default']['locale']);
605
606
    bindtextdomain('messages', __DIR__ . '/../var/cache2/translate');
607
    set_php_locale();
608
    textdomain('messages');
609
}
610
611
/**
612
 * @param string $sCode
613
 * @return string
614
 */
615
function tpl_do_translation($sCode)
616
{
617
    global $opt, $style, $tplname;
618
619
    $sResultCode = '';
620
    $nCurrentPos = 0;
621
    while ($nCurrentPos < mb_strlen($sCode)) {
622
        $nStartOfHTML = mb_strpos($sCode, '?>', $nCurrentPos);
623
        if ($nStartOfHTML === false) {
624
            $sResultCode .= mb_substr($sCode, $nCurrentPos, mb_strlen($sCode) - $nCurrentPos);
625
            $nCurrentPos = mb_strlen($sCode);
626
        } else {
627
            $nEndOfHTML = mb_strpos($sCode, '<?', $nStartOfHTML);
628
            if ($nEndOfHTML === false) {
629
                $nEndOfHTML = mb_strlen($sCode);
630
            }
631
632
            $sResultCode .= mb_substr($sCode, $nCurrentPos, $nStartOfHTML - $nCurrentPos);
633
            $sHTMLCode = mb_substr($sCode, $nStartOfHTML, $nEndOfHTML - $nStartOfHTML);
634
            $sResultCode .= gettext_do_html($sHTMLCode);
635
636
            $nCurrentPos = $nEndOfHTML;
637
        }
638
    }
639
640
    return $sResultCode;
641
}
642
643
/**
644
 * @param string $sCode
645
 * @return string
646
 */
647
function gettext_do_html($sCode)
648
{
649
    $sResultCode = '';
650
    $nCurrentPos = 0;
651
    while ($nCurrentPos < mb_strlen($sCode)) {
652
        $nStartOf = mb_strpos($sCode, '{' . 't}', $nCurrentPos);
653
        if ($nStartOf === false) {
654
            $sResultCode .= mb_substr($sCode, $nCurrentPos, mb_strlen($sCode) - $nCurrentPos);
655
            $nCurrentPos = mb_strlen($sCode);
656
        } else {
657
            $nEndOf = mb_strpos($sCode, '{/t}', $nStartOf);
658
            if ($nEndOf === false) {
659
                $nEndOf = mb_strlen($sCode);
660
            } else {
661
                $nEndOf += 4;
662
            }
663
664
            $sResultCode .= mb_substr($sCode, $nCurrentPos, $nStartOf - $nCurrentPos);
665
            $sTransString = mb_substr($sCode, $nStartOf + 3, $nEndOf - $nStartOf - 3 - 4);
666
667
            $sResultCode .= t($sTransString);
668
669
            $nCurrentPos = $nEndOf;
670
        }
671
    }
672
673
    return $sResultCode;
674
}
675
676
/**
677
 * @param $str
678
 * @return string
679
 */
680
function t($str)
681
{
682
    global $translate;
683
684
    $str = $translate->t($str, '', basename(__FILE__), __LINE__);
685
    $args = func_get_args();
686
    for ($nIndex = count($args) - 1; $nIndex > 0; $nIndex--) {
687
        $str = str_replace('%' . $nIndex, $args[$nIndex], $str);
688
    }
689
690
    return $str;
691
}
692
693
/**
694
 * @param $text
695
 * @return string
696
 */
697 View Code Duplication
function t_prepare_text($text)
698
{
699
    $text = mb_ereg_replace("\t", ' ', $text);
700
    $text = mb_ereg_replace("\r", ' ', $text);
701
    $text = mb_ereg_replace("\n", ' ', $text);
702
    while (mb_strpos($text, '  ') !== false) {
703
        $text = mb_ereg_replace('  ', ' ', $text);
704
    }
705
706
    return $text;
707
}
708
709
/**
710
 * @return mixed|null|string
711
 */
712
function getUserCountry()
713
{
714
    global $opt, $cookie, $usr;
715
716
    // language specified in cookie?
717 View Code Duplication
    if ($cookie->is_set('usercountry')) {
718
        $sCountry = $cookie->get('usercountry', null);
719
        if ($sCountry != null) {
720
            return $sCountry;
721
        }
722
    }
723
724
    // user specified a country?
725
    if (isset($usr) && ($usr !== false)) {
726
        $sCountry = sqlValue("SELECT `country` FROM `user` WHERE `user_id`='" . ($usr['userid'] + 0) . "'", null);
727
        if ($sCountry != null) {
728
            return $sCountry;
729
        }
730
    }
731
732
    // default country of this language
733
    //
734
    // disabled: produces unexpected results on multi-domains without translation,
735
    // and will confusingly switch country when switching language  -- following 3.9.2015
736
    //
737
    // if (isset($opt['template']['locale']) && isset($opt['locale'][$opt['template']['locale']]['country']))
738
    //    return $opt['locale'][$opt['template']['locale']]['country'];
739
740
    // default country of installation (or domain)
741
    if (isset($opt['template']['default']['country'])) {
742
        return $opt['template']['default']['country'];
743
    }
744
745
    // country could not be determined by the above checks -> return "GB"
746
    return 'GB';
747
}
748
749
/**
750
 * external help embedding
751
 * pay attention to use only ' quotes in $text (escape other ')
752
 *
753
 * see corresponding function in lib2/common.inc.php
754
 * @param $ocPage
755
 * @return string
756
 */
757
function helppagelink($ocPage)
758
{
759
    global $opt, $locale, $translate;
760
761
    $help_locale = $locale;
762
    $rs = sql(
763
        "SELECT `helppage` FROM `helppages` WHERE `ocpage`='&1' AND `language`='&2'",
764
        $ocPage,
765
        $help_locale
766
    );
767
    if (mysql_num_rows($rs) == 0) {
768
        mysql_free_result($rs);
769
        $rs = sql(
770
            "SELECT `helppage` FROM `helppages` WHERE `ocpage`='&1' AND `language`='*'",
771
            $ocPage
772
        );
773
    }
774
    if (mysql_num_rows($rs) == 0) {
775
        mysql_free_result($rs);
776
        $rs = sql(
777
            "SELECT `helppage` FROM `helppages` WHERE `ocpage`='&1' AND `language`='&2'",
778
            $ocPage,
779
            $opt['template']['default']['fallback_locale']
780
        );
781
        if (mysql_num_rows($rs) > 0) {
782
            $help_locale = $opt['template']['default']['fallback_locale'];
783
        }
784
    }
785
786
    if (mysql_num_rows($rs) > 0) {
787
        $record = sql_fetch_array($rs);
788
        $helpPage = $record['helppage'];
789
    } else {
790
        $helpPage = '';
791
    }
792
    mysql_free_result($rs);
793
794
    $imgTitle = $translate->t('Instructions', '', basename(__FILE__), __LINE__);
795
    $imgTitle = "alt='" . $imgTitle . "' title='" . $imgTitle . "'";
796
797
    if (substr($helpPage, 0, 1) == '!') {
798
        return "<a class='nooutline' href='" . substr($helpPage, 1) . "' " . $imgTitle . " target='_blank'>";
799
    }
800
    if ($helpPage != '' && isset($opt['locale'][$help_locale]['helpwiki'])) {
801
        return "<a class='nooutline' href='" . $opt['locale'][$help_locale]['helpwiki'] .
802
            str_replace(' ', '_', $helpPage) . "' " . $imgTitle . " target='_blank'>";
803
    }
804
    
805
806
    return '';
807
}
808
809
function get_logtype_name($logtype, $language)
810
{
811
    return sqlValue(
812
        "SELECT IFNULL(`stt`.`text`, `log_types`.`en`)
813
         FROM `log_types`
814
         LEFT JOIN `sys_trans_text` `stt` ON `stt`.`trans_id`=`log_types`.`trans_id` AND `stt`.`lang`='" . sql_escape($language) . "'
815
         WHERE `log_types`.`id`='" . sql_escape($logtype) . "'",
816
        ''
817
    );
818
}
819