<commit_before><?php

require_once 'lib/enjoyClassBase/validatorBase.php';

class modelBase {

    var $dataRep;
    var $tables;
    var $foreignKeys=array();
    var $dependents=array();
    var $subModels=array();
    var $config;
    var $fieldsConfig;
    var $primaryKey;
    var $result = array();
    var $label=array();
    var $incomingModels=array();
    
    var $bpmModel=null;
    
    /**
     * Base class for the Models
     * @param PDO $dataRep
     * @param array $config with the General Config
     * @param array $incomingModels with allready instanced Models
     */
    
    function __construct($dataRep, &$config,&$incomingModels=array()) {
        $this->dataRep = $dataRep;
        $this->config = &$config;
        $this->incomingModels = &$incomingModels;
        $this->dataRep->getInstance();

        if ($this->bpmModel==null) {
            require_once 'lib/commonModules/bpm/models/model_bpm.php';
            $this->bpmModel = new bpmModel($this->dataRep,$this->config,$this->tables);
        }        
    }

    /**
     * Fetchs registers limiting the results for pagination purpouses
     * @param array $options for the fetch method
     * @return array with the results
     */
    function fethLimited($options=array()) {
        
        $options["additional"][]="LIMIT 0,".$this->config["helpers"]["crud_listMaxLines"];
        return $this->fetch($options);
    
    }
    
    function insertRecord() {
        
        $validator= new validatorBase($this->config, $this->fieldsConfig,$this->primaryKey);
        $register=array();
        
        foreach ($this->fieldsConfig as $field => $configSection) {
            $addField=true;
            if ($field != $this->primaryKey and substr($field, 0,5)!="enjoy" ) {
                if (key_exists($this->tables.'_'.$field, $_REQUEST)) {
                    if ($_REQUEST[$this->tables.'_'.$field]=="") {
                        if (isset($configSection["definition"]["options"])) {
                            $fieldsOptions = $configSection["definition"]["options"];
                            if (!in_array("required", $fieldsOptions) and $_REQUEST[$this->tables.'_'.$field]=="") {
                                $addField=false; //avoid inserting data if not required and empty
                            }                    
                        }
                        else{
                            $addField=false; //avoid inserting data if not required and empty
                        }
                        
                    }
                    
                    if ($addField) {
                        $register[$field]=$_REQUEST[$this->tables.'_'.$field];
                        $options["fields"][]=$field;
                        $options["values"][0][]="'".$_REQUEST[$this->tables.'_'.$field]."'";
                        
                    }
                    
                }
            }
        }        
        
        $validationResult=$validator->validateFields($register);
        
        if ($validationResult!== true) {
            throw new Exception($validationResult);
//            exit($validationResult);
        }
        
        $validationResult=$validator->validateRegister($register);
        
        if ($validationResult!== true) {
            throw new Exception($validationResult);
//            exit($validationResult);
        }
        
        foreach ($this->subModels as $subModelEnry => $subModelConfig) {
            $subModel=&$subModelConfig['model'];
            $subModelValidator= new validatorBase($subModel->config, $subModel->fieldsConfig,$subModel->primaryKey);
            $freshFields=array();
            
            foreach ($subModel->fieldsConfig as $field => $configSection) {
                $freshField=true;#"roles_applications_id_app"
                if (isset($subModel->fieldsConfig[$field]["definition"]["options"])) {
                    $subModelFieldsOptions = $subModel->fieldsConfig[$field]["definition"]["options"];
                    if (in_array("required", $subModelFieldsOptions) ) {
                        $freshField=false;
                    }            
                }
                if ($freshField) {
                    $freshFields[]=$field;
                }                
                if (key_exists($subModel->tables.'_'.$field, $_REQUEST)) {
                    $subModelRegister[$field]=$_REQUEST[$subModel->tables.'_'.$field];
                }
            }        

            $subModelValidationResult=$subModelValidator->validateFields($subModelRegister,$freshFields);

            if ($subModelValidationResult!== true) {
                throw new Exception($subModelValidationResult);
            }
        }
        
        $okOperation=$this->insert($options);
        
        if ($okOperation) {
            $newPrimaryKey=$this->dataRep->getLastInsertId();

            foreach ($this->subModels as $subModelEnry => $subModelConfig) {

                $subModel=&$subModelConfig['model'];
                $linkerField=$subModelConfig['linkerField'];
                $linkedField=$subModelConfig['linkedField'];
                $linkedDataField=$subModelConfig['linkedDataField'];
                $type=$subModelConfig['type'];

                if (!isset($_REQUEST[$this->tables.'_'.$linkerField])) {
                    $_REQUEST[$subModel->tables.'_'.$linkedField]=$newPrimaryKey;
                }
                else{
                    $_REQUEST[$subModel->tables.'_'.$linkedField]=$_REQUEST[$this->tables.'_'.$linkerField];
                }


                $linkedDataFieldVar=$_REQUEST[$subModel->tables.'_'.$linkedDataField];

                if (is_array($linkedDataFieldVar)) {
                    foreach ($linkedDataFieldVar as $linkedDataFieldValue) {
                        $_REQUEST[$subModel->tables.'_'.$linkedDataField]=$linkedDataFieldValue;
                        $okOperation=$subModel->insertRecord();
                        
                        if (!$okOperation) {
                            break 2;
                        }
                        
                    }
                }elseif($linkedDataFieldVar!=''){
                    $okOperation=$subModel->insertRecord();
                    
                    if (!$okOperation) {
                        break;
                    }                    
                    
                }

            }
            
            if (count($this->config['bpmFlow']) and is_object($this->bpmModel)){ //checks if is object to avoid the nested bpmModel to insert 

                $_REQUEST[$this->bpmModel->tables.'_user']=$_SESSION["user"];
                $_REQUEST[$this->bpmModel->tables.'_id_process']=$newPrimaryKey;
                $_REQUEST[$this->bpmModel->tables.'_state']=$this->config['bpmFlow']['initialState'];
                $_REQUEST[$this->bpmModel->tables.'_date']=date('Y-m-d H:i:s');
                $_REQUEST[$this->bpmModel->tables.'_info']=$_REQUEST['bpm_info'];                
                $okOperation=$this->bpmModel->insertRecord();
                if (!$okOperation) {
                    throw new Exception("BPM: Insert Error");
                }            
            }
                 
        }
        
        return $okOperation;
        
    }
    
