Pageadmin::handleDeletePage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
/*
4
    HCSF - A multilingual CMS and Shopsystem
5
    Copyright (C) 2014  Marcus Haase - [email protected]
6
7
    This program is free software: you can redistribute it and/or modify
8
    it under the terms of the GNU General Public License as published by
9
    the Free Software Foundation, either version 3 of the License, or
10
    (at your option) any later version.
11
12
    This program is distributed in the hope that it will be useful,
13
    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
    GNU General Public License for more details.
16
17
    You should have received a copy of the GNU General Public License
18
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
namespace HaaseIT\HCSF\Controller\Admin;
22
23
24
use HaaseIT\HCSF\UserPage;
25
use Zend\ServiceManager\ServiceManager;
26
27
/**
28
 * Class Pageadmin
29
 * @package HaaseIT\HCSF\Controller\Admin
30
 */
31
class Pageadmin extends Base
32
{
33
    /**
34
     * @var \HaaseIT\HCSF\HardcodedText
35
     */
36
    private $hardcodedtextcats;
37
38
    /**
39
     * Pageadmin constructor.
40
     * @param ServiceManager $serviceManager
41
     */
42
    public function __construct(ServiceManager $serviceManager)
43
    {
44
        parent::__construct($serviceManager);
45
        $this->hardcodedtextcats = $serviceManager->get('hardcodedtextcats');
46
    }
47
48
    /**
49
     *
50
     */
51
    public function preparePage()
52
    {
53
        $this->P = new \HaaseIT\HCSF\CorePage($this->serviceManager, [], 'admin/base.twig');
54
        $this->P->cb_pagetype = 'content';
55
        $this->P->cb_subnav = 'admin';
56
57
        $this->P->cb_customcontenttemplate = 'pageadmin';
58
59
        // adding language to page here
60
        if (filter_input(INPUT_GET, 'action') === 'insert_lang') {
61
            $this->insertLang();
62
        }
63
64
        $getaction = filter_input(INPUT_GET, 'action');
65
        if ($getaction === null) {
66
            $this->P->cb_customdata['pageselect'] = $this->showPageselect();
67
        } elseif (!empty(filter_input(INPUT_GET, 'page_key')) && ($getaction === 'edit' || $getaction === 'delete')) {
68
            if ($getaction === 'delete' && filter_input(INPUT_POST, 'delete') === 'do') {
69
                $this->handleDeletePage();
70
            } else { // edit or update page
71
                $this->handleEditPage();
72
            }
73
        } elseif ($getaction === 'addpage') {
74
            $this->handleAddPage();
75
        }
76
    }
77
78
    protected function handleDeletePage()
79
    {
80
        // delete and put message in customdata
81
        $Ptodelete = new UserPage($this->serviceManager, filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW), true);
82
        if ($Ptodelete->cb_id != NULL) {
83
            $Ptodelete->remove();
84
        } else {
85
            $this->helper->terminateScript($this->hardcodedtextcats->get('pageadmin_exception_pagetodeletenotfound'));
86
        }
87
        $this->P->cb_customdata['deleted'] = true;
88
    }
89
90
    protected function handleAddPage()
91
    {
92
        $aErr = [];
93
        if (filter_input(INPUT_POST, 'addpage') === 'do') {
94
            $sPagekeytoadd = trim(filter_input(INPUT_POST, 'pagekey', FILTER_SANITIZE_SPECIAL_CHARS));
95
96
            if (mb_substr($sPagekeytoadd, 0, 2) === '/_') {
97
                $aErr['reservedpath'] = true;
98
            } elseif (strlen($sPagekeytoadd) < 4) {
99
                $aErr['keytooshort'] = true;
100
            } else {
101
                $Ptoadd = new UserPage($this->serviceManager, $sPagekeytoadd, true);
102
                if ($Ptoadd->cb_id == NULL) {
103
                    if ($Ptoadd->insert($sPagekeytoadd)) {
104
                        $this->helper->redirectToPage('/_admin/pageadmin.html?page_key='.$sPagekeytoadd.'&action=edit');
105
                    } else {
106
                        $this->helper->terminateScript($this->hardcodedtextcats->get('pageadmin_exception_couldnotinsertpage'));
107
                    }
108
                } else {
109
                    $aErr['keyalreadyinuse'] = true;
110
                }
111
            }
112
            $this->P->cb_customdata['err'] = $aErr;
113
            unset($aErr);
114
        }
115
        $this->P->cb_customdata['showaddform'] = true;
116
    }
