BaseModel.php 24.7 KB
Newer Older
1
<?php
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
/**
*    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.
*
28 29 30 31 32
*/

namespace OPNsense\Base;

use OPNsense\Base\FieldTypes\ArrayField;
33
use OPNsense\Base\FieldTypes\ContainerField;
34
use OPNsense\Core\Config;
35
use Phalcon\Logger\Adapter\Syslog;
36

37 38
/**
 * Class BaseModel implements base model to bind config and definition to object.
39 40
 * Derive from BaseModel to create usable models.
 * Every model definition should include a class (derived from BaseModel) and a xml model to define the data (model.xml)
41
 *
42 43
 * See the HelloWorld model for a full implementation.
 * (https://github.com/opnsense/plugins/tree/master/devel/helloworld/src/opnsense/mvc/app/models/OPNsense/HelloWorld)
44 45 46
 *
 * @package OPNsense\Base
 */
47 48 49 50 51 52 53 54 55 56 57 58 59
abstract class BaseModel
{
    /**
     * @var null|BaseField internal model data structure, should contain Field type objects
     */
    private $internalData = null;

    /**
     * place where the real data in the config.xml should live
     * @var string
     */
    private $internal_mountpoint = '';

60 61 62 63 64 65 66 67 68 69 70
    /**
     * this models version number, defaults to 0.0.0 (no version)
     * @var string
     */
    private $internal_model_version = "0.0.0";

