GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

TwigTpl::render()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 8
nop 2
1
<?php
2
3
/**
4
 * eduVPN - End-user friendly VPN.
5
 *
6
 * Copyright: 2016-2017, The Commons Conservancy eduVPN Programme
7
 * SPDX-License-Identifier: AGPL-3.0+
8
 */
9
10
namespace SURFnet\VPN\Common;
11
12
use RuntimeException;
13
use Twig_Environment;
14
use Twig_Extensions_Extension_I18n;
15
use Twig_Loader_Filesystem;
16
use Twig_SimpleFilter;
17
18
class TwigTpl implements TplInterface
19
{
20
    /** @var string */
21
    private $localeDir;
22
23
    /** @var string */
24
    private $appName;
25
26
    /** @var Twig_Environment */
27
    private $twig;
28
29
    /** @var array */
30
    private $defaultVariables;
31
32
    /**
33
     * Create TwigTemplateManager.
34
     *
35
     * @param array  $templateDirs template directories to look in where later
36
     *                             paths override the earlier paths
37
     * @param string $cacheDir     the writable directory to store the cache
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cacheDir not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
38
     */
39
    public function __construct(array $templateDirs, $localeDir, $appName, $cacheDir = null)
40
    {
41
        $existingTemplateDirs = [];
42
        foreach ($templateDirs as $templateDir) {
43
            if (false !== is_dir($templateDir)) {
44
                $existingTemplateDirs[] = $templateDir;
45
            }
46
        }
47
        $existingTemplateDirs = array_reverse($existingTemplateDirs);
48
49
        $environmentOptions = [
50
            'strict_variables' => true,
51
        ];
52
53
        if (null !== $cacheDir) {
54
            if (false === is_dir($cacheDir)) {
55
                if (false === @mkdir($cacheDir, 0700, true)) {
56
                    throw new RuntimeException('unable to create template cache directory');
57
                }
58
            }
59
            $environmentOptions['cache'] = $cacheDir;
60
        }
61
        $this->localeDir = $localeDir;
62
        $this->appName = $appName;
63
        $this->twig = new Twig_Environment(
64
            new Twig_Loader_Filesystem(
65
                $existingTemplateDirs
66
            ),
67
            $environmentOptions
68
        );
69
70
        $this->defaultVariables = [];
71
    }
72
73
    public function setDefault(array $templateVariables)
74
    {
75
        $this->defaultVariables = $templateVariables;
76
    }
77
78
    public function addDefault(array $templateVariables)
79
    {
80
        $this->defaultVariables = array_merge(
81
            $this->defaultVariables, $templateVariables
82
        );
83
    }
84
85
    public function setI18n($languageStr, $localeDir)
86
    {
87
        putenv(sprintf('LC_ALL=%s', $languageStr));
0 ignored issues
show
Security Other Vulnerability introduced by
sprintf('LC_ALL=%s', $languageStr) can contain request data and is used in security-relevant context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_COOKIE, and $uiLanguage is assigned
    in src/TwigTpl.php on line 134
  2. $uiLanguage is passed to TwigTpl::setI18n()
    in src/TwigTpl.php on line 139
  3. $languageStr is passed through sprintf()
    in src/TwigTpl.php on line 87

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
88
89
        if (false === setlocale(LC_ALL, [$languageStr, sprintf('%s.UTF-8', $languageStr)])) {
90
            throw new RuntimeException(sprintf('unable to set locale "%s"', $languageStr));
91
        }
92
93
        if ($localeDir !== bindtextdomain($this->appName, $localeDir)) {
94
            throw new RuntimeException('unable to bind text domain');
95
        }
96
97
        if (!is_string(bind_textdomain_codeset($this->appName, 'UTF-8'))) {
98
            throw new RuntimeException('unable to bind text domain codeset');
99
        }
100
101
        if ($this->appName !== textdomain($this->appName)) {
102
            throw new RuntimeException('unable to set text domain');
103
        }
104
105
        $this->twig->addExtension(new Twig_Extensions_Extension_I18n());
106
    }
107
108
    public function addFilter(Twig_SimpleFilter $filter)
109
    {
110
        $this->twig->addFilter($filter);
111
    }
112
113
    /**
114
     * Render the template.
115
     *
116
     * @param string $templateName      the name of the template
117
     * @param array  $templateVariables the variables to be used in the
118
     *                                  template
119
     *
120
     * @return string the rendered template
121
     */
122
    public function render($templateName, array $templateVariables)
0 ignored issues
show
Coding Style introduced by
render uses the super-global variable $_COOKIE 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...
123
    {
124
        $uiLanguage = 'en_US';
125
        // determine default language
126
        if (array_key_exists('supportedLanguages', $this->defaultVariables)) {
127
            // take the first language of the supported languages as the default
128
            $uiLanguage = array_keys($this->defaultVariables['supportedLanguages'])[0];
129
        }
130
131
        if (array_key_exists('uiLanguage', $_COOKIE)) {
132
            if (array_key_exists('supportedLanguages', $this->defaultVariables)) {
133
                if (array_key_exists($_COOKIE['uiLanguage'], $this->defaultVariables['supportedLanguages'])) {
134
                    $uiLanguage = $_COOKIE['uiLanguage'];
135
                }
136
            }
137
        }
138
139
        $this->setI18n($uiLanguage, $this->localeDir);
140
        $templateVariables = array_merge($this->defaultVariables, $templateVariables);
141
142
        return $this->twig->render(
143
            sprintf(
144
                '%s.twig',
145
                $templateName
146
            ),
147
            $templateVariables
148
        );
149
    }
150
}
151