117
118
    /**
119
     * @return array
120
     */
121
    protected function showPageselect() {
122
        $aGroups = [];
123
        $adminpagegroups = $this->config->getCore('admin_page_groups');
124
        foreach ($adminpagegroups as $sValue) {
125
            $TMP = explode('|', $sValue);
126
            $aGroups[$TMP[0]] = $TMP[1];
127
        }
128
129
        $dbal = $this->serviceManager->get('dbal');
130
131
        /** @var \Doctrine\DBAL\Query\QueryBuilder $queryBuilder */
132
        $queryBuilder = $dbal->createQueryBuilder();
133
        $queryBuilder
134
            ->select('*')
135
            ->from('content_base')
136
            ->orderBy('cb_key')
137
        ;
138
        $statement = $queryBuilder->execute();
139
140
        while ($aResult = $statement->fetch()) {
141
            if (isset($aGroups[$aResult['cb_group']])) {
142
                $aTree[$aResult['cb_group']][] = $aResult;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aTree was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aTree = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
143
            } else {
144
                $aTree['_'][] = $aResult;
0 ignored issues
show
Bug introduced by
The variable $aTree does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
145
            }
146
        }
147
148
        foreach ($aGroups as $sKey => $sValue) {
149
            if (isset($aTree[$sKey])) {
150
                $aOptions_g[] = $sKey.'|'.$sValue;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aOptions_g was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aOptions_g = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
151
            }
152
        }
153
154
        return [
155
            'options_groups' => isset($aOptions_g) ? $aOptions_g : [],
156
            'tree' => isset($aTree) ? $aTree : [],
157
        ];
158
    }
159
160
    protected function insertLang()
161
    {
162
        $Ptoinsertlang = new UserPage(
163
            $this->serviceManager,
164
            filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
165
            true)
166
        ;
167
168
        if ($Ptoinsertlang->cb_id != NULL && $Ptoinsertlang->oPayload->cl_id == NULL) {
0 ignored issues
show
Bug introduced by
The property cl_id does not seem to exist in HaaseIT\HCSF\PagePayload.

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...
169
            $Ptoinsertlang->oPayload->insert($Ptoinsertlang->cb_id);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class HaaseIT\HCSF\PagePayload as the method insert() does only exist in the following sub-classes of HaaseIT\HCSF\PagePayload: HaaseIT\HCSF\UserPagePayload. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
170
            $this->helper->redirectToPage('/_admin/pageadmin.html?page_key='.$Ptoinsertlang->cb_key.'&action=edit');
171
        } else {
172
            $this->helper->terminateScript($this->hardcodedtextcats->get('pageadmin_exception_couldnotinsertlang'));
173
        }
174
    }
175
176
    protected function handleEditPage()