    /**
     * model version in config.xml
     * @var null
     */
    private $internal_current_model_version = null;
71

72 73 74 75 76 77
    /**
     * cache classes
     * @var null
     */
    private static $internalCacheReflectionClasses = null;

78 79 80 81 82 83
    /**
     * If the model needs a custom initializer, override this init() method
     * Default behaviour is to do nothing in this init.
     */
    protected function init()
    {
84
        return;
85 86
    }

Ad Schellevis's avatar
Ad Schellevis committed
87 88 89 90 91 92 93 94
    /**
     * parse option data for model setter.
     * @param $xmlNode
     * @return array|string
     */
    private function parseOptionData($xmlNode)
    {
        if ($xmlNode->count() == 0) {
95
            $result = (string)$xmlNode;
Ad Schellevis's avatar
Ad Schellevis committed
96 97 98 99 100 101 102 103 104
        } else {
            $result = array();
            foreach ($xmlNode->children() as $childNode) {
                $result[$childNode->getName()] = $this->parseOptionData($childNode);
            }
        }
        return $result;
    }

105 106 107
    /**
     * fetch reflection class (cached by field type)
     * @param $classname classname to construct
Ad Schellevis's avatar
Ad Schellevis committed
108 109
     * @return array
     * @throws ModelException
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
     */
    private function getNewField($classname)
    {
        if (self::$internalCacheReflectionClasses === null) {
            self::$internalCacheReflectionClasses = array();
        }
        if (!isset(self::$internalCacheReflectionClasses[$classname])) {
            $is_derived_from_basefield = false;
            if (class_exists($classname)) {
                $field_rfcls = new \ReflectionClass($classname);
                $check_derived = $field_rfcls->getParentClass();
                while ($check_derived != false) {
                    if ($check_derived->name == 'OPNsense\Base\FieldTypes\BaseField') {
                        $is_derived_from_basefield = true;
                        break;
                    }
                    $check_derived = $check_derived->getParentClass();
                }
            }
            if (!$is_derived_from_basefield) {
                // class found, but of wrong type. raise an exception.
                throw new ModelException("class ".$field_rfcls->name." of wrong type in model definition");
            }
133
            self::$internalCacheReflectionClasses[$classname] = $field_rfcls;
134 135 136 137
        }
        return self::$internalCacheReflectionClasses[$classname];
    }

138
    /**
139 140 141 142
     * parse model and config xml to object model using types in FieldTypes
     * @param SimpleXMLElement $xml model xml data (from items section)
     * @param SimpleXMLElement $config_data (current) config data
     * @param BaseField $internal_data output structure using FieldTypes,rootnode is internalData
143 144
     * @throws ModelException parse error
     */
145
    private function parseXml(&$xml, &$config_data, &$internal_data)
146
    {
147 148
        // copy xml tag attributes to Field
        if ($config_data != null) {
149
            foreach ($config_data->attributes() as $AttrKey => $AttrValue) {
150
                $internal_data->setAttributeValue($AttrKey, $AttrValue->__toString());
151 152 153 154
            }
        }

        // iterate model children
155 156 157 158
        foreach ($xml->children() as $xmlNode) {
            $tagName = $xmlNode->getName();
            // every item results in a Field type object, the first step is to determine which object to create
            // based on the input model spec
159 160
            $xmlNodeType = $xmlNode->attributes()["type"];
            if (!empty($xmlNodeType)) {
161
                // construct field type object
162
                $field_rfcls = $this->getNewField("OPNsense\\Base\\FieldTypes\\".$xmlNodeType);
163 164
            } else {
                // no type defined, so this must be a standard container (without content)
165
                $field_rfcls = $this->getNewField('OPNsense\Base\FieldTypes\ContainerField');
166 167 168 169 170 171 172 173
            }

            // generate full object name ( section.section.field syntax ) and create new Field
            if ($internal_data->__reference == "") {
                $new_ref = $tagName;
            } else {
                $new_ref = $internal_data->__reference . "." . $tagName;
            }
174
            $fieldObject = $field_rfcls->newInstance($new_ref, $tagName);
175 176 177 178 179 180 181 182 183

            // now add content to this model (recursive)
            if ($fieldObject->isContainer() == false) {
                $internal_data->addChildNode($tagName, $fieldObject);
                if ($xmlNode->count() > 0) {
                    // if fieldtype contains properties, try to call the setters
                    foreach ($xmlNode->children() as $fieldMethod) {
                        $method_name = "set".$fieldMethod->getName();
                        if ($field_rfcls->hasMethod($method_name)) {
Ad Schellevis's avatar
Ad Schellevis committed
184
                            $fieldObject->$method_name($this->parseOptionData($fieldMethod));
185 186 187 188 189 190 191 192 193 194 195 196
                        }
                    }
                }
                if ($config_data != null && isset($config_data->$tagName)) {
                    // set field content from config (if available)
                    $fieldObject->setValue($config_data->$tagName->__toString());
                }
            } else {
                // add new child node container, always try to pass config data
                if ($config_data != null && isset($config_data->$tagName)) {
                    $config_section_data = $config_data->$tagName;
                } else {
197
                    $config_section_data = null;
198 199 200 201 202 203
                }

                if ($fieldObject instanceof ArrayField) {
                    // handle Array types, recurring items
                    if ($config_section_data != null) {
                        foreach ($config_section_data as $conf_section) {
204 205 206 207 208 209 210
                            // Array items are identified by a UUID, read from attribute or create a new one
                            if (isset($conf_section->attributes()->uuid)) {
                                $tagUUID = $conf_section->attributes()['uuid']->__toString();
                            } else {
                                $tagUUID = $internal_data->generateUUID();
                            }

211
                            // iterate array items from config data
212
                            $child_node = new ContainerField($fieldObject->__reference . "." . $tagUUID, $tagName);
213
                            $this->parseXml($xmlNode, $conf_section, $child_node);
214 215 216 217
                            if (!isset($conf_section->attributes()->uuid)) {
                                // if the node misses a uuid, copy it to this nodes attributes
                                $child_node->setAttributeValue('uuid', $tagUUID);
                            }
218
                            $fieldObject->addChildNode($tagUUID, $child_node);
219 220
                        }
                    } else {
221
                        // There's no content in config.xml for this array node.
222 223
                        $tagUUID = $internal_data->generateUUID();
                        $child_node = new ContainerField($fieldObject->__reference . ".".$tagUUID, $tagName);
224
                        $child_node->setInternalIsVirtual();
225
                        $this->parseXml($xmlNode, $config_section_data, $child_node);
226
                        $fieldObject->addChildNode($tagUUID, $child_node);
227 228
                    }
                } else {
229
                    // All other node types (Text,Email,...)
230 231 232
                    $this->parseXml($xmlNode, $config_section_data, $fieldObject);
                }

233
                // add object as child to this node
234 235 236 237 238 239 240 241 242 243 244 245
                $internal_data->addChildNode($xmlNode->getName(), $fieldObject);
            }
        }
    }

