Completed
Pull Request — develop (#534)
by Agel_Nash
05:08
created

save_template.processor.php ➔ saveTemplateAccess()   D

Complexity

Conditions 9
Paths 13

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 21
nc 13
nop 1
dl 0
loc 32
rs 4.909
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
$template = $modx->db->escape($_POST['post']);
11
$templatename = $modx->db->escape(trim($_POST['templatename']));
12
$description = $modx->db->escape($_POST['description']);
13
$locked = $_POST['locked'] == 'on' ? 1 : 0;
14
$selectable = $id == $modx->config['default_template'] ? 1 :    // Force selectable
15
    $_POST['selectable'] == 'on' ? 1 : 0;
16
$currentdate = time() + $modx->config['server_offset_time'];
17
18
//Kyle Jaebker - added category support
19 View Code Duplication
if (empty($_POST['newcategory']) && $_POST['categoryid'] > 0) {
20
    $categoryid = (int)$_POST['categoryid'];
21
} elseif (empty($_POST['newcategory']) && $_POST['categoryid'] <= 0) {
22
    $categoryid = 0;
23
} else {
24
    include_once(MODX_MANAGER_PATH . 'includes/categories.inc.php');
25
    $categoryid = checkCategory($_POST['newcategory']);
26
    if (!$categoryid) {
27
        $categoryid = newCategory($_POST['newcategory']);
28
    }
29
}
30
31
if ($templatename == "") {
32
    $templatename = "Untitled template";
33
}
34
35
switch ($_POST['mode']) {
36
    case '19':
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...
37
38
        // invoke OnBeforeTempFormSave event
39
        $modx->invokeEvent("OnBeforeTempFormSave", array(
40
            "mode" => "new",
41
            "id" => $id
42
        ));
43
44
        // disallow duplicate names for new templates
45
        $rs = $modx->db->select('COUNT(id)', $modx->getFullTableName('site_templates'), "templatename='{$templatename}'");
46
        $count = $modx->db->getValue($rs);
47
        if ($count > 0) {
48
            $modx->manager->saveFormValues(19);
49
            $modx->webAlertAndQuit(sprintf($_lang['duplicate_name_found_general'], $_lang['template'], $templatename), "index.php?a=19");
50
        }
51
52
        //do stuff to save the new doc
53
        $newid = $modx->db->insert(array(
54
            'templatename' => $templatename,
55
            'description' => $description,
56
            'content' => $template,
57
            'locked' => $locked,
58
            'selectable' => $selectable,
59
            'category' => $categoryid,
60
            'createdon' => $currentdate,
61
            'editedon' => $currentdate
62
        ), $modx->getFullTableName('site_templates'));
63
64
        // invoke OnTempFormSave event
65
        $modx->invokeEvent("OnTempFormSave", array(
66
            "mode" => "new",
67
            "id" => $newid
68
        ));
69
        // Set new assigned Tvs
70
        saveTemplateAccess($newid);
71
72
        // Set the item name for logger
73
        $_SESSION['itemname'] = $templatename;
74
75
        // empty cache
76
        $modx->clearCache('full');
77
78
        // finished emptying cache - redirect
79
        if ($_POST['stay'] != '') {
80
            $a = ($_POST['stay'] == '2') ? "16&id=$newid" : "19";
81
            $header = "Location: index.php?a=" . $a . "&r=2&stay=" . $_POST['stay'];
82
            header($header);
83
        } else {
84
            $header = "Location: index.php?a=76&r=2";
85
            header($header);
86
        }
87
88
        break;
89
    case '16':
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...
90
91
        // invoke OnBeforeTempFormSave event
92
        $modx->invokeEvent("OnBeforeTempFormSave", array(
93
            "mode" => "upd",
94
            "id" => $id
95
        ));
96
97
        // disallow duplicate names for templates
98
        $rs = $modx->db->select('COUNT(*)', $modx->getFullTableName('site_templates'), "templatename='{$templatename}' AND id!='{$id}'");
99
        $count = $modx->db->getValue($rs);
100
        if ($count > 0) {
101
            $modx->manager->saveFormValues(16);
102
            $modx->webAlertAndQuit(sprintf($_lang['duplicate_name_found_general'], $_lang['template'], $templatename), "index.php?a=16&id={$id}");
103
        }
104
105
        //do stuff to save the edited doc
106
        $modx->db->update(array(
107
            'templatename' => $templatename,
108
            'description' => $description,
109
            'content' => $template,
110
            'locked' => $locked,
111
            'selectable' => $selectable,
112
            'category' => $categoryid,
113
            'editedon' => $currentdate
114
        ), $modx->getFullTableName('site_templates'), "id='{$id}'");
115
        // Set new assigned Tvs
116
        saveTemplateAccess($id);
117
118
        // invoke OnTempFormSave event
119
        $modx->invokeEvent("OnTempFormSave", array(
120
            "mode" => "upd",
121
            "id" => $id
122
        ));
123
124
        // Set the item name for logger
125
        $_SESSION['itemname'] = $templatename;
126
127
        // first empty the cache
128
        $modx->clearCache('full');
129
130
        // finished emptying cache - redirect
131
        if ($_POST['stay'] != '') {
132
            $a = ($_POST['stay'] == '2') ? "16&id=$id" : "19";
133
            $header = "Location: index.php?a=" . $a . "&r=2&stay=" . $_POST['stay'];
134
            header($header);
135
        } else {
136
            $modx->unlockElement(1, $id);
137
            $header = "Location: index.php?a=76&r=2";
138
            header($header);
139
        }
140
141
142
        break;
143
    default:
144
        $modx->webAlertAndQuit("No operation set in request.");
145
}
146
147
function saveTemplateAccess($id)
0 ignored issues
show
Coding Style introduced by
saveTemplateAccess 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...
148
{
149
    global $modx;
150
    if ($_POST['tvsDirty'] == 1) {
151
        $newAssignedTvs = $_POST['assignedTv'];
152
153
        // Preserve rankings of already assigned TVs
154
        $rs = $modx->db->select("tmplvarid, rank", $modx->getFullTableName('site_tmplvar_templates'), "templateid='{$id}'", "");
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $rs. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
155
156
        $ranksArr = array();
157
        $highest = 0;
158
        while ($row = $modx->db->getRow($rs)) {
159
            $ranksArr[$row['tmplvarid']] = $row['rank'];
160
            $highest = $highest < $row['rank'] ? $row['rank'] : $highest;
161
        };
162
163
        $modx->db->delete($modx->getFullTableName('site_tmplvar_templates'), "templateid='{$id}'");
164
        if (empty($newAssignedTvs)) {
165
            return;
166
        }
167
        foreach ($newAssignedTvs as $tvid) {
168
            if (!$id || !$tvid) {
169
                continue;
170
            }    // Dont link zeros
171
            $modx->db->insert(array(
172
                'templateid' => $id,
173
                'tmplvarid' => $tvid,
174
                'rank' => isset($ranksArr[$tvid]) ? $ranksArr[$tvid] : $highest += 1 // append TVs to rank
175
            ), $modx->getFullTableName('site_tmplvar_templates'));
176
        }
177
    }
178
}
179