177
    {
178
        $requestpagekey = filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
179
        if ($requestpagekey !== null && $Ptoedit = new UserPage($this->serviceManager, $requestpagekey, true)) {
180
            if (filter_input(INPUT_POST, 'action_a') === 'true') {
181
                $Ptoedit = $this->updatePage($Ptoedit);
182
            }
183
            $this->P->cb_customdata['page'] = $Ptoedit;
184
            $this->P->cb_customdata['admin_page_types'] = $this->config->getCore('admin_page_types');
185
            $this->P->cb_customdata['admin_page_groups'] = $this->config->getCore('admin_page_groups');
186
            $this->P->cb_customdata['allow_page_from_file'] = $this->config->getCore('allow_pages_from_file');
187
            $aOptions = [''];
188
            $navigation = $this->config->getNavigation();
189
            foreach ($navigation as $sKey => $aValue) {
190
                if ($sKey === 'admin') {
191
                    continue;
192
                }
193
                $aOptions[] = $sKey;
194
            }
195
            $this->P->cb_customdata['subnavarea_options'] = $aOptions;
196
            unset($aOptions);
197
198
            // show archived versions of this page
199
            if ($Ptoedit->oPayload->cl_id != NULL) {
200
201
                $dbal = $this->serviceManager->get('dbal');
202
203
                /** @var \Doctrine\DBAL\Query\QueryBuilder $queryBuilder */
204
                $queryBuilder = $dbal->createQueryBuilder();
205
                $queryBuilder
206
                    ->select('*')
207
                    ->from('content_lang_archive')
208
                    ->where('cl_id = ?')
209
                    ->andWhere('cl_lang = ?')
210
                    ->setParameter(0, $Ptoedit->oPayload->cl_id)
0 ignored issues
show
Bug introduced by
The property cl_id does not seem to exist in HaaseIT\HCSF\PagePayload.

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...
211
                    ->setParameter(1, $this->config->getLang())
212
                    ->orderBy('cla_timestamp', 'DESC')
213
                ;
214
                $statement = $queryBuilder->execute();
215
                $iArchivedRows = $statement->rowCount();
216
217
                if ($iArchivedRows > 0) {
218
                    $aListSetting = [
219
                        ['title' => 'cla_timestamp', 'key' => 'cla_timestamp', 'width' => '15%', 'linked' => false,],
220
                        ['title' => 'cl_html', 'key' => 'cl_html', 'width' => '40%', 'linked' => false, 'escapehtmlspecialchars' => true,],
221
                        ['title' => 'cl_keywords', 'key' => 'cl_keywords', 'width' => '15%', 'linked' => false, 'escapehtmlspecialchars' => true,],
222
                        ['title' => 'cl_description', 'key' => 'cl_description', 'width' => '15%', 'linked' => false, 'escapehtmlspecialchars' => true,],
223
                        ['title' => 'cl_title', 'key' => 'cl_title', 'width' => '15%', 'linked' => false, 'escapehtmlspecialchars' => true,],
224
                    ];
225
                    $aData = $statement->fetchAll();
226
                    $this->P->cb_customdata['archived_list'] = \HaaseIT\Toolbox\Tools::makeListtable(
227
                        $aListSetting,
228
                        $aData,
229
                        $this->serviceManager->get('twig')
230
                    );
231
                }
232
            }
233
        } else {
234
            $this->helper->terminateScript($this->hardcodedtextcats->get('pageadmin_exception_pagenotfound'));
235
        }
236
    }
237
238
    protected function updatePage(UserPage $Ptoedit)
239
    {
240
        $purifier = false;
241
        if ($this->config->getCore('pagetext_enable_purifier')) {
242
            $purifier = $this->helper->getPurifier('page');
243
        }
244
245
        $Ptoedit->cb_html_from_file = false;
246
        if ($this->config->getCore('allow_pages_from_file')) {
247
            $htmlFromFile = filter_input(INPUT_POST, 'page_from_file', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
248
            if ($htmlFromFile == 'y') {
249
                $Ptoedit->cb_html_from_file = true;
250
            }
251
        }
252
253
        $Ptoedit->cb_pagetype = filter_input(INPUT_POST, 'page_type', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
254
        $Ptoedit->cb_group = filter_input(INPUT_POST, 'page_group', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
255
        $Ptoedit->cb_pageconfig = filter_input(INPUT_POST, 'page_config', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_NO_ENCODE_QUOTES);
256
        $Ptoedit->cb_subnav = filter_input(INPUT_POST, 'page_subnav', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
257
        $Ptoedit->purifier = $purifier;
0 ignored issues
show
Documentation Bug introduced by
It seems like $purifier can also be of type false. However, the property $purifier is declared as type object<HTMLPurifier>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
258
        $Ptoedit->write();
259
260
        if ($Ptoedit->oPayload->cl_id != NULL) {
0 ignored issues
show
Bug introduced by
The property cl_id does not seem to exist in HaaseIT\HCSF\PagePayload.

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...
261
            $Ptoedit->oPayload->cl_html = filter_input(INPUT_POST, 'page_html');
262
            $Ptoedit->oPayload->cl_title = filter_input(INPUT_POST, 'page_title', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
263
            $Ptoedit->oPayload->cl_description = filter_input(INPUT_POST, 'page_description', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
264
            $Ptoedit->oPayload->cl_keywords = filter_input(INPUT_POST, 'page_keywords', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
265
            $Ptoedit->oPayload->purifier = $purifier;
0 ignored issues
show
Bug introduced by
The property purifier does not seem to exist in HaaseIT\HCSF\PagePayload.

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...
266
            $Ptoedit->oPayload->write();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class HaaseIT\HCSF\PagePayload as the method write() does only exist in the following sub-classes of HaaseIT\HCSF\PagePayload: HaaseIT\HCSF\UserPagePayload. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
267
        }
268
269
        $Ptoedit = new UserPage(
270
            $this->serviceManager,
271
            filter_input(INPUT_GET, 'page_key', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
272
            true
273
        );
274
        $this->P->cb_customdata['updated'] = true;
275
276
        return $Ptoedit;
277
    }
278
}
279