    /**
     * Construct new model type, using it's own xml template
     * @throws ModelException if the model xml is not found or invalid
     */
    public function __construct()
    {
        // setup config handle to singleton config singleton
246
        $internalConfigHandle = Config::getInstance();
247 248 249 250 251 252 253

        // init new root node, all details are linked to this
        $this->internalData = new FieldTypes\ContainerField();

        // determine our caller's filename and try to find the model definition xml
        // throw error on failure
        $class_info = new \ReflectionClass($this);
254
        $model_filename = substr($class_info->getFileName(), 0, strlen($class_info->getFileName())-3) . "xml";
255
        if (!file_exists($model_filename)) {
256
            throw new ModelException('model xml '.$model_filename.' missing');
257 258 259
        }
        $model_xml = simplexml_load_file($model_filename);
        if ($model_xml === false) {
260
            throw new ModelException('model xml '.$model_filename.' not valid');
261 262
        }
        if ($model_xml->getName() != "model") {
263
            throw new ModelException('model xml '.$model_filename.' seems to be of wrong type');
264
        }
265
        $this->internal_mountpoint = $model_xml->mount;
266

267
        if (!empty($model_xml->version)) {
268
            $this->internal_model_version = (string)$model_xml->version;
269 270
        }

271 272
        // use an xpath expression to find the root of our model in the config.xml file
        // if found, convert the data to a simple structure (or create an empty array)
273
        $tmp_config_data = $internalConfigHandle->xpath($model_xml->mount);
274
        if ($tmp_config_data->length > 0) {
275
            $config_array = simplexml_import_dom($tmp_config_data->item(0));
276 277 278 279 280
        } else {
            $config_array = array();
        }

        // We've loaded the model template, now let's parse it into this object
281
        $this->parseXml($model_xml->items, $config_array, $this->internalData);
282 283 284 285 286 287 288
        // root may contain a version, store if found
        if (empty($config_array)) {
            // new node, reset
            $this->internal_current_model_version = "0.0.0";
        } elseif (!empty($config_array->attributes()['version'])) {
            $this->internal_current_model_version = (string)$config_array->attributes()['version'];
        }
289

290 291
        // trigger post loading event
        $this->internalData->eventPostLoading();
292 293 294 295 296 297 298

        // call Model initializer
        $this->init();
    }

    /**
     * reflect getter to internalData (ContainerField)
299
     * @param string $name property name
300 301 302 303 304 305 306 307 308
     * @return mixed
     */
    public function __get($name)
    {
        return $this->internalData->$name;
    }

    /**
     * reflect setter to internalData (ContainerField)
309 310
     * @param string $name property name
     * @param string $value property value
311 312 313
     */
    public function __set($name, $value)
    {
314
        $this->internalData->$name = $value;
315 316
    }

317 318 319 320 321 322 323 324 325
    /**
     * forward to root node's getFlatNodes
     * @return array all children
     */
    public function getFlatNodes()
    {
        return $this->internalData->getFlatNodes();
    }

326 327 328 329 330 331 332 333 334 335 336 337
    /**
     * get nodes as array structure
     * @return array
     */
    public function getNodes()
    {
        return $this->internalData->getNodes();
    }

    /**
     * structured setter for model
     * @param array|$data named array
Ad Schellevis's avatar
Ad Schellevis committed
338
     * @return array
339 340 341 342 343 344
     */
    public function setNodes($data)
    {
        return $this->internalData->setNodes($data);
    }

345 346
    /**
     * validate full model using all fields and data in a single (1 deep) array
347 348
     * @param bool $validateFullModel validate full model or only changed fields
     * @return \Phalcon\Validation\Message\Group
349
     */
350
    public function performValidation($validateFullModel = false)
351 352 353 354 355 356 357
    {
        // create a Phalcon validator and collect all model validations
        $validation = new \Phalcon\Validation();
        $validation_data = array();
        $all_nodes = $this->internalData->getFlatNodes();

        foreach ($all_nodes as $key => $node) {
358 359 360 361 362 363 364 365
            if ($validateFullModel || $node->isFieldChanged()) {
                $node_validators = $node->getValidators();
                foreach ($node_validators as $item_validator) {
                    $validation->add($key, $item_validator);
                }
                if (count($node_validators) > 0) {
                    $validation_data[$key] = $node->__toString();
                }
366 367 368 369 370 371 372 373 374 375 376 377
            }
        }

        if (count($validation_data) > 0) {
            $messages = $validation->validate($validation_data);
        } else {
            $messages = new \Phalcon\Validation\Message\Group();
        }

        return $messages;
    }

378 379 380 381
    /**
     * perform a validation on changed model fields, using the (renamed) internal reference as a source pointer
     * for the requestor to identify its origin
     * @param null|string $sourceref source reference, for example model.section
Ad Schellevis's avatar
Ad Schellevis committed
382
     * @param string $targetref target reference, for example section. used as prefix if no source given
383 384
     * @return array list of validation errors, indexed by field reference
     */
Ad Schellevis's avatar
Ad Schellevis committed
385
    public function validate($sourceref = null, $targetref = "")
386 387 388 389 390 391 392 393 394
    {
        $result = array();
        $valMsgs = $this->performValidation();
        foreach ($valMsgs as $field => $msg) {
            // replace absolute path to attribute for relative one at uuid.
            if ($sourceref != null) {
                $fieldnm = str_replace($sourceref, $targetref, $msg->getField());
                $result[$fieldnm] = $msg->getMessage();
            } else {
395
                $fieldnm = $targetref . $msg->getField();
Ad Schellevis's avatar
Ad Schellevis committed
396
                $result[$fieldnm] = $msg->getMessage();
397 398 399 400 401
            }
        }
        return $result;
    }

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    /**
     * render xml document from model including all parent nodes.
     * (parent nodes are included to ease testing)
     *
     * @return \SimpleXMLElement xml representation of the model
     */
    public function toXML()
    {
        // calculate root node from mountpoint
        $xml_root_node = "";
        $str_parts = explode("/", str_replace("//", "/", $this->internal_mountpoint));
        for ($i=0; $i < count($str_parts); $i++) {
            if ($str_parts[$i] != "") {
                $xml_root_node .= "<".$str_parts[$i].">";
            }
        }
        for ($i=count($str_parts)-1; $i >= 0; $i--) {
            if ($str_parts[$i] != "") {
                $xml_root_node .= "</".$str_parts[$i].">";
            }
        }

        $xml = new \SimpleXMLElement($xml_root_node);
        $this->internalData->addToXMLNode($xml->xpath($this->internal_mountpoint)[0]);
426 427 428 429
        // add this model's version to the newly created xml structure
        if (!empty($this->internal_current_model_version)) {
            $xml->xpath($this->internal_mountpoint)[0]->addAttribute('version', $this->internal_current_model_version);
        }
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

        return $xml;
    }

