Completed
Push — master ( 6c2a60...7d299e )
by Marcus
03:23
created

HCSF::setupDB()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 27
rs 8.8571
cc 1
eloc 18
nc 1
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
    public function __construct()
16
    {
17
        define('HCSF_BASEDIR', dirname(__DIR__).DIRECTORY_SEPARATOR);
18
        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');
19
        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');
20
        define('DB_ITEMGROUPFIELDS', 'itmg_no, itmg_name, itmg_img, itmgt_shorttext, itmgt_details');
21
        define('FILE_PAYPALLOG', 'ipnlog.txt');
22
23
        // set scale for bcmath
24
        bcscale(6);
25
    }
26
27
    public function init()
28
    {
29
        $this->serviceManager = new ServiceManager();
30
31
        $this->setupRequest();
32
33
        HelperConfig::init();
34
        if (HelperConfig::$core['debug']) {
35
            \HaaseIT\Toolbox\Tools::$bEnableDebug = true;
36
        }
37
38
        $this->setupSession();
39
40
        date_default_timezone_set(HelperConfig::$core['defaulttimezone']);
41
42
        $this->setupHardcodedTextcats();
43
44
        $this->serviceManager->setFactory('db', function () {
45
            return null;
46
        });
47
48
        if (!HelperConfig::$core['maintenancemode']) {
49
            $this->setupDB();
50
            $this->setupTextcats();
51
            HelperConfig::loadNavigation($this->serviceManager);
52
        }
53
54
        $this->setupTwig();
55
56
        if (HelperConfig::$core['enable_module_shop']) {
57
            $this->serviceManager->setFactory('oItem', function (ServiceManager $serviceManager) {
58
                return new \HaaseIT\HCSF\Shop\Items($serviceManager);
59
            });
60
        }
61
62
        $router = new \HaaseIT\HCSF\Router($this->serviceManager);
63
        return $router->getPage();
64
    }
65
66
    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...
67
    {
68
        // PSR-7 Stuff
69
        // Init request object
70
        $this->serviceManager->setFactory('request', function () {
71
            $request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();
72
73
            // cleanup request
74
            $requesturi = urldecode($request->getRequestTarget());
75
            $parsedrequesturi = substr($requesturi, strlen(dirname($_SERVER['PHP_SELF'])));
76
            if (substr($parsedrequesturi, 1, 1) !== '/') {
77
                $parsedrequesturi = '/'.$parsedrequesturi;
78
            }
79
            return $request->withRequestTarget($parsedrequesturi);
80
        });
81
    }
82
83
    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...