    /**
     * Generic insert tool
     * @param array $options with the fields and values
     */
    function insert($options) {

        list($fieldsSql, $valuesSql) = $this->getInsertConf($options);
        
        $sql = "INSERT INTO $this->tables $fieldsSql VALUES $valuesSql";

        try {
            $query = $this->dataRep->pdo->prepare($sql);
            $query->execute();
            $okOperation=true;
        } catch (PDOException $exc) {
            $error= new error($this->config);<commit_msg>avoids a bpm insert call upon the bpmModel itself<commit_after><?php

require_once 'lib/enjoyClassBase/validatorBase.php';

class modelBase {

    var $dataRep;
    var $tables;
    var $foreignKeys=array();
    var $dependents=array();
    var $subModels=array();
    var $config;
    var $fieldsConfig;
    var $primaryKey;
    var $result = array();
    var $label=array();
    var $incomingModels=array();
    
    var $bpmModel=null;
    
    /**
     * Base class for the Models
     * @param PDO $dataRep
     * @param array $config with the General Config
     * @param array $incomingModels with allready instanced Models
     */
    
    function __construct($dataRep, &$config,&$incomingModels=array()) {
        $this->dataRep = $dataRep;
        $this->config = &$config;
        $this->incomingModels = &$incomingModels;
        $this->dataRep->getInstance();

        if ($this->bpmModel==null) {
            require_once 'lib/commonModules/bpm/models/model_bpm.php';
            $this->bpmModel = new bpmModel($this->dataRep,$this->config,$this->tables);
        }        
    }

    /**
     * Fetchs registers limiting the results for pagination purpouses
     * @param array $options for the fetch method
     * @return array with the results
     */
    function fethLimited($options=array()) {
        
        $options["additional"][]="LIMIT 0,".$this->config["helpers"]["crud_listMaxLines"];
        return $this->fetch($options);
    
    }
    
    function insertRecord() {
        
        $validator= new validatorBase($this->config, $this->fieldsConfig,$this->primaryKey);
        $register=array();
        
        foreach ($this->fieldsConfig as $field => $configSection) {
            $addField=true;
            if ($field != $this->primaryKey and substr($field, 0,5)!="enjoy" ) {
                if (key_exists($this->tables.'_'.$field, $_REQUEST)) {
                    if ($_REQUEST[$this->tables.'_'.$field]=="") {
                        if (isset($configSection["definition"]["options"])) {
                            $fieldsOptions = $configSection["definition"]["options"];
                            if (!in_array("required", $fieldsOptions) and $_REQUEST[$this->tables.'_'.$field]=="") {
                                $addField=false; //avoid inserting data if not required and empty
                            }                    
                        }
                        else{
                            $addField=false; //avoid inserting data if not required and empty
                        }
                        
                    }
                    
                    if ($addField) {
                        $register[$field]=$_REQUEST[$this->tables.'_'.$field];
                        $options["fields"][]=$field;
                        $options["values"][0][]="'".$_REQUEST[$this->tables.'_'.$field]."'";
                        
                    }
                    
                }
            }
        }        
        
        $validationResult=$validator->validateFields($register);
        
        if ($validationResult!== true) {
            throw new Exception($validationResult);
//            exit($validationResult);
        }
        
        $validationResult=$validator->validateRegister($register);
        
        if ($validationResult!== true) {
            throw new Exception($validationResult);
//            exit($validationResult);
        }
        
        foreach ($this->subModels as $subModelEnry => $subModelConfig) {
            $subModel=&$subModelConfig['model'];
            $subModelValidator= new validatorBase($subModel->config, $subModel->fieldsConfig,$subModel->primaryKey);
            $freshFields=array();
            
            foreach ($subModel->fieldsConfig as $field => $configSection) {
                $freshField=true;#"roles_applications_id_app"
                if (isset($subModel->fieldsConfig[$field]["definition"]["options"])) {
                    $subModelFieldsOptions = $subModel->fieldsConfig[$field]["definition"]["options"];
                    if (in_array("required", $subModelFieldsOptions) ) {
                        $freshField=false;
                    }            
                }
                if ($freshField) {
                    $freshFields[]=$field;
                }                
                if (key_exists($subModel->tables.'_'.$field, $_REQUEST)) {
                    $subModelRegister[$field]=$_REQUEST[$subModel->tables.'_'.$field];
                }
            }        

            $subModelValidationResult=$subModelValidator->validateFields($subModelRegister,$freshFields);

            if ($subModelValidationResult!== true) {
                throw new Exception($subModelValidationResult);
            }
        }
        
        $okOperation=$this->insert($options);
        
        if ($okOperation) {
            $newPrimaryKey=$this->dataRep->getLastInsertId();

            foreach ($this->subModels as $subModelEnry => $subModelConfig) {

                $subModel=&$subModelConfig['model'];
                $linkerField=$subModelConfig['linkerField'];
                $linkedField=$subModelConfig['linkedField'];
                $linkedDataField=$subModelConfig['linkedDataField'];
                $type=$subModelConfig['type'];

                if (!isset($_REQUEST[$this->tables.'_'.$linkerField])) {
                    $_REQUEST[$subModel->tables.'_'.$linkedField]=$newPrimaryKey;
                }
                else{
                    $_REQUEST[$subModel->tables.'_'.$linkedField]=$_REQUEST[$this->tables.'_'.$linkerField];
                }


                $linkedDataFieldVar=$_REQUEST[$subModel->tables.'_'.$linkedDataField];

                if (is_array($linkedDataFieldVar)) {
                    foreach ($linkedDataFieldVar as $linkedDataFieldValue) {
                        $_REQUEST[$subModel->tables.'_'.$linkedDataField]=$linkedDataFieldValue;
                        $okOperation=$subModel->insertRecord();
                        
                        if (!$okOperation) {
                            break 2;
                        }
                        
                    }
                }elseif($linkedDataFieldVar!=''){
                    $okOperation=$subModel->insertRecord();
                    
                    if (!$okOperation) {
                        break;
                    }                    
                    
                }

            }
            
            if (count($this->config['bpmFlow']) and is_object($this->bpmModel)){ //checks if is object to avoid the nested bpmModel to insert 

                if ($this->config['bpmFlow']['bpmModel']==$this->tables) {
                    $_REQUEST[$this->bpmModel->tables.'_user']=$_SESSION["user"];
                    $_REQUEST[$this->bpmModel->tables.'_id_process']=$newPrimaryKey;
                    $_REQUEST[$this->bpmModel->tables.'_state']=$this->config['bpmFlow']['initialState'];
                    $_REQUEST[$this->bpmModel->tables.'_date']=date('Y-m-d H:i:s');
                    $_REQUEST[$this->bpmModel->tables.'_info']=$_REQUEST['bpm_info'];                
                    $okOperation=$this->bpmModel->insertRecord();
                    if (!$okOperation) {
                        throw new Exception("BPM: Insert Error");
                    }
                    
                }
                
            }
                 
        }
        
        return $okOperation;
        
    }
    
    /**
     * Generic insert tool
     * @param array $options with the fields and values
     */
    function insert($options) {

        list($fieldsSql, $valuesSql) = $this->getInsertConf($options);
        
        $sql = "INSERT INTO $this->tables $fieldsSql VALUES $valuesSql";

        try {
            $query = $this->dataRep->pdo->prepare($sql);
            $query->execute();
            $okOperation=true;
        } catch (PDOException $exc) {
            $error= new error($this->config);
{'fraction_non_alphanumeric': 0.13567618449952934, 'fraction_numerical': 0.0006275494195167869, 'mean_word_length': 1.567423876268729, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 149, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '950086', 'n_tokens_mistral': 4087, 'n_tokens_neox': 3913, 'n_words': 627}