    /**
     * serialize model singleton to config object
     */
    private function internalSerializeToConfig()
    {
        // setup config handle to singleton config singleton
        $internalConfigHandle = Config::getInstance();
        $config_xml = $internalConfigHandle->object();

        // serialize this model's data to xml
        $data_xml = $this->toXML();

        // Locate source node (in theory this must return a valid result, delivered by toXML).
        // Because toXML delivers the actual xml including the full path, we need to find the root of our data.
        $source_node = $data_xml->xpath($this->internal_mountpoint);

        // find parent of mountpoint (create if it doesn't exists)
        $target_node = $config_xml;
        $str_parts = explode("/", str_replace("//", "/", $this->internal_mountpoint));
        for ($i=0; $i < count($str_parts)-1; $i++) {
            if ($str_parts[$i] != "") {
                if (count($target_node->xpath($str_parts[$i])) == 0) {
                    $target_node = $target_node->addChild($str_parts[$i]);
                } else {
                    $target_node = $target_node->xpath($str_parts[$i])[0];
                }
            }
        }

        // copy model data into config
        $toDom = dom_import_simplexml($target_node);
        $fromDom = dom_import_simplexml($source_node[0]);

        // remove old model data and write new
        foreach ($toDom->getElementsByTagName($fromDom->nodeName) as $oldNode) {
            $toDom->removeChild($oldNode);
        }
        $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
    }

    /**
     * validate model and serialize data to config singleton object.
     *
477
     * @param bool $validateFullModel by default we only validate the fields we have changed
478 479 480
     * @param bool $disable_validation skip validation, be careful to use this!
     * @throws \Phalcon\Validation\Exception validation errors
     */
481
    public function serializeToConfig($validateFullModel = false, $disable_validation = false)
482
    {
483 484 485 486 487 488 489 490 491
        // create logger to save possible consistency issues to
        $logger = new Syslog("config", array(
            'option' => LOG_PID,
            'facility' => LOG_LOCAL4
        ));

        // Perform validation, collect all messages and raise exception if validation is not disabled.
        // If for some reason the developer chooses to ignore the errors, let's at least log there something
        // wrong in this model.
492
        $messages = $this->performValidation($validateFullModel);
493 494 495
        if ($messages->count() > 0) {
            $exception_msg = "";
            foreach ($messages as $msg) {
496
                $exception_msg_part = "[".get_class($this).":".$msg->getField()."] ";
497
                $exception_msg_part .= $msg->getMessage();
498
                $exception_msg .= "$exception_msg_part\n";
499
                // always log validation errors
500
                $logger->error($exception_msg_part);
501 502
            }
            if (!$disable_validation) {
503 504 505 506 507
                throw new \Phalcon\Validation\Exception($exception_msg);
            }
        }
        $this->internalSerializeToConfig();
    }
508 509 510 511 512 513 514 515 516 517 518 519 520

