SettingsController.php 26.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<?php
/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 */
namespace OPNsense\IDS\Api;

31
use \Phalcon\Filter;
32
use \OPNsense\Base\ApiMutableModelControllerBase;
33
use \OPNsense\Base\Filters\QueryFilter;
34 35
use \OPNsense\Core\Backend;
use \OPNsense\Core\Config;
36
use \OPNsense\Base\UIModelGrid;
37 38 39 40 41

/**
 * Class SettingsController Handles settings related API actions for the IDS module
 * @package OPNsense\IDS
 */
42
class SettingsController extends ApiMutableModelControllerBase
43
{
Franco Fichtner's avatar
Franco Fichtner committed
44 45
    static protected $internalModelName = 'ids';
    static protected $internalModelClass = '\OPNsense\IDS\IDS';
46

47
    /**
48
     * @return array plain model settings (non repeating items)
49
     */
50
    protected function getModelNodes()
51
    {
52 53 54 55 56
        $settingsNodes = array('general');
        $result = array();
        $mdlIDS = $this->getModel();
        foreach ($settingsNodes as $key) {
            $result[$key] = $mdlIDS->$key->getNodes();
57
        }
58
        return $result;
59 60 61 62 63 64 65 66 67 68
    }

    /**
     * search installed ids rules
     * @return array
     */
    public function searchInstalledRulesAction()
    {
        if ($this->request->isPost()) {
            $this->sessionClose();
69 70 71 72
            // create filter to sanitize input data
            $filter = new Filter();
            $filter->add('query', new QueryFilter());

73

Ad Schellevis's avatar
Ad Schellevis committed
74
            // fetch query parameters (limit results to prevent out of memory issues)
75
            $itemsPerPage = $this->request->getPost('rowCount', 'int', 9999);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
            $currentPage = $this->request->getPost('current', 'int', 1);

            if ($this->request->hasPost('sort') && is_array($this->request->getPost("sort"))) {
                $sortStr = '';
                $sortBy = array_keys($this->request->getPost("sort"));
                if ($this->request->getPost("sort")[$sortBy[0]] == "desc") {
                    $sortOrd = 'desc';
                } else {
                    $sortOrd = 'asc';
                }

                foreach ($sortBy as $sortKey) {
                    if ($sortStr != '') {
                        $sortStr .= ',';
                    }
91
                    $sortStr .= $filter->sanitize($sortKey, "query") . ' '. $sortOrd . ' ';
92 93 94 95 96
                }
            } else {
                $sortStr = 'sid';
            }
            if ($this->request->getPost('searchPhrase', 'string', '') != "") {
97
                $searchTag = $filter->sanitize($this->request->getPost('searchPhrase'), "query");
98
                $searchPhrase = 'msg,source,sid/"*'.$searchTag.'"';
99 100 101 102 103 104
            } else {
                $searchPhrase = '';
            }

            // add filter for classtype
            if ($this->request->getPost("classtype", "string", '') != "") {
105
                $searchTag = $filter->sanitize($this->request->getPost('classtype'), "query");
106
                $searchPhrase .= " classtype/".$searchTag.' ';
107 108
            }

109 110 111 112 113 114
            // add filter for action
            if ($this->request->getPost("action", "string", '') != "") {
                $searchTag = $filter->sanitize($this->request->getPost('action'), "query");
                $searchPhrase .= " installed_action/".$searchTag.' ';
            }

115 116
            // request list of installed rules
            $backend = new Backend();
117
            $response = $backend->configdpRun("ids query rules", array($itemsPerPage,
118 119
                ($currentPage-1)*$itemsPerPage,
                $searchPhrase, $sortStr));
120

121 122 123 124 125 126 127
            $data = json_decode($response, true);

            if ($data != null && array_key_exists("rows", $data)) {
                $result = array();
                $result['rows'] = $data['rows'];
                // update rule status with own administration
                foreach ($result['rows'] as &$row) {
128
                    $row['enabled_default'] = $row['enabled'];
129
                    $row['enabled'] = $this->getModel()->getRuleStatus($row['sid'], $row['enabled']);
130
                    $row['action'] = $this->getModel()->getRuleAction($row['sid'], $row['action'], true);
131 132 133 134
                }

                $result['rowCount'] = count($result['rows']);
                $result['total'] = $data['total_rows'];
135
                $result['parameters'] = $data['parameters'];
136 137 138 139 140 141 142 143 144 145 146 147
                $result['current'] = (int)$currentPage;
                return $result;
            } else {
                return array();
            }
        } else {
            return array();
        }
    }

    /**
     * get rule information
148
     * @param string|null $sid rule identifier
149 150
     * @return array|mixed
     */
Franco Fichtner's avatar
Franco Fichtner committed
151
    public function getRuleInfoAction($sid = null)
152 153
    {
        // request list of installed rules
154 155 156 157 158 159 160
        if (!empty($sid)) {
            $backend = new Backend();
            $response = $backend->configdpRun("ids query rules", array(1, 0,'sid/'.$sid));
            $data = json_decode($response, true);
        } else {
            $data = null;
        }
161 162 163

        if ($data != null && array_key_exists("rows", $data) && count($data['rows'])>0) {
            $row = $data['rows'][0];
164
            // set current enable status (default + registered offset)
165
            $row['enabled_default'] = $row['enabled'];
166
            $row['action_default'] = $row['action'];
167
            $row['enabled'] = $this->getModel()->getRuleStatus($row['sid'], $row['enabled']);
168
            $row['action'] = $this->getModel()->getRuleAction($row['sid'], $row['action']);
169
            //
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
            if (isset($row['reference']) && $row['reference'] != '') {
                // browser friendly reference data
                $row['reference_html'] = '';
                foreach (explode("\n", $row['reference']) as $ref) {
                    $ref = trim($ref);
                    $item_html = '<small><a href="%url%" target="_blank">%ref%</a></small>';
                    if (substr($ref, 0, 4) == 'url,') {
                        $item_html = str_replace("%url%", 'http://'.substr($ref, 4), $item_html);
                        $item_html = str_replace("%ref%", substr($ref, 4), $item_html);
                    } elseif (substr($ref, 0, 7) == "system,") {
                        $item_html = str_replace("%url%", substr($ref, 7), $item_html);
                        $item_html = str_replace("%ref%", substr($ref, 7), $item_html);
                    } elseif (substr($ref, 0, 8) == "bugtraq,") {
                        $item_html = str_replace("%url%", "http://www.securityfocus.com/bid/".
                            substr($ref, 8), $item_html);
                        $item_html = str_replace("%ref%", "bugtraq ".substr($ref, 8), $item_html);
                    } elseif (substr($ref, 0, 4) == "cve,") {
                        $item_html = str_replace("%url%", "http://cve.mitre.org/cgi-bin/cvename.cgi?name=".
                            substr($ref, 4), $item_html);
                        $item_html = str_replace("%ref%", substr($ref, 4), $item_html);
                    } elseif (substr($ref, 0, 7) == "nessus,") {
                        $item_html = str_replace("%url%", "http://cgi.nessus.org/plugins/dump.php3?id=".
                            substr($ref, 7), $item_html);
                        $item_html = str_replace("%ref%", 'nessus '.substr($ref, 7), $item_html);
                    } elseif (substr($ref, 0, 7) == "mcafee,") {
                        $item_html = str_replace("%url%", "http://vil.nai.com/vil/dispVirus.asp?virus_k=".
                            substr($ref, 7), $item_html);
                        $item_html = str_replace("%ref%", 'macafee '.substr($ref, 7), $item_html);
                    } else {
                        continue;
                    }
                    $row['reference_html'] .= $item_html.'<br/>';
                }
            }
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            return $row;
        } else {
            return array();
        }
    }

    /**
     * list available classtypes
     * @return array
     * @throws \Exception
     */
    public function listRuleClasstypesAction()
    {
        $backend = new Backend();
        $response = $backend->configdRun("ids list classtypes");
        $data = json_decode($response, true);
        if ($data != null && array_key_exists("items", $data)) {
            return $data;
        } else {
            return array();
        }
    }

227
    /**
228 229
     * list all installable rules including configuration additions
     * @return array
230
     */
231
    private function listInstallableRules()
232
    {
233
        $result = array();
234 235 236 237
        $backend = new Backend();
        $response = $backend->configdRun("ids list installablerulesets");
        $data = json_decode($response, true);
        if ($data != null && array_key_exists("items", $data)) {
238
            ksort($data['items']);
239 240 241 242
            foreach ($data['items'] as $filename => $fileinfo) {
                $item = array();
                $item['description'] = $fileinfo['description'];
                $item['filename'] = $fileinfo['filename'];
243 244 245
                $item['documentation_url'] = $fileinfo['documentation_url'];
                if (!empty($fileinfo['documentation_url'])) {
                    $item['documentation'] = "<a href='".$item['documentation_url']."' target='_new'>";
246
                    $item['documentation'] .= $item['documentation_url'];
247 248 249 250
                    $item['documentation'] .= '</a>';
                } else {
                    $item['documentation'] = null;
                }
251 252 253

                // format timestamps
                if ($fileinfo['modified_local'] == null) {
254
                    $item['modified_local'] = null;
255
                } else {
256
                    $item['modified_local'] = date('Y/m/d G:i', $fileinfo['modified_local']);
257
                }
258
                // retrieve status from model
259 260 261 262 263 264 265 266 267 268
                $fileNode = $this->getModel()->getFileNode($fileinfo['filename']);
                $item['enabled'] = (string)$fileNode->enabled;
                $item['filter'] = $fileNode->filter->getNodeData(); // filter (option list)
                $item['filter_str'] = (string)$fileNode->filter; // filter current value
                $result[] = $item;
            }
        }
        return $result;
    }

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    /**
     * list ruleset properties
     * @return array
     */
    public function getRulesetpropertiesAction()
    {
        $result = array('properties' => array());
        $backend = new Backend();
        $response = $backend->configdRun("ids list installablerulesets");
        $data = json_decode($response, true);
        if ($data != null && isset($data["properties"])) {
            foreach ($data['properties'] as $key => $settings) {
                $result['properties'][$key] = !empty($settings['default']) ? $settings['default'] : "";
                foreach ($this->getModel()->fileTags->tag->__items as $tag) {
                    if ((string)$tag->property == $key) {
                        $result['properties'][(string)$tag->property] = (string)$tag->value;
                    }
                }
            }
        }
        return $result;
    }

    /**
     * update ruleset properties
     * @return array
     */
    public function setRulesetpropertiesAction()
    {
        $result = array("result" => "failed");
        if ($this->request->isPost() && $this->request->hasPost("properties")) {
            // only update properties available in "ids list installablerulesets"
            $backend = new Backend();
            $response = $backend->configdRun("ids list installablerulesets");
            $data = json_decode($response, true);
            if ($data != null && isset($data["properties"])) {
                $setProperties = $this->request->getPost("properties");
                foreach ($setProperties as $key => $value) {
                    if (isset($data['properties'][$key])) {
                        if (!isset($result['fields'])) {
                            $result['fields'] = array(); // return updated fields
                        }
                        $result['fields'][] = $key;
                        $resultTag = null;
                        foreach ($this->getModel()->fileTags->tag->__items as $tag) {
                            if ((string)$tag->property == $key) {
                                $resultTag = $tag;
                                break;
                            }
                        }
                        if ($resultTag == null) {
                            $resultTag = $this->getModel()->fileTags->tag->Add();
                        }
                        $resultTag->property = (string)$key;
                        $resultTag->value = (string)$value;
                    }
                }
                $validations = $this->getModel()->validate();
                if (count($validations)) {
                    $result['validations'] = $validations;
                } else {
                    $this->getModel()->serializeToConfig();
                    Config::getInstance()->save();
                    $result["result"] = "saved";
                }
            }
        }
        return $result;
    }

339 340 341 342 343 344 345 346 347
    /**
     * list all installable rules including current status
     * @return array|mixed list of items when $id is null otherwise the selected item is returned
     * @throws \Exception
     */
    public function listRulesetsAction()
    {
        $result = array();
        $result['rows'] = $this->listInstallableRules();
348 349
        // sort by description
        usort($result['rows'], function ($item1, $item2) {
Franco Fichtner's avatar
Franco Fichtner committed
350
            return strcmp(strtolower($item1['description']), strtolower($item2['description']));
351
        });
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        $result['rowCount'] = count($result['rows']);
        $result['total'] = count($result['rows']);
        $result['current'] = 1;
        return $result;
    }

    /**
     * get ruleset list info (file)
     * @param string $id list filename
     * @return array|mixed list details
     */
    public function getRulesetAction($id)
    {
        $rules = $this->listInstallableRules();
        foreach ($rules as $rule) {
            if ($rule['filename'] == $id) {
                return $rule;
369 370
            }
        }
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        return array();
    }

    /**
     * set ruleset attributes
     * @param $filename rule filename (key)
     * @return array
     */
    public function setRulesetAction($filename)
    {
        $result = array("result" => "failed");
        if ($this->request->isPost()) {
            // we're only allowed to edit filenames which have an install ruleset, request valid ones from configd
            $backend = new Backend();
            $response = $backend->configdRun("ids list installablerulesets");
            $data = json_decode($response, true);
            if ($data != null && array_key_exists("items", $data) && array_key_exists($filename, $data['items'])) {
                // filename exists, input ruleset data
                $mdlIDS = $this->getModel();
                $node = $mdlIDS->getFileNode($filename);

                // send post attributes to model
                $node->setNodes($_POST);

                $validations = $mdlIDS->validate($node->__reference . ".", "");
                if (count($validations)) {
                    $result['validations'] = $validations;
                } else {
                    // serialize model to config and save
                    $mdlIDS->serializeToConfig();
                    Config::getInstance()->save();
                    $result["result"] = "saved";
                }
            }
        }
        return $result;
407 408 409 410
    }

    /**
     * toggle usage of rule file or set enabled / disabled depending on parameters
411
     * @param $filenames (target) rule file name, or list of filenames separated by a comma
412 413 414 415 416
     * @param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
     * @return array status 0/1 or error
     * @throws \Exception
     * @throws \Phalcon\Validation\Exception
     */
417
    public function toggleRulesetAction($filenames, $enabled = null)
418
    {
419
        $update_count = 0;
420 421 422 423 424
        $result = array("status" => "none");
        if ($this->request->isPost()) {
            $backend = new Backend();
            $response = $backend->configdRun("ids list installablerulesets");
            $data = json_decode($response, true);
425 426 427 428 429 430 431 432 433 434 435 436
            foreach (explode(",", $filenames) as $filename) {
                if ($data != null && array_key_exists("items", $data) && array_key_exists($filename, $data['items'])) {
                    $node = $this->getModel()->getFileNode($filename);
                    if ($enabled == "0" || $enabled == "1") {
                        $node->enabled = (string)$enabled;
                    } elseif ((string)$node->enabled == "1") {
                        $node->enabled = "0";
                    } else {
                        $node->enabled = "1";
                    }
                    // only update result state if all items until now are ok
                    if ($result['status'] != 'error') {
437
                        $result['status'] = (string)$node->enabled;
438 439
                    }
                    $update_count++;
440
                } else {
441
                    $result['status'] = "error";
442
                }
443 444
            }
            if ($update_count > 0) {
445 446 447 448 449 450 451
                $this->getModel()->serializeToConfig();
                Config::getInstance()->save();
            }
        }
        return $result;
    }

452
    /**
453
     * toggle rule enable status
454 455
     * @param string $sids unique id
     * @param string|int $enabled desired state enabled(1)/disabled(1), leave empty for toggle
456
     * @return array empty
457
     */
458
    public function toggleRuleAction($sids, $enabled = null)
459
    {
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        if ($this->request->isPost()) {
            $update_count = 0;
            foreach (explode(",", $sids) as $sid) {
                $ruleinfo = $this->getRuleInfoAction($sid);
                if (count($ruleinfo) > 0) {
                    if ($enabled == null) {
                        // toggle state
                        if ($ruleinfo['enabled'] == 1) {
                            $new_state = 0;
                        } else {
                            $new_state = 1;
                        }
                    } elseif ($enabled == 1) {
                        $new_state = 1;
                    } else {
                        $new_state = 0;
                    }

478 479 480 481
                    if ($ruleinfo['enabled_default'] == $new_state &&
                        array_key_exists($ruleinfo['action_default'], $ruleinfo['action']) &&
                        $ruleinfo['action'][$ruleinfo['action_default']]['selected'] == 1
                        ) {
482 483 484 485 486 487 488 489 490 491 492 493 494
                        // if we're switching back to default, remove alter rule
                        $this->getModel()->removeRule($sid);
                    } elseif ($new_state == 1) {
                        $this->getModel()->enableRule($sid);
                    } else {
                        $this->getModel()->disableRule($sid);
                    }
                    $update_count++;
                }
            }
            if ($update_count > 0) {
                $this->getModel()->serializeToConfig();
                Config::getInstance()->save();
495 496 497 498
            }
        }
        return array();
    }
Ad Schellevis's avatar
Ad Schellevis committed
499

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    /**
     * set rule action
     * @param $sid item unique id
     * @return array
     */
    public function setRuleAction($sid)
    {
        $result = array("result" => "failed");
        if ($this->request->isPost() && $this->request->hasPost("action")) {
            $ruleinfo = $this->getRuleInfoAction($sid);
            $newAction = $this->request->getPost("action", "striptags", null);
            if (count($ruleinfo) > 0) {
                $mdlIDS = $this->getModel();
                if ($ruleinfo['enabled_default'] == $ruleinfo['enabled'] &&
                    $ruleinfo['action_default'] == $newAction
                    ) {
                    // if we're switching back to default, remove alter rule
                    $mdlIDS->removeRule($sid);
                } else {
                    $mdlIDS->setAction($sid, $newAction);
                }

522 523 524 525
                $validations = $mdlIDS->validate();
                if (count($validations)) {
                    $result['validations'] = $validations;
                } else {
526 527 528 529 530 531 532 533 534
                    $mdlIDS->serializeToConfig();
                    Config::getInstance()->save();
                    $result["result"] = "saved";
                }
            }
        }
        return $result;
    }

535
    /**
536 537
     * search user defined rules
     * @return array list of found user rules
538
     */
539
    public function searchUserRuleAction()
540
    {
541 542
        $this->sessionClose();
        $mdlIDS = $this->getModel();
543
        $grid = new UIModelGrid($mdlIDS->userDefinedRules->rule);
544 545
        return $grid->fetchBindRequest(
            $this->request,
546
            array("enabled", "action", "description"),
547 548
            "description"
        );
549 550 551
    }

    /**
552 553
     * update user defined rules
     * @param string $uuid internal id
554 555 556
     * @return array save result + validation output
     * @throws \Phalcon\Validation\Exception
     */
557
    public function setUserRuleAction($uuid)
558 559
    {
        $result = array("result"=>"failed");
560
        if ($this->request->isPost() && $this->request->hasPost("rule")) {
561 562
            $mdlIDS = $this->getModel();
            if ($uuid != null) {
563
                $node = $mdlIDS->getNodeByReference('userDefinedRules.rule.'.$uuid);
564
                if ($node != null) {
565 566
                    $node->setNodes($this->request->getPost("rule"));
                    $validations = $mdlIDS->validate($node->__reference, "rule");
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
                    if (count($validations)) {
                        $result['validations'] = $validations;
                    } else {
                        // serialize model to config and save
                        $mdlIDS->serializeToConfig();
                        Config::getInstance()->save();
                        $result["result"] = "saved";
                    }
                }
            }
        }
        return $result;
    }

    /**
582
     * add new user defined rule
583 584 585
     * @return array save result + validation output
     * @throws \Phalcon\Validation\Exception
     */
586
    public function addUserRuleAction()
587 588
    {
        $result = array("result"=>"failed");
589
        if ($this->request->isPost() && $this->request->hasPost("rule")) {
590
            $mdlIDS = $this->getModel();
591 592 593
            $node = $mdlIDS->userDefinedRules->rule->Add();
            $node->setNodes($this->request->getPost("rule"));
            $validations = $mdlIDS->validate($node->__reference, "rule");
594 595 596 597 598 599 600 601 602 603 604 605 606
            if (count($validations)) {
                $result['validations'] = $validations;
            } else {
                // serialize model to config and save
                $mdlIDS->serializeToConfig();
                Config::getInstance()->save();
                $result["result"] = "saved";
            }
        }
        return $result;
    }

    /**
607 608 609
     * get properties of user defined rule
     * @param null|string $uuid user rule internal id
     * @return array user defined properties
610
     */
611
    public function getUserRuleAction($uuid = null)
612 613 614
    {
        $mdlIDS = $this->getModel();
        if ($uuid != null) {
615
            $node = $mdlIDS->getNodeByReference('userDefinedRules.rule.'.$uuid);
616 617
            if ($node != null) {
                // return node
618
                return array("rule" => $node->getNodes());
619 620 621
            }
        } else {
            // generate new node, but don't save to disc
622
            $node = $mdlIDS->userDefinedRules->rule->add();
623
            return array("rule" => $node->getNodes());
624 625 626 627 628
        }
        return array();
    }

    /**
629 630
     * delete user rule item
     * @param string $uuid user rule internal id
631 632 633
     * @return array
     * @throws \Phalcon\Validation\Exception
     */
634
    public function delUserRuleAction($uuid)
635 636 637 638
    {
        $result = array("result"=>"failed");
        if ($this->request->isPost() && $uuid != null) {
            $mdlIDS = $this->getModel();
639
            if ($mdlIDS->userDefinedRules->rule->del($uuid)) {
640 641 642 643 644 645 646 647 648 649 650 651
                // if item is removed, serialize to config and save
                $mdlIDS->serializeToConfig();
                Config::getInstance()->save();
                $result['result'] = 'deleted';
            } else {
                $result['result'] = 'not found';
            }
        }
        return $result;
    }

    /**
652 653
     * toggle user defined rule by uuid (enable/disable)
     * @param $uuid user defined rule internal id
654 655 656
     * @param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
     * @return array status
     */
657
    public function toggleUserRuleAction($uuid, $enabled = null)
658 659 660 661
    {
        $result = array("result" => "failed");
        if ($this->request->isPost() && $uuid != null) {
            $mdlIDS = $this->getModel();
662
            $node = $mdlIDS->getNodeByReference('userDefinedRules.rule.' . $uuid);
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
            if ($node != null) {
                if ($enabled == "0" || $enabled == "1") {
                    $node->enabled = (string)$enabled;
                } elseif ($node->enabled->__toString() == "1") {
                    $node->enabled = "0";
                } else {
                    $node->enabled = "1";
                }
                $result['result'] = $node->enabled;
                // if item has toggled, serialize to config and save
                $mdlIDS->serializeToConfig();
                Config::getInstance()->save();
            }
        }
        return $result;
    }
679
}