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

save_plugin.processor.php ➔ getEventIdByName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 14
rs 9.4285
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_plugin')) {
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
$locked = $_POST['locked'] == 'on' ? '1' : '0';
13
$plugincode = $modx->db->escape($_POST['post']);
14
$properties = $modx->db->escape($_POST['properties']);
15
$disabled = $_POST['disabled'] == 'on' ? '1' : '0';
16
$moduleguid = $modx->db->escape($_POST['moduleguid']);
17
$sysevents = !empty($_POST['sysevents']) ? $_POST['sysevents'] : array();
18
$parse_docblock = $_POST['parse_docblock'] == '1' ? '1' : '0';
19
$currentdate = time() + $modx->config['server_offset_time'];
20
21
//Kyle Jaebker - added category support
22
if (empty($_POST['newcategory']) && $_POST['categoryid'] > 0) {
23
    $categoryid = (int)$_POST['categoryid']);
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected ')'
Loading history...
24
} elseif (empty($_POST['newcategory']) && $_POST['categoryid'] <= 0) {
25
    $categoryid = 0;
26
} else {
27
    include_once(MODX_MANAGER_PATH . 'includes/categories.inc.php');
28
    $categoryid = getCategory($_POST['newcategory']);
29
}
30
31
if ($name == '') {
32
    $name = 'Untitled plugin';
33
}
34
35
if ($parse_docblock) {
36
    $parsed = $modx->parseDocBlockFromString($plugincode, true);
37
    $name       = isset($parsed['name']) ? $parsed['name'] : $name;
38
    $sysevents  = isset($parsed['events']) ? explode(',', $parsed['events']) : $sysevents;
39
    $properties = isset($parsed['properties']) ? $parsed['properties'] : $properties;
40
    $moduleguid = isset($parsed['guid']) ? $parsed['guid'] : $moduleguid;
41
42
    $description = isset($parsed['description']) ? $parsed['description'] : $description;
43
    $version = isset($parsed['version']) ? '<b>' . $parsed['version'] . '</b> ' : '';
44
    if ($version) {
45
        $description = $version . trim(preg_replace('/(<b>.+?)+(<\/b>)/i', '', $description));
46
    }
47
    if (isset($parsed['modx_category'])) {
48
        include_once(MODX_MANAGER_PATH . 'includes/categories.inc.php');
49
        $categoryid = getCategory($parsed['modx_category']);
50
    }
51
}
52
53
$tblSitePlugins = $modx->getFullTableName('site_plugins');
54
$eventIds = array();
55
switch ($_POST['mode']) {
56
    case '101':
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...
57
58
        // invoke OnBeforePluginFormSave event
59
        $modx->invokeEvent('OnBeforePluginFormSave', array(
60
            'mode' => 'new',
61
            'id' => $id
62
        ));
63
64
        // disallow duplicate names for active plugins
65
        if ($disabled == '0') {
66
            $rs = $modx->db->select('COUNT(id)', $modx->getFullTableName('site_plugins'), "name='{$name}' AND disabled='0'");
67
            $count = $modx->db->getValue($rs);
68
            if ($count > 0) {
69
                $modx->manager->saveFormValues(101);
70
                $modx->webAlertAndQuit(sprintf($_lang['duplicate_name_found_general'], $_lang['plugin'], $name), 'index.php?a=101');
71
            }
72
        }
73
74
        //do stuff to save the new plugin
75
        $newid = $modx->db->insert(array(
76
            'name' => $name,
77
            'description' => $description,
78
            'plugincode' => $plugincode,
79
            'disabled' => $disabled,
80
            'moduleguid' => $moduleguid,
81
            'locked' => $locked,
82
            'properties' => $properties,
83
            'category' => $categoryid,
84
            'createdon' => $currentdate,
85
            'editedon' => $currentdate
86
        ), $tblSitePlugins);
87
88
        // save event listeners
89
        saveEventListeners($newid, $sysevents, $_POST['mode']);
90
91
        // invoke OnPluginFormSave event
92
        $modx->invokeEvent('OnPluginFormSave', array(
93
            'mode' => 'new',
94
            'id' => $newid
95
        ));
96
97
        // Set the item name for logger
98
        $_SESSION['itemname'] = $name;
99
100
        // empty cache
101
        $modx->clearCache('full');
102
103
        // finished emptying cache - redirect
104
        if ($_POST['stay'] != '') {
105
            $a = ($_POST['stay'] == '2') ? "102&id=$newid" : '101';
106
            $header = 'Location: index.php?a=' . $a . '&r=2&stay=' . $_POST['stay'];
107
            header($header);
108
        } else {
109
            $header = 'Location: index.php?a=76&r=2';
110
            header($header);
111
        }
112
        break;
113
    case '102':
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...
114
115
        // invoke OnBeforePluginFormSave event
116
        $modx->invokeEvent('OnBeforePluginFormSave', array(
117
            'mode' => 'upd',
118
            'id' => $id
119
        ));
120
121
        // disallow duplicate names for active plugins
122
        if ($disabled == '0') {
123
            $rs = $modx->db->select('COUNT(*)', $modx->getFullTableName('site_plugins'), "name='{$name}' AND id!='{$id}' AND disabled='0'");
124
            if ($modx->db->getValue($rs) > 0) {
125
                $modx->manager->saveFormValues(102);
126
                $modx->webAlertAndQuit(sprintf($_lang['duplicate_name_found_general'], $_lang['plugin'], $name), "index.php?a=102&id={$id}");
127
            }
128
        }
129
130
        //do stuff to save the edited plugin
131
        $modx->db->update(array(
132
            'name' => $name,
133
            'description' => $description,
134
            'plugincode' => $plugincode,
135
            'disabled' => $disabled,
136
            'moduleguid' => $moduleguid,
137
            'locked' => $locked,
138
            'properties' => $properties,
139
            'category' => $categoryid,
140
            'editedon' => $currentdate
141
        ), $tblSitePlugins, "id='{$id}'");
142
143
        // save event listeners
144
        saveEventListeners($id, $sysevents, $_POST['mode']);
145
146
        // invoke OnPluginFormSave event
147
        $modx->invokeEvent('OnPluginFormSave', array(
148
            'mode' => 'upd',
149
            'id' => $id
150
        ));
151
152
        // Set the item name for logger
153
        $_SESSION['itemname'] = $name;
154
155
        // empty cache
156
        $modx->clearCache('full');
157
158
        // finished emptying cache - redirect
159
        if ($_POST['stay'] != '') {
160
            $a = ($_POST['stay'] == '2') ? "102&id=$id" : '101';
161
            $header = 'Location: index.php?a=' . $a . '&r=2&stay=' . $_POST['stay'];
162
            header($header);
163
        } else {
164
            $modx->unlockElement(5, $id);
165
            $header = 'Location: index.php?a=76&r=2';
166
            header($header);
167
        }
168
        break;
169
    default:
170
        $modx->webAlertAndQuit('No operation set in request.');
171
}
172
173
# Save Plugin Event Listeners
0 ignored issues
show
Coding Style introduced by
Perl-style comments are not allowed. Use "// Comment." or "/* comment */" instead.
Loading history...
174
function saveEventListeners($id, $sysevents, $mode)
175
{
176
    global $modx;
177
    // save selected system events
178
    $formEventList = array();
179
    foreach ($sysevents as $evtId) {
180
        if(!preg_match('@^[1-9][0-9]*$@',$evtId)) $evtId = getEventIdByName($evtId);
181
        if ($mode == '101') {
182
            $rs = $modx->db->select('max(priority) as priority', '[+prefix+]site_plugin_events', "evtid='{$evtId}'");
183
        } else {
184
            $rs = $modx->db->select('priority', '[+prefix+]site_plugin_events', "evtid='{$evtId}' and pluginid='{$id}'");
185
        }
186
        $prevPriority = $modx->db->getValue($rs);
187
        if ($mode == '101') {
188
            $priority = isset($prevPriority) ? $prevPriority + 1 : 1;
189
        } else {
190
            $priority = isset($prevPriority) ? $prevPriority : 1;
191
        }
192
        $formEventList[] = array('pluginid' => $id, 'evtid' => $evtId, 'priority' => $priority);
193
    }
194
195
    $evtids = array();
196
    foreach ($formEventList as $eventInfo) {
197
        $where = vsprintf("pluginid='%s' AND evtid='%s'", $eventInfo);
198
        $modx->db->save($eventInfo, '[+prefix+]site_plugin_events', $where);
199
        $evtids[] = $eventInfo['evtid'];
200
    }
201
202
    $rs = $modx->db->select('*', '[+prefix+]site_plugin_events', sprintf("pluginid='%s'", $id));
203
    $dbEventList = array();
204
    $del = array();
205
    while($row = $modx->db->getRow($rs)) {
206
        if(!in_array($row['evtid'], $evtids)) $del[] = $row['evtid'];
207
    }
208
209
    if(empty($del)) return;
210
211
    foreach($del as $delid) {
212
        $modx->db->delete('[+prefix+]site_plugin_events', sprintf("evtid='%s' AND pluginid='%s'", $delid, $id));
213
    }
214
}
215
216
function getEventIdByName($name)
217
{
218
    global $modx;
219
    static $eventIds=array();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 0 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
220
221
    if(isset($eventIds[$name])) return $eventIds[$name];
222
223
    $rs = $modx->db->select('id, name', '[+prefix+]system_eventnames');
224
    while ($row = $modx->db->getRow($rs)) {
225
        $eventIds[$row['name']] = $row['id'];
226
    }
227
228
    return $eventIds[$name];
229
}
230
231