    /**
     * find node by reference starting at the root node
     * @param string $reference node reference (point separated "node.subnode.subsubnode")
     * @return BaseField|null field node by reference (or null if not found)
     */
    public function getNodeByReference($reference)
    {
        $parts = explode(".", $reference);

        $node = $this->internalData;
        while (count($parts)>0) {
            $childName = array_shift($parts);
521
            if (isset($node->getChildren()[$childName])) {
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
                $node = $node->getChildren()[$childName];
            } else {
                return null;
            }
        }
        return $node;
    }

    /**
     * set node value by name (if reference exists)
     * @param string $reference node reference (point separated "node.subnode.subsubnode")
     * @param string $value
     * @return bool value saved yes/no
     */
    public function setNodeByReference($reference, $value)
    {
        $node =$this->getNodeByReference($reference);
        if ($node != null) {
            $node->setValue($value);
            return true;
        } else {
            return false;
        }
    }
546 547 548 549 550 551 552 553 554 555 556 557 558

    /**
     * Execute model version migrations
     * Every model may contain a migrations directory containing BaseModelMigration descendants, which
     * are executed in order of version number.
     *
     * The BaseModelMigration class should be named with the corresponding version
     * prefixed with an M and . replaced by _ for example : M1_0_1 equals version 1.0.1
     *
     */
    public function runMigrations()
    {
        if (version_compare($this->internal_current_model_version, $this->internal_model_version, '<')) {
559
            $upgradePerfomed = false;
560 561 562 563
            $logger = new Syslog("config", array('option' => LOG_PID, 'facility' => LOG_LOCAL4));
            $class_info = new \ReflectionClass($this);
            // fetch version migrations
            $versions = array();
564 565
            // set default migration for current model version
            $versions[$this->internal_model_version] =__DIR__."/BaseModelMigration.php";
566
            foreach (glob(dirname($class_info->getFileName())."/Migrations/M*.php") as $filename) {
Franco Fichtner's avatar
Franco Fichtner committed
567
                $version = str_replace('_', '.', explode('.', substr(basename($filename), 1))[0]);
568 569
                $versions[$version] = $filename;
            }
570

571 572 573 574 575
            uksort($versions, "version_compare");
            foreach ($versions as $mig_version => $filename) {
                if (version_compare($this->internal_current_model_version, $mig_version, '<') &&
                    version_compare($this->internal_model_version, $mig_version, '>=') ) {
                    // execute upgrade action
576 577 578 579 580 581
                    if (!strstr($filename, '/tests/app')) {
                        $mig_classname = explode('.', explode('/mvc/app/models', $filename)[1])[0];
                    } else {
                        // unit tests use a different namespace for their models
                        $mig_classname = "/tests".explode('.', explode('/mvc/tests/app/models', $filename)[1])[0];
                    }
582
                    $mig_classname = str_replace('/', '\\', $mig_classname);
583 584
                    // Phalcon's autoloader uses _ as a directory locator, we need to import these files ourselves
                    require_once $filename;
585
                    $mig_class = new \ReflectionClass($mig_classname);
586 587
                    $chk_class = empty($mig_class->getParentClass()) ? $mig_class :  $mig_class->getParentClass();
                    if ($chk_class->name == 'OPNsense\Base\BaseModelMigration') {
588 589 590
                        $migobj = $mig_class->newInstance();
                        try {
                            $migobj->run($this);
591
                            $upgradePerfomed = true;
592 593 594 595 596
                        } catch (\Exception $e) {
                            $logger->error("failed migrating from version " .
                                $this->internal_current_model_version .
                                " to " . $mig_version . " in ".
                                $class_info->getName() .
Franco Fichtner's avatar
Franco Fichtner committed
597
                                " [skipping step]");
598 599 600 601 602
                        }
                        $this->internal_current_model_version = $mig_version;
                    }
                }
            }
603 604 605
            // serialize to config after last migration step, keep the config data static as long as not all
            // migrations have completed.
            if ($upgradePerfomed) {
606 607 608 609 610
                try {
                    $this->serializeToConfig();
                } catch (\Exception $e) {
                    $logger->error("Model ".$class_info->getName() ." can't be saved, skip ( " .$e . " )");
                }
611
            }
612 613
        }
    }
614 615 616 617 618 619 620 621 622

    /**
     * return current version number
     * @return null|string
     */
    public function getVersion()
    {
        return $this->internal_current_model_version;
    }
623
}