84
    {
85
        if (isset($_COOKIE['acceptscookies']) && HelperConfig::$core['enable_module_customer'] && $_COOKIE['acceptscookies'] === 'yes') {
86
            // Session handling
87
            // session.use_trans_sid wenn nötig aktivieren
88
            session_name('sid');
89
            // Session wenn nötig starten
90
            if (session_id() == '') {
91
                session_start();
92
            }
93
94
            // check if the stored ip and ua equals the clients, if not, reset. if not set at all, reset
95
            if (!empty($_SESSION['hijackprevention'])) {
96
                if (
97
                    $_SESSION['hijackprevention']['remote_addr'] != $_SERVER['REMOTE_ADDR']
98
                    ||
99
                    $_SESSION['hijackprevention']['user_agent'] != $_SERVER['HTTP_USER_AGENT']
100
                ) {
101
                    \session_regenerate_id();
102
                    \session_unset();
103
                }
104
            } else {
105
                \session_regenerate_id();
106
                \session_unset();
107
                $_SESSION['hijackprevention']['remote_addr'] = $_SERVER['REMOTE_ADDR'];
108
                $_SESSION['hijackprevention']['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
109
            }
110
        }
111
    }
112
113
    protected function setupHardcodedTextcats()
114
    {
115
        if (file_exists(HCSF_BASEDIR.'src/hardcodedtextcats/'.HelperConfig::$lang.'.php')) {
116
            $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/'.HelperConfig::$lang.'.php';
117
        } else {
118
            if (file_exists(HCSF_BASEDIR.'src/hardcodedtextcats/'.key(HelperConfig::$core['lang_available']).'.php')) {
119
                $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/'.key(HelperConfig::$core['lang_available']).'.php';
120
            } else {
121
                $HT = require HCSF_BASEDIR.'src/hardcodedtextcats/de.php';
122
            }
123
        }
124
125
        HardcodedText::init($HT);
126
    }
127
128
    protected function setupDB()
129
    {
130
        $this->serviceManager->setFactory('dbal', function () {
131
            $config = new \Doctrine\DBAL\Configuration();
132
133
            $connectionParams = [
134
                'url' =>
135
                    HelperConfig::$secrets['db_type'].'://'
136
                    .HelperConfig::$secrets['db_user'].':'
137
                    .HelperConfig::$secrets['db_password'].'@'
138
                    .HelperConfig::$secrets['db_server'].'/'
139
                    .HelperConfig::$secrets['db_name'],
140
                'charset' => 'UTF8',
141
                'driverOptions' => [
142
                    \PDO::ATTR_EMULATE_PREPARES => false,
143
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
144
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
145
                ],
146
            ];
147
148
            return \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
149
        });
150
151
        $this->serviceManager->setFactory('db', function (ServiceManager $serviceManager) {
152
            return $serviceManager->get('dbal')->getWrappedConnection();
153
        });
154
    }
155
156
    protected function setupTextcats()
157
    {
158
        $this->serviceManager->setFactory('textcats', function (ServiceManager $serviceManager) {
159
            $langavailable = HelperConfig::$core['lang_available'];
160
            $textcats = new \HaaseIT\Toolbox\Textcat(
161
                HelperConfig::$lang,
162
                $serviceManager->get('db'),
163
                key($langavailable),
164
                HelperConfig::$core['textcatsverbose'],
165
                PATH_LOGS
166
            );
167
            $textcats->loadTextcats();
168
169
            return $textcats;
170
        });
171
    }
172
173
    protected function setupTwig()
174
    {
175
        $this->serviceManager->setFactory('twig', function (ServiceManager $serviceManager) {
176
            $loader = new \Twig_Loader_Filesystem([PATH_BASEDIR.'customviews', HCSF_BASEDIR.'src/views/']);
177
178
            $twig_options = [
179
                'autoescape' => false,
180
                'debug' => HelperConfig::$core['debug'] ? true : false,
181
            ];
182
            if (HelperConfig::$core['templatecache_enable'] &&
183
                is_dir(PATH_TEMPLATECACHE) && is_writable(PATH_TEMPLATECACHE)) {
184
                $twig_options['cache'] = PATH_TEMPLATECACHE;
185
            }
186
            $twig = new \Twig_Environment($loader, $twig_options);
187
188
            if (HelperConfig::$core['allow_parsing_of_page_content']) {
189
                $twig->addExtension(new \Twig_Extension_StringLoader());
190
            } else { // make sure, template_from_string is callable
191
                $twig->addFunction(new \Twig_SimpleFunction('template_from_string', '\HaaseIT\HCSF\Helper::reachThrough'));
192
            }
193
194
            if (!HelperConfig::$core['maintenancemode']) {
195
                $twig->addFunction(new \Twig_SimpleFunction('T', [$serviceManager->get('textcats'), 'T']));
196
            } else {
197
                $twig->addFunction(new \Twig_SimpleFunction('T', '\HaaseIT\HCSF\Helper::returnEmptyString'));
198
            }
199
200
            $twig->addFunction(new \Twig_SimpleFunction('HT', '\HaaseIT\HCSF\HardcodedText::get'));
201
            $twig->addFunction(new \Twig_SimpleFunction('gFF', '\HaaseIT\Toolbox\Tools::getFormField'));
202
            $twig->addFunction(new \Twig_SimpleFunction('ImgURL', '\HaaseIT\HCSF\Helper::getSignedGlideURL'));
203
            $twig->addFunction(new \Twig_SimpleFunction('callback', 'HaaseIT\HCSF\Helper::twigCallback'));
204
            $twig->addFunction(new \Twig_SimpleFunction('makeLinkHRefWithAddedGetVars', '\HaaseIT\Toolbox\Tools::makeLinkHRefWithAddedGetVars'));
205
            $twig->addFilter(new \Twig_SimpleFilter('decodehtmlentity', 'html_entity_decode'));
206
207
            return $twig;
208
        });
209
    }
210
211
    /**
212
     * @return mixed
213
     */
214
    public function getServiceManager()
215
    {
216
        return $this->serviceManager;
217
    }
218
219
    /**
220
     * @param Page $P
221
     * @return array
222
     */
223
    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...
224
    {
225
        $requesturi = $this->serviceManager->get('request')->getRequestTarget();
226
227
        $aP = [
228
            'language' => HelperConfig::$lang,
229
            'pageconfig' => $P->cb_pageconfig,
230
            'pagetype' => $P->cb_pagetype,
231
            'subnavkey' => $P->cb_subnav,
232
            'requesturi' => $requesturi,
233
            'requesturiarray' => parse_url($requesturi),
234
            'locale_format_date' => HelperConfig::$core['locale_format_date'],
235
            'locale_format_date_time' => HelperConfig::$core['locale_format_date_time'],
236
            'maintenancemode' => HelperConfig::$core['maintenancemode'],
237
            'numberformat_decimals' => HelperConfig::$core['numberformat_decimals'],
238
            'numberformat_decimal_point' => HelperConfig::$core['numberformat_decimal_point'],
239
            'numberformat_thousands_seperator' => HelperConfig::$core['numberformat_thousands_seperator'],
240
            'customroottemplate' => $P->getCustomRootTemplate(),
241
            'headers' => $P->getHeaders(),
242
        ];
243
        if (HelperConfig::$core['enable_module_customer']) {
244
            $aP['isloggedin'] = \HaaseIT\HCSF\Customer\Helper::getUserData();
245
            $aP['enable_module_customer'] = true;
246
        }
247
        if (HelperConfig::$core['enable_module_shop']) {
248
            $aP['currency'] = HelperConfig::$shop['waehrungssymbol'];
249
            $aP['orderamounts'] = HelperConfig::$shop['orderamounts'];
250
            if (isset(HelperConfig::$shop['vat']['full'])) {
251
                $aP['vatfull'] = HelperConfig::$shop['vat']['full'];
252
            }
253
            if (isset(HelperConfig::$shop['vat']['reduced'])) {
254
                $aP['vatreduced'] = HelperConfig::$shop['vat']['reduced'];
255
            }
256
            if (isset(HelperConfig::$shop['custom_order_fields'])) {
257
                $aP['custom_order_fields'] = HelperConfig::$shop['custom_order_fields'];
258
            }
259
            $aP['enable_module_shop'] = true;
260
        }
261
        if (isset($P->cb_key)) {
262
            $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...
263
        } else {
264
            $aP['path'] = pathinfo($aP['requesturi']);
265
        }
266
        if ($P->cb_customcontenttemplate != NULL) {
267
            $aP['customcontenttemplate'] = $P->cb_customcontenttemplate;
268
        }
269
        if ($P->cb_customdata != NULL) {
270
            $aP['customdata'] = $P->cb_customdata;
271
        }
272
        if (isset($_SERVER['HTTP_REFERER'])) {
273
            $aP['referer'] = $_SERVER['HTTP_REFERER'];
274
        }
275
276
        // if there is no subnav defined but there is a default subnav defined, use it
277
        // subnavkey can be used in the templates to find out, where we are
278
        if ((!isset($aP['subnavkey']) || $aP['subnavkey'] == '') && HelperConfig::$core['subnav_default'] != '') {
279
            $aP['subnavkey'] = HelperConfig::$core['subnav_default'];
280
            $P->cb_subnav = HelperConfig::$core['subnav_default'];
281
        }
282
        if ($P->cb_subnav != NULL && isset(HelperConfig::$navigation[$P->cb_subnav])) {
283
            $aP['subnav'] = HelperConfig::$navigation[$P->cb_subnav];
284
        }
285
286
        // Get page title, meta-keywords, meta-description
287
        $aP['pagetitle'] = $P->oPayload->getTitle();
288
        $aP['keywords'] = $P->oPayload->cl_keywords;
289
        $aP['description'] = $P->oPayload->cl_description;
290
291
        // TODO: Add head scripts to DB
292
        //if (isset($P["head_scripts"]) && $P["head_scripts"] != '') $aP["head_scripts"] = $P["head_scripts"];
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
293
294
        // Shopping cart infos
295
        if (HelperConfig::$core['enable_module_shop']) {
296
            $aP['cartinfo'] = SHelper::getShoppingcartData();
297
        }
298
299
        $aP['countrylist'][] = ' | ';
300
        foreach (HelperConfig::$countries['countries_' .HelperConfig::$lang] as $sKey => $sValue) {
301
            $aP['countrylist'][] = $sKey.'|'.$sValue;
302
        }
303
304
        if (
305
            HelperConfig::$core['enable_module_shop']
306
            && (
307
                $aP['pagetype'] === 'itemoverview'
308
                || $aP['pagetype'] === 'itemoverviewgrpd'
309
                || $aP['pagetype'] === 'itemdetail'
310
            )
311
        ) {
312
            $aP = SHelper::handleItemPage($this->serviceManager, $P, $aP);
313
        }
314
315
        $aP['content'] = $P->oPayload->cl_html;
316
317
        $aP['content'] = str_replace('@', '&#064;', $aP['content']); // Change @ to HTML Entity -> maybe less spam mails
318
319
        $aP['lang_available'] = HelperConfig::$core['lang_available'];
320
        $aP['lang_detection_method'] = HelperConfig::$core['lang_detection_method'];
321
        $aP['lang_by_domain'] = HelperConfig::$core['lang_by_domain'];
322
323
        if (HelperConfig::$core['debug']) {
324
            \HaaseIT\HCSF\Helper::getDebug($aP, $P);
325
            $aP['debugdata'] = \HaaseIT\Toolbox\Tools::$sDebug;
326
        }
327
328
        return $aP;
329
    }
330
}