Completed
Pull Request — develop (#534)
by Agel_Nash
06:46 queued 01:24
created

save_tmplvars.processor.php ➔ saveTemplateVarAccess()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 19
nc 12
nop 0
dl 0
loc 32
rs 8.439
c 0
b 0
f 0
1
<?php
2
if( ! defined('IN_MANAGER_MODE') || IN_MANAGER_MODE !== true) {
3
    die("<b>INCLUDE_ORDERING_ERROR</b><br /><br />Please use the EVO Content Manager instead of accessing this file directly.");
4
}
5
if (!$modx->hasPermission('save_template')) {
6
    $modx->webAlertAndQuit($_lang["error_no_privileges"]);
7
}
8
9
$id = (int)$_POST['id'];
10
$name = $modx->db->escape(trim($_POST['name']));
11
$description = $modx->db->escape($_POST['description']);
12
$caption = $modx->db->escape($_POST['caption']);
13
$type = $modx->db->escape($_POST['type']);
14
$elements = $modx->db->escape($_POST['elements']);
15
$default_text = $modx->db->escape($_POST['default_text']);
16
$rank = isset ($_POST['rank']) ? $modx->db->escape($_POST['rank']) : 0;
17
$display = $modx->db->escape($_POST['display']);
18
$params = $modx->db->escape($_POST['params']);
19
$locked = $_POST['locked'] == 'on' ? 1 : 0;
20
$origin = isset($_REQUEST['or']) ? (int)$_REQUEST['or'] : 76;
21
$originId = isset($_REQUEST['oid']) ? (int)$_REQUEST['oid'] : null;
22
$currentdate = time() + $modx->config['server_offset_time'];
23
24
//Kyle Jaebker - added category support
25 View Code Duplication
if (empty($_POST['newcategory']) && $_POST['categoryid'] > 0) {
26
    $categoryid = (int)$_POST['categoryid'];
27
} elseif (empty($_POST['newcategory']) && $_POST['categoryid'] <= 0) {
28
    $categoryid = 0;
29
} else {
30
    include_once(MODX_MANAGER_PATH . 'includes/categories.inc.php');
31
    $categoryid = checkCategory($_POST['newcategory']);
32
    if (!$categoryid) {
33
        $categoryid = newCategory($_POST['newcategory']);
34
    }
35
}
36
37
$name = $name != '' ? $name : "Untitled variable";
38
$caption = $caption != '' ? $caption : $name;
39
40
// get table names
41
$tbl_site_tmplvars = $modx->getFullTableName('site_tmplvars');
42
43
switch ($_POST['mode']) {
44
    case '300':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
45
46
        // invoke OnBeforeTVFormSave event
47
        $modx->invokeEvent("OnBeforeTVFormSave", array(
48
            "mode" => "new",
49
            "id" => $id
50
        ));
51
52
        // disallow duplicate names for new tvs
53
        $rs = $modx->db->select('COUNT(*)', $tbl_site_tmplvars, "name='{$name}'");
54
        $count = $modx->db->getValue($rs);
55
        if ($count > 0) {
56
            $modx->manager->saveFormValues(300);
57
            $modx->webAlertAndQuit(sprintf($_lang['duplicate_name_found_general'], $_lang['tv'], $name), "index.php?a=300");
58
        }
59
        // disallow reserved names
60 View Code Duplication
        if (in_array($name, array('id', 'type', 'contentType', 'pagetitle', 'longtitle', 'description', 'alias', 'link_attributes', 'published', 'pub_date', 'unpub_date', 'parent', 'isfolder', 'introtext', 'content', 'richtext', 'template', 'menuindex', 'searchable', 'cacheable', 'createdby', 'createdon', 'editedby', 'editedon', 'deleted', 'deletedon', 'deletedby', 'publishedon', 'publishedby', 'menutitle', 'donthit', 'privateweb', 'privatemgr', 'content_dispo', 'hidemenu', 'alias_visible'))) {
61
            $_POST['name'] = '';
62
            $modx->manager->saveFormValues(300);
63
            $modx->webAlertAndQuit(sprintf($_lang['reserved_name_warning'], $_lang['tv'], $name), "index.php?a=300");
64
        }
65
66
        // Add new TV
67
        $newid = $modx->db->insert(array(
68
            'name' => $name,
69
            'description' => $description,
70
            'caption' => $caption,
71
            'type' => $type,
72
            'elements' => $elements,
73
            'default_text' => $default_text,
74
            'display' => $display,
75
            'display_params' => $params,
76
            'rank' => $rank,
77
            'locked' => $locked,
78
            'category' => $categoryid,
79
            'createdon' => $currentdate,
80
            'editedon' => $currentdate
81
        ), $tbl_site_tmplvars);
82
83
        // save access permissions
84
        saveTemplateVarAccess();
85
        saveDocumentAccessPermissons();
86
87
        // invoke OnTVFormSave event
88
        $modx->invokeEvent("OnTVFormSave", array(
89
            "mode" => "new",
90
            "id" => $newid
91
        ));
92
93
        // Set the item name for logger
94
        $_SESSION['itemname'] = $caption;
95
96
        // empty cache
97
        $modx->clearCache('full');
98
99
        // finished emptying cache - redirect
100
        if ($_POST['stay'] != '') {
101
            $a = ($_POST['stay'] == '2') ? "301&id=$newid" : "300";
102
            $header = "Location: index.php?a=" . $a . "&r=2&stay=" . $_POST['stay'];
103
            header($header);
104
        } else {
105
            $header = "Location: index.php?a=76&r=2";
106
            header($header);
107
        }
108
        break;
109
    case '301':
110
        // invoke OnBeforeTVFormSave event
111
        $modx->invokeEvent("OnBeforeTVFormSave", array(
112
            "mode" => "upd",
113
            "id" => $id
114
        ));
115
116
        // disallow duplicate names for tvs
117
        $rs = $modx->db->select('COUNT(*)', $tbl_site_tmplvars, "name='{$name}' AND id!='{$id}'");
118
        if ($modx->db->getValue($rs) > 0) {
119
            $modx->manager->saveFormValues(300);
120
            $modx->webAlertAndQuit(sprintf($_lang['duplicate_name_found_general'], $_lang['tv'], $name), "index.php?a=301&id={$id}");
121
        }
122
        // disallow reserved names
123 View Code Duplication
        if (in_array($name, array('id', 'type', 'contentType', 'pagetitle', 'longtitle', 'description', 'alias', 'link_attributes', 'published', 'pub_date', 'unpub_date', 'parent', 'isfolder', 'introtext', 'content', 'richtext', 'template', 'menuindex', 'searchable', 'cacheable', 'createdby', 'createdon', 'editedby', 'editedon', 'deleted', 'deletedon', 'deletedby', 'publishedon', 'publishedby', 'menutitle', 'donthit', 'privateweb', 'privatemgr', 'content_dispo', 'hidemenu', 'alias_visible'))) {
124
            $modx->manager->saveFormValues(300);
125
            $modx->webAlertAndQuit(sprintf($_lang['reserved_name_warning'], $_lang['tv'], $name), "index.php?a=301&id={$id}");
126
        }
127
128
        // update TV
129
        $modx->db->update(array(
130
            'name' => $name,
131
            'description' => $description,
132
            'caption' => $caption,
133
            'type' => $type,
134
            'elements' => $elements,
135
            'default_text' => $default_text,
136
            'display' => $display,
137
            'display_params' => $params,
138
            'rank' => $rank,
139
            'locked' => $locked,
140
            'category' => $categoryid,
141
            'editedon' => $currentdate
142
        ), $tbl_site_tmplvars, "id='{$id}'");
143
144
        // save access permissions
145
        saveTemplateVarAccess();
146
        saveDocumentAccessPermissons();
147
148
        // invoke OnTVFormSave event
149
        $modx->invokeEvent("OnTVFormSave", array(
150
            "mode" => "upd",
151
            "id" => $id
152
        ));
153
154
        // Set the item name for logger
155
        $_SESSION['itemname'] = $caption;
156
157
        // empty cache
158
        $modx->clearCache('full');
159
160
        // finished emptying cache - redirect
161
        if ($_POST['stay'] != '') {
162
            $a = ($_POST['stay'] == '2') ? "301&id=$id" : "300";
163
            $header = "Location: index.php?a=" . $a . "&r=2&stay=" . $_POST['stay'] . "&or=" . $origin . "&oid=" . $originId;
164
            header($header);
165
        } else {
166
            $modx->unlockElement(2, $id);
167
            $header = "Location: index.php?a=" . $origin . "&r=2" . (empty($originId) ? '' : '&id=' . $originId);
168
            header($header);
169
        }
170
171
        break;
172
    default:
173
        $modx->webAlertAndQuit("No operation set in request.");
174
}
175
176
function saveTemplateVarAccess()
0 ignored issues
show
Coding Style introduced by
saveTemplateVarAccess uses the super-global variable $_POST 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...
177
{
178
    global $id, $newid;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
179
    global $modx;
180
181
    if ($newid) {
182
        $id = $newid;
183
    }
184
    $templates = $_POST['template']; // get muli-templates based on S.BRENNAN mod
185
186
    // update template selections
187
    $tbl_site_tmplvar_templates = $modx->getFullTableName('site_tmplvar_templates');
188
189
    $getRankArray = array();
190
191
    $getRank = $modx->db->select("templateid, rank", $tbl_site_tmplvar_templates, "tmplvarid='{$id}'");
192
193
    while ($row = $modx->db->getRow($getRank)) {
194
        $getRankArray[$row['templateid']] = $row['rank'];
195
    }
196
197
198
    $modx->db->delete($tbl_site_tmplvar_templates, "tmplvarid = '{$id}'");
199
    for ($i = 0; $i < count($templates); $i++) {
200
        $setRank = ($getRankArray[$templates[$i]]) ? $getRankArray[$templates[$i]] : 0;
201
        $modx->db->insert(array(
202
            'tmplvarid' => $id,
203
            'templateid' => $templates[$i],
204
            'rank' => $setRank,
205
        ), $tbl_site_tmplvar_templates);
206
    }
207
}
208
209 View Code Duplication
function saveDocumentAccessPermissons()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
saveDocumentAccessPermissons uses the super-global variable $_POST 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...
210
{
211
    global $id, $newid;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
212
    global $modx, $use_udperms;
213
214
    $tbl_site_tmplvar_templates = $modx->getFullTableName('site_tmplvar_access');
215
216
    if ($newid) {
217
        $id = $newid;
218
    }
219
    $docgroups = $_POST['docgroups'];
220
221
    // check for permission update access
222
    if ($use_udperms == 1) {
223
        // delete old permissions on the tv
224
        $modx->db->delete($tbl_site_tmplvar_templates, "tmplvarid='{$id}'");
225
        if (is_array($docgroups)) {
226
            foreach ($docgroups as $value) {
227
                $modx->db->insert(array(
228
                    'tmplvarid' => $id,
229
                    'documentgroup' => stripslashes($value),
230
                ), $tbl_site_tmplvar_templates);
231
            }
232
        }
233
    }
234
}
235