Completed
Push — master ( 0aee47...def38b )
by Marcus
02:08
created

HCSF::init()   C

Complexity

Conditions 9
Paths 128

Size

Total Lines 49
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 49
rs 5.3846
cc 9
eloc 27
nc 128
nop 0
1
<?php
2
3
namespace HaaseIT\HCSF;
4
5
use Zend\ServiceManager\ServiceManager;
6
use HaaseIT\HCSF\Shop\Helper as SHelper;
7
8
class HCSF
9
{
10
    /**
11
     * @var ServiceManager
12
     */
13
    protected $serviceManager;
14
15
    /**
16
     * HCSF constructor.
17
     * @param string $basedir
18
     */
19
    public function __construct($basedir)
20
    {
21
        define('HCSF_BASEDIR', dirname(__DIR__).DIRECTORY_SEPARATOR);
22
        define('DB_ADDRESSFIELDS', 'cust_id, cust_no, cust_email, cust_corp, cust_name, cust_street, cust_zip, cust_town, cust_phone, cust_cellphone, cust_fax, cust_country, cust_group, cust_active, cust_emailverified, cust_tosaccepted, cust_cancellationdisclaimeraccepted');
23
        define('DB_ITEMFIELDS', 'itm_no, itm_name, itm_price, itm_vatid, itm_rg, itm_img, itm_group, itm_data, itm_weight, itml_name_override, itml_text1, itml_text2, itm_index');
24
        define('DB_ITEMGROUPFIELDS', 'itmg_no, itmg_name, itmg_img, itmgt_shorttext, itmgt_details');
25
        define('FILE_PAYPALLOG', 'ipnlog.txt');
26
        define('CLI', php_sapi_name() === 'cli');
27
28
        define("PATH_BASEDIR", $basedir.DIRECTORY_SEPARATOR);
29
        define("PATH_LOGS", PATH_BASEDIR.'hcsflogs/');
30
        define("PATH_CACHE", PATH_BASEDIR.'cache/');
31
        define("DIRNAME_TEMPLATECACHE", 'templates');
32
        define("PATH_TEMPLATECACHE", PATH_CACHE.DIRNAME_TEMPLATECACHE);
33
        define("PATH_PURIFIERCACHE", PATH_CACHE.'htmlpurifier/');
34
        define("DIRNAME_GLIDECACHE", 'glide');
35
        define("PATH_GLIDECACHE", PATH_CACHE.DIRNAME_GLIDECACHE);
36
37
        $foo = get_defined_constants();
0 ignored issues
show
Unused Code introduced by
$foo is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
38
39
        // set scale for bcmath
40
        bcscale(6);
41
    }
42
43
    public function init()
44
    {
45
        $this->serviceManager = new ServiceManager();
46
47
        if (!CLI) {
48
            $this->setupRequest();
49
        }
50
51
        HelperConfig::init();
52
        define("PATH_DOCROOT", PATH_BASEDIR.HelperConfig::$core['dirname_docroot']);
53
        if (HelperConfig::$core['debug']) {
54
            \HaaseIT\Toolbox\Tools::$bEnableDebug = true;
55
        }
56
57
        if (!CLI) {
58
            $this->setupSession();
59
        }
60
61
        date_default_timezone_set(HelperConfig::$core['defaulttimezone']);
62
63
        $this->setupHardcodedTextcats();
64
65
        $this->serviceManager->setFactory('db', function () {
66
            return null;
67
        });
68
69
        if (!HelperConfig::$core['maintenancemode'] || CLI) {
70
            $this->setupDB();
71
            $this->setupTextcats();
72
            HelperConfig::loadNavigation($this->serviceManager);
73
        }
74
75
        if (!CLI) {
76
            $this->setupTwig();
77
        }
78
79
        if (HelperConfig::$core['enable_module_shop']) {
80
            $this->serviceManager->setFactory('oItem', function (ServiceManager $serviceManager) {
81
                return new \HaaseIT\HCSF\Shop\Items($serviceManager);
82
            });
83
        }
84
85
        if (!CLI) {
86
            $router = new \HaaseIT\HCSF\Router($this->serviceManager);
87
            return $router->getPage();
88
        }
89
90
        return true;
91
    }
92
93
    protected function setupRequest()
0 ignored issues
show
Coding Style introduced by
setupRequest uses the super-global variable $_SERVER 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...
94
    {
95
        // PSR-7 Stuff
96
        // Init request object
97
        $this->serviceManager->setFactory('request', function () {
98
            $request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
99
100
            // cleanup request
101
            $requesturi = urldecode($request->getRequestTarget());
102
            $parsedrequesturi = substr($requesturi, strlen(dirname($_SERVER['PHP_SELF'])));
103
            if (substr($parsedrequesturi, 1, 1) !== '/') {
104
                $parsedrequesturi = '/'.$parsedrequesturi;
105
            }
106
            return $request->withRequestTarget($parsedrequesturi);
107
        });
108
    }
109
110
    protected function setupSession()
0 ignored issues
show
Coding Style introduced by
setupSession 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...
Coding Style introduced by
setupSession uses the super-global variable $_SESSION 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...
Coding Style introduced by
setupSession uses the super-global variable $_SERVER 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...
111
    {
112
        if (isset($_COOKIE['acceptscookies']) && HelperConfig::$core['enable_module_customer'] && $_COOKIE['acceptscookies'] === 'yes') {
113
            // Session handling
114
            // session.use_trans_sid wenn nötig aktivieren
115
            session_name('sid');
116
            // Session wenn nötig starten
117
            if (session_id() == '') {
118
                session_start();
119
            }
120
121
            // check if the stored ip and ua equals the clients, if not, reset. if not set at all, reset
122
            if (!empty($_SESSION['hijackprevention'])) {
123
                if (
124
                    $_SESSION['hijackprevention']['remote_addr'] != $_SERVER['REMOTE_ADDR']
125
                    ||
126
                    $_SESSION['hijackprevention']['user_agent'] != $_SERVER['HTTP_USER_AGENT']
127
                ) {
128
                    \session_regenerate_id();
129
                    \session_unset();
130
                }
131
            } else {
132
                \session_regenerate_id();
133
                \session_unset();
134
                $_SESSION['hijackprevention']['remote_addr'] = $_SERVER['REMOTE_ADDR'];
135
                $_SESSION['hijackprevention']['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
136
            }
137
        }
138
    }
139
140
    protected function setupHardcodedTextcats()
141
    {
142
        if (file_exists(HCSF_BASEDIR.'src/hardcodedtextcats/'.HelperConfig::$lang.'.php')) {
143
            $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/'.HelperConfig::$lang.'.php';
144
        } else {
145
            if (file_exists(HCSF_BASEDIR.'src/hardcodedtextcats/'.key(HelperConfig::$core['lang_available']).'.php')) {
146
                $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/'.key(HelperConfig::$core['lang_available']).'.php';
147
            } else {
148
                $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/de.php';
149
            }
150
        }
151
152
        HardcodedText::init($HT);
153
    }
154
155
    protected function setupDB()
156
    {
157
        $this->serviceManager->setFactory('dbal', function () {
158
            $config = new \Doctrine\DBAL\Configuration();
159
160
            $connectionParams = [
161
                'url' =>
162
                    HelperConfig::$secrets['db_type'].'://'
163
                    .HelperConfig::$secrets['db_user'].':'
164
                    .HelperConfig::$secrets['db_password'].'@'
165
                    .HelperConfig::$secrets['db_server'].'/'
166
                    .HelperConfig::$secrets['db_name'],
167
                'charset' => 'UTF8',
168
                'driverOptions' => [
169
                    \PDO::ATTR_EMULATE_PREPARES => false,
170
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
171
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
172
                ],
173
            ];
174
175
            return \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
176
        });
177
178
        $this->serviceManager->setFactory('db', function (ServiceManager $serviceManager) {
179
            return $serviceManager->get('dbal')->getWrappedConnection();
180
        });
181
    }
182
183
    protected function setupTextcats()
184
    {
185
        $this->serviceManager->setFactory('textcats', function (ServiceManager $serviceManager) {
186
            $langavailable = HelperConfig::$core['lang_available'];
187
            $textcats = new \HaaseIT\Toolbox\Textcat(
188
                HelperConfig::$lang,
189
                $serviceManager->get('db'),
190
                key($langavailable),
191
                HelperConfig::$core['textcatsverbose'],
192
                PATH_LOGS
193
            );
194
            $textcats->loadTextcats();
195
196
            return $textcats;
197
        });
198
    }
199
200
    protected function setupTwig()
201
    {
202
        $this->serviceManager->setFactory('twig', function (ServiceManager $serviceManager) {
203
            $loader = new \Twig_Loader_Filesystem([PATH_BASEDIR.'customviews', HCSF_BASEDIR.'src/views/']);
204
205
            $twig_options = [
206
                'autoescape' => false,
207
                'debug' => HelperConfig::$core['debug'] ? true : false,
208
            ];
209
            if (HelperConfig::$core['templatecache_enable'] &&
210
                is_dir(PATH_TEMPLATECACHE) && is_writable(PATH_TEMPLATECACHE)) {
211
                $twig_options['cache'] = PATH_TEMPLATECACHE;
212
            }
213
            $twig = new \Twig_Environment($loader, $twig_options);
214
215
            if (HelperConfig::$core['allow_parsing_of_page_content']) {
216
                $twig->addExtension(new \Twig_Extension_StringLoader());
217
            } else { // make sure, template_from_string is callable
218
                $twig->addFunction(new \Twig_SimpleFunction('template_from_string', '\HaaseIT\HCSF\Helper::reachThrough'));
219
            }
220
221
            if (!HelperConfig::$core['maintenancemode']) {
222
                $twig->addFunction(new \Twig_SimpleFunction('T', [$serviceManager->get('textcats'), 'T']));
223
            } else {
224
                $twig->addFunction(new \Twig_SimpleFunction('T', '\HaaseIT\HCSF\Helper::returnEmptyString'));
225
            }
226
227
            $twig->addFunction(new \Twig_SimpleFunction('HT', '\HaaseIT\HCSF\HardcodedText::get'));
228
            $twig->addFunction(new \Twig_SimpleFunction('gFF', '\HaaseIT\Toolbox\Tools::getFormField'));
229
            $twig->addFunction(new \Twig_SimpleFunction('ImgURL', '\HaaseIT\HCSF\Helper::getSignedGlideURL'));
230
            $twig->addFunction(new \Twig_SimpleFunction('callback', 'HaaseIT\HCSF\Helper::twigCallback'));
231
            $twig->addFunction(new \Twig_SimpleFunction('makeLinkHRefWithAddedGetVars', '\HaaseIT\Toolbox\Tools::makeLinkHRefWithAddedGetVars'));
232
            $twig->addFilter(new \Twig_SimpleFilter('decodehtmlentity', 'html_entity_decode'));
233
234
            return $twig;
235
        });
236
    }
237
238
    /**
239
     * @return ServiceManager
240
     */
241
    public function getServiceManager()
242
    {
243
        return $this->serviceManager;
244
    }
245
246
    /**
247
     * @param Page $P
248
     * @return array
249
     */
250
    public function generatePage(Page $P)
0 ignored issues
show
Coding Style introduced by
generatePage uses the super-global variable $_SERVER 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...
251
    {
252
        $requesturi = $this->serviceManager->get('request')->getRequestTarget();
253
254
        $aP = [
255
            'language' => HelperConfig::$lang,
256
            'pageconfig' => $P->cb_pageconfig,
257
            'pagetype' => $P->cb_pagetype,
258
            'subnavkey' => $P->cb_subnav,
259
            'requesturi' => $requesturi,
260
            'requesturiarray' => parse_url($requesturi),
261
            'locale_format_date' => HelperConfig::$core['locale_format_date'],
262
            'locale_format_date_time' => HelperConfig::$core['locale_format_date_time'],
263
            'maintenancemode' => HelperConfig::$core['maintenancemode'],
264
            'numberformat_decimals' => HelperConfig::$core['numberformat_decimals'],
265
            'numberformat_decimal_point' => HelperConfig::$core['numberformat_decimal_point'],
266
            'numberformat_thousands_seperator' => HelperConfig::$core['numberformat_thousands_seperator'],
267
            'customroottemplate' => $P->getCustomRootTemplate(),
268
            'headers' => $P->getHeaders(),
269
        ];
270
        if (HelperConfig::$core['enable_module_customer']) {
271
            $aP['isloggedin'] = \HaaseIT\HCSF\Customer\Helper::getUserData();
272
            $aP['enable_module_customer'] = true;
273
        }
274
        if (HelperConfig::$core['enable_module_shop']) {
275
            $aP['currency'] = HelperConfig::$shop['waehrungssymbol'];
276
            $aP['orderamounts'] = HelperConfig::$shop['orderamounts'];
277
            if (isset(HelperConfig::$shop['vat']['full'])) {
278
                $aP['vatfull'] = HelperConfig::$shop['vat']['full'];
279
            }
280
            if (isset(HelperConfig::$shop['vat']['reduced'])) {
281
                $aP['vatreduced'] = HelperConfig::$shop['vat']['reduced'];
282
            }
283
            if (isset(HelperConfig::$shop['custom_order_fields'])) {
284
                $aP['custom_order_fields'] = HelperConfig::$shop['custom_order_fields'];
285
            }
286
            $aP['enable_module_shop'] = true;
287
        }
288
        if (isset($P->cb_key)) {
289
            $aP['path'] = pathinfo($P->cb_key);
0 ignored issues
show
Bug introduced by
The property cb_key does not seem to exist in HaaseIT\HCSF\Page.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
290
        } else {
291
            $aP['path'] = pathinfo($aP['requesturi']);
292
        }
293
        if ($P->cb_customcontenttemplate != NULL) {
294
            $aP['customcontenttemplate'] = $P->cb_customcontenttemplate;
295
        }
296
        if ($P->cb_customdata != NULL) {
297
            $aP['customdata'] = $P->cb_customdata;
298
        }
299
        if (isset($_SERVER['HTTP_REFERER'])) {
300
            $aP['referer'] = $_SERVER['HTTP_REFERER'];
301
        }
302
303
        // if there is no subnav defined but there is a default subnav defined, use it
304
        // subnavkey can be used in the templates to find out, where we are
305
        if ((!isset($aP['subnavkey']) || $aP['subnavkey'] == '') && HelperConfig::$core['subnav_default'] != '') {
306
            $aP['subnavkey'] = HelperConfig::$core['subnav_default'];
307
            $P->cb_subnav = HelperConfig::$core['subnav_default'];
308
        }
309
        if ($P->cb_subnav != NULL && isset(HelperConfig::$navigation[$P->cb_subnav])) {
310
            $aP['subnav'] = HelperConfig::$navigation[$P->cb_subnav];
311
        }
312
313
        // Get page title, meta-keywords, meta-description
314
        $aP['pagetitle'] = $P->oPayload->getTitle();
315
        $aP['keywords'] = $P->oPayload->cl_keywords;
316
        $aP['description'] = $P->oPayload->cl_description;
317
318
        // Shopping cart infos
319
        if (HelperConfig::$core['enable_module_shop']) {
320
            $aP['cartinfo'] = SHelper::getShoppingcartData();
321
        }
322
323
        $aP['countrylist'][] = ' | ';
324
        foreach (HelperConfig::$countries['countries_' .HelperConfig::$lang] as $sKey => $sValue) {
325
            $aP['countrylist'][] = $sKey.'|'.$sValue;
326
        }
327
328
        if (
329
            HelperConfig::$core['enable_module_shop']
330
            && (
331
                $aP['pagetype'] === 'itemoverview'
332
                || $aP['pagetype'] === 'itemoverviewgrpd'
333
                || $aP['pagetype'] === 'itemdetail'
334
            )
335
        ) {
336
            $aP = SHelper::handleItemPage($this->serviceManager, $P, $aP);
337
        }
338
339
        $aP['content'] = $P->oPayload->cl_html;
340
341
        $aP['content'] = str_replace('@', '&#064;', $aP['content']); // Change @ to HTML Entity -> maybe less spam mails
342
343
        $aP['lang_available'] = HelperConfig::$core['lang_available'];
344
        $aP['lang_detection_method'] = HelperConfig::$core['lang_detection_method'];
345
        $aP['lang_by_domain'] = HelperConfig::$core['lang_by_domain'];
346
347
        if (HelperConfig::$core['debug']) {
348
            \HaaseIT\HCSF\Helper::getDebug($aP, $P);
349
            $aP['debugdata'] = \HaaseIT\Toolbox\Tools::$sDebug;
350
        }
351
352
        return $aP;
353
    }
354
}
355