Run the filters before each save.

@param Model $model
@param array $options
@return bool|mixed
519970
public function beforeSave(Model $model, $options = array()) {
        $settings = $this->settings[$model->alias];

        if ($model->data[$model->alias]) {
            foreach ($model->data[$model->alias] as $key => &$value) {
                if (isset($settings[$key])) {
                    $filters = $settings[$key];

                    // Strip tags
                    if (isset($filters['strip']) && $filters['strip']['filter']) {
                        $value = strip_tags($value, (string) $filters['strip']['allowed']);
                    }

                    // HTML escape
                    if (isset($filters['html']) && $filters['html']['filter']) {
                        $value = Sanitize::html($value, array(
                            'quotes' => $filters['html']['flags'],
                            'charset' => $filters['html']['encoding'],
                            'double' => $filters['html']['double']
                        ));
                    }

                    // Paranoid
                    if (isset($filters['paranoid']) && $filters['paranoid']['filter']) {
                        $value = Sanitize::paranoid($value, (array) $filters['paranoid']['allowed']);
                    }

                    // SQL escape
                    if (isset($filters['escape']) && $filters['escape']['filter']) {
                        $value = Sanitize::escape($value, $model->useDbConfig);
                    }
                }
            }
        }

        return true;
    }
1261809
protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model)
    {
        if ($this->request) {
            $this->processSortOnly($model);

            $model->setFilter(array('gto_id_token' => $this->token->getTokenId()));
        }
    }
463260
protected function saveModel(Model $model, array $options = []) {
		if ($model->isInsertForced()) {
			unset($model->_id);
			$model->unforceInsert();
		}
		
		// Update
		if (isset($model->_id)) {
			$data = $model->getDataForUpdate();
			unset($data['_id']);

			$id = $this->normalizeId($model->_id);
			
			return $this->getAdapter()->update(
				$this->getTableName(),
				['_id'  => $id],
				['$set' => $data],
				$options
			);
		}
		
		// Insert
		return $this->getAdapter()->insert(
			$this->getTableName(),
			$model->getDataForInsert(),
			$options
		);
	}
1167900
public function save(array $options = []) {
        $saved = parent::save($options);

        array_walk($this->translations, function($translation, $locale)  {
            if(! array_filter($translation))
                return false;

            $this->newTranslation($locale, $translation)
                ->save();
        });

        return $saved;
    }
416942
public function beforeValidate(Model $model, $options = array()) {
		$this->runtime[$model->alias]['data'] = $model->data[$model->alias];
      	$this->_fixPresian($model);
      return true;
    }
236263
public function create($model = null, array $options = [])
    {
        $options += ['process' => false, 'jsForm' => false];
        $options = $this->addClass($options, $this->_class('form'));

        $isProcess = $options['process'];

        if ($isProcess !== false) {
            $_options = [
                'url' => [
                    'plugin'     => $this->request->getParam('plugin'),
                    'controller' => $this->request->getParam('controller'),
                    'action'     => 'process'
                ]
            ];

            $options['jsForm'] = true;
            $options = Hash::merge($_options, $options);
        }

        $isJsForm = $options['jsForm'];
        if ($isJsForm) {
            $this->_isJsForm = true;
            $options = $this->addClass($options, 'jsForm');
        }

        unset($options['process'], $options['jsForm']);

        return parent::create($model, $options);
    }
1273737
protected function removeModel(Model $model, array $options = []) {
		if (! isset($model->_id)) {
			throw new Exceptions\OperationError('The model has no ID');
		}
		
		$id = $this->normalizeId($model->_id);
		
		return $this->getAdapter()->remove(
			$this->getTableName(),
			['_id' => $id],
			$options
		);
	}
30952
public function beforeDelete(Model $model, $cascade = true) {
        if (empty($model->id)) {
            return false;
        }

        return $this->deleteFiles($model, $model->id, array(), true);
    }
929015
protected function saveColumns(Model $model)
    {
        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $columns = $class::getColumns();
        $relations = $class::getRelations();
        $cols = [];
        $sets = [];
        $data = [];

        foreach ($columns as $column => $def) {
            if (isset($model->{$column}) && null === $model->{$column} && isset($def['default'])) {
                $sets[$column] = ':' . $column;
                $data[':'.$column] = $def['default'];
            } else {
                $cols[] = $column;
                $sets[$column] = ':' . $column;
                switch ($def['type']) {
                    case 'boolean':
                        $data[':' . $column] = (int)$model->{$column};
                        break;
                    default:
                        $data[':' . $column] = $model->{$column};
                        break;
                }
            }
        }

        foreach ($relations as $rel => $def) {
            switch ($def['type']) {
                case $class::BELONGS_TO:
                    $column = $class::getRelationLinkName($def);
                    if (!in_array($column, $cols)) {
                        // todo: test this!
                        //if (isset($model->{$column}) && !is_null($model->{$column})) {
                        if (isset($model->{$column})) {
                            $sets[$column] = ':' . $column;
                            $data[':'.$column] = $model->{$column};
                        } elseif (isset($model->{$rel}) && $model->{$rel} instanceof Model) {
                            $sets[$column] = ':' . $column;
                            $data[':'.$column] = $model->{$rel}->getPk();
                        }
                    }
                    break;
            }
        }

        $connection = $class::getDbConnection();
        if ($model->isNew()) {
            $query = new Query();
            $query->insert($class::getTableName())
                ->values($sets)
                ->params($data);
            $connection->execute($query);
            $model->{$class::PK} = $connection->lastInsertId();
        } else {
            $query = new Query();
            $query->update($class::getTableName())
                ->values($sets)
                ->where($this->quoteName($class::PK) . '='. $model->getPk())
                ->params($data);
            $connection->execute($query);
        }

        return $model;

    }
1341454
public function afterSave(Model $Model, $created, $options = array()) {
		if ($this->settings[$Model->alias]['auto'] === false) {
			return true;
		}
		if (!$Model->ShadowModel) {
			return true;
		}
		if ($created) {
			$Model->ShadowModel->create($Model->data, true);
			$Model->ShadowModel->set($Model->primaryKey, $Model->id);
			$Model->ShadowModel->set('version_created', date('Y-m-d H:i:s'));
			foreach ($Model->data as $alias => $aliasData) {
				if (isset($Model->ShadowModel->_schema[$alias])) {
					if (isset($aliasData[$alias]) && !empty($aliasData[$alias])) {
						$Model->ShadowModel->set($alias, implode(',', $aliasData[$alias]));
					}
				}
			}
			$success = (bool)$Model->ShadowModel->save();
			$Model->versionId = $Model->ShadowModel->id;
			return $success;
		}

		$habtm = array();
		foreach ($Model->getAssociated('hasAndBelongsToMany') as $assocAlias) {
			if (isset($Model->ShadowModel->_schema[$assocAlias])) {
				$habtm[] = $assocAlias;
			}
		}
		$data = $Model->find('first', array('contain' => $habtm, 'conditions' => array($Model->alias . '.' . $Model->primaryKey =>
					$Model->id)));

		$changeDetected = false;
		foreach ($data[$Model->alias] as $key => $value) {
			if (isset($data[$Model->alias][$Model->primaryKey]) && !empty($this->_oldData[$Model->alias]) && isset($this->_oldData[$Model->
				alias][$Model->alias][$key])) {

				$oldValue = $this->_oldData[$Model->alias][$Model->alias][$key];
			} else {
				$oldValue = '';
			}
			if ($value != $oldValue && !in_array($key, $this->settings[$Model->alias]['ignore'])) {
				$changeDetected = true;
			}
		}
		$Model->ShadowModel->create($data);
		if (!empty($habtm)) {
			foreach ($habtm as $assocAlias) {
				if (in_array($assocAlias, $this->settings[$Model->alias]['ignore'])) {
					continue;
				}
				$oldIds = Hash::extract($this->_oldData[$Model->alias], $assocAlias . '.{n}.id');
				if (!isset($Model->data[$assocAlias])) {
					$Model->ShadowModel->set($assocAlias, implode(',', $oldIds));
					continue;
				}
				$currentIds = Hash::extract($data, $assocAlias . '.{n}.id');
				$idChanges = array_diff($currentIds, $oldIds);
				if (!empty($idChanges)) {
					$Model->ShadowModel->set($assocAlias, implode(',', $currentIds));
					$changeDetected = true;
				} else {
					$Model->ShadowModel->set($assocAlias, implode(',', $oldIds));
				}
			}
		}
		unset($this->_oldData[$Model->alias]);
		if (!$changeDetected) {
			return true;
		}
		$Model->ShadowModel->set('version_created', date('Y-m-d H:i:s'));
		$Model->ShadowModel->save();
		$Model->versionId = $Model->ShadowModel->id;
		if (is_numeric($this->settings[$Model->alias]['limit'])) {
			$conditions = array('conditions' => array($Model->alias . '.' . $Model->primaryKey => $Model->id));
			$count = $Model->ShadowModel->find('count', $conditions);
			if ($count > $this->settings[$Model->alias]['limit']) {
				$conditions['order'] = $Model->alias . '.version_created ASC, ' . $Model->alias . '.version_id ASC';
				$oldest = $Model->ShadowModel->find('first', $conditions);
				$Model->ShadowModel->id = null;
				$Model->ShadowModel->delete($oldest[$Model->alias][$Model->ShadowModel->primaryKey]);
			}
		}
		return true;
	}
409303
public function save(DatagateAwareInterface $model, array $options = []) {
		if ($model->isEmpty()) {
			throw new Exceptions\OperationError('Model has no data');
		}
		
		if ($model instanceof Model) {
			return $this->saveModel($model, $options);
		}
		
		
		if ($model instanceof Collection) {
			return $this->saveCollection($model, $options);
		}
		
		throw new Exceptions\OperationError('Unknown instance of the "DatagateAwareInterface" was given: "' . get_class($model) . '"');
	}
34990
public function insert($model, array $options = [])
    {
        $values = $this->convertValues->convertToMongoValues(get_values($model), []);

        $result = $this->collection->insertOne($values, $options);
        if (false == $result->isAcknowledged()) {
            throw new \LogicException('Operation is not acknowledged');
        }

        set_object_id($model, new ObjectID((string) $result->getInsertedId()));
        $this->changesCollector->register($model, $values);

        return $result;
    }
128666
public function beforeSave(Model $model, $options = array()) {
        $settings = $this->settings[$model->alias];
        $columnMap = $settings['columnMap'];
        $statusMap = $settings['statusMap'];

        $data = $model->data[$model->alias];
        $points = 0;

        // Updating record, so leave it alone
        if (!empty($data[$model->primaryKey]) || $model->id) {
            return true;
        }

        if ($data) {
            $website = $data[$columnMap['website']];
            $content = $data[$columnMap['content']];
            $author = $data[$columnMap['author']];
            $email = $data[$columnMap['email']];

            // If referrer does not come from the originating domain
            $referrer = env('HTTP_REFERER');

            if ($referrer && strpos($referrer, trim(env('HTTP_HOST'), '/')) === false) {
                $points = $points - 20;
            }

            // Get links in the content
            preg_match_all('/(^|\s|\n)(?:(?:http|ftp|irc)s?:\/\/|www\.)(?:[-a-z0-9]+\.)+[a-z\.]{2,5}/is', $content, $matches);
            $links = $matches[0];

            $totalLinks = count($links);
            $length = mb_strlen($content);

            // How many links are in the body
            // +2 if less than 2, -1 per link if over 2
            if ($totalLinks > 2) {
                $points = $points - $totalLinks;
            } else {
                $points = $points + 2;
            }

            // How long is the body
            // +2 if more then 20 chars and no links, -1 if less then 20
            if ($length >= 20 && $totalLinks <= 0) {
                $points = $points + 2;
            } else if ($length >= 20 && $totalLinks == 1) {
                ++$points;
            } else if ($length < 20) {
                --$points;
            }

            // Number of previous comments from email
            // +1 per approved, -1 per spam
            $comments = $model->find('all', array(
                'fields' => array($columnMap['id'], $columnMap['status']),
                'conditions' => array($columnMap['email'] => $data[$columnMap['email']]),
                'recursive' => -1,
                'contain' => false
            ));

            if ($comments) {
                foreach ($comments as $comment) {
                    if (in_array($comment[$model->alias][$columnMap['status']], array($statusMap['spam'], $statusMap['deleted']))) {
                        --$points;
                    }

                    if ($comment[$model->alias][$columnMap['status']] == $statusMap['approved']) {
                        ++$points;
                    }
                }
            }

            // Keyword search
            // -1 per blacklisted keyword
            foreach ($settings['keywords'] as $keyword) {
                if (mb_stripos($content, $keyword) !== false) {
                    --$points;
                }
            }

            // URLs that have certain words or characters in them
            // -1 per blacklisted word
            // URL length
            // -1 if more then 30 chars
            foreach ($links as $link) {
                foreach ($settings['blacklist'] as $character) {
                    if (mb_stripos($link, $character) !== false) {
                        --$points;
                    }
                }

                foreach ($settings['keywords'] as $keyword) {
                    if (mb_stripos($link, $keyword) !== false) {
                        --$points;
                    }
                }

                if (mb_strlen($link) >= 30) {
                    --$points;
                }
            }

            // Check the website, author and comment for blacklisted
            // -1 per instance
            foreach ($settings['blacklist'] as $character) {
                if (mb_stripos($website, $character) !== false) {
                    --$points;
                }
            }

            foreach ($settings['keywords'] as $keyword) {
                if (mb_stripos($author, $keyword) !== false) {
                    --$points;
                }

                if (mb_stripos($content, $keyword) !== false) {
                    --$points;
                }
            }

            // Body starts with...
            // -10 points
            if ($pos = mb_stripos($content, ' ')) {
                $firstWord = mb_substr($content, 0, $pos);
            } else {
                $firstWord = trim($content);
            }

            $firstDisallow = array('interesting', 'cool', 'sorry') + $settings['keywords'];

            if (in_array(mb_strtolower($firstWord), $firstDisallow)) {
                $points = $points - 10;
            }

            // Author name has http:// in it
            // -2 points
            if (mb_stripos($author, 'http://') !== false) {
                $points = $points - 2;
            }

            // Body used in previous comment
            // -1 per exact comment
            $previousComments = $model->find('count', array(
                'conditions' => array($columnMap['content'] => $content),
                'recursive' => -1,
                'contain' => false
            ));

            if ($previousComments > 0) {
                $points = $points - $previousComments;
            }

            // Random character match
            // -1 point per 5 consecutive consonants
            $totalMatches = preg_match_all('/[^aAeEiIoOuU\s]{5,}+/i', $content);

            if ($totalMatches > 0) {
                $points = $points - $totalMatches;
            }

            // Email mostly consonants
            // -5 points
            if (preg_match('/[^aAeEiIoOuU\s]{5,}+/i', strstr($email, '@', true))) {
                $points = $points - 5;
            }

            // IP has been marked as spam before
            // -1 point per filtered IP
            if (!empty($data[$columnMap['ip']])) {
                $blockedIPs = $model->find('count', array(
                    'conditions' => array(
                        $columnMap['ip'] => $data[$columnMap['ip']],
                        $columnMap['status'] => array($statusMap['spam'], $statusMap['deleted'])
                    ),
                    'recursive' => -1,
                    'contain' => false
                ));

                if ($blockedIPs > 0) {
                    $points = $points - $blockedIPs;
                }
            }
        }

        // Finalize and save
        if ($points >= 1) {
            $status = $statusMap['approved'];
        } else if ($points == 0) {
            $status = $statusMap['pending'];
        } else if ($points <= $settings['deletion']) {
            $status = $statusMap['deleted'];
        } else {
            $status = $statusMap['spam'];
        }

        if ($status == $statusMap['deleted']) {
            $model->validationErrors[$columnMap['content']] = $settings['blockMessage'];

            return false;

        } else {
            $model->data[$model->alias][$columnMap['status']] = $status;

            if ($settings['savePoints']) {
                $model->data[$model->alias][$columnMap['points']] = $points;
            }

            if ($settings['sendEmail']) {
                $this->notify($model, $data, $status, $points);
            }
        }

        return true;
    }
817491
public function setUp ( Model $Model, $options	 = array() ) {
		 
		 if ( !empty($options['fieldsParaSumatoria']) ) {
		 	$this->fieldsParaSumatoria = $options['fieldsParaSumatoria'];
		 }

		 if ( !empty($options['fechaField']) ) {
		 	$this->fechaField = $options['fechaField'];
		 }
	}
46747
public function beforeSave(Model $model, $options = array()) {
        $alias = $model->alias;

        if (empty($model->data[$alias])) {
            return true;
        }

        // Loop through the data and upload the file
        foreach ($model->data[$alias] as $field => $file) {
            if (empty($this->settings[$alias][$field])) {
                continue;
            }

            // Gather attachment settings
            $attachment = $this->_settingsCallback($model, $this->settings[$alias][$field]);
            $data = array();

            // Initialize Transit
            $transit = new Transit($file);
            $transit->setDirectory($attachment['tempDir']);

            $this->_uploads[$alias] = $transit;

            // Set transformers and transporter
            $this->_addTransformers($model, $transit, $attachment);
            $this->_setTransporter($model, $transit, $attachment);

            // Attempt upload or import
            try {
                $overwrite = $attachment['overwrite'];
                $response = null;

                // File upload
                if (is_array($file)) {
                    $response = $transit->upload($overwrite);

                // Remote import
                } else if (preg_match('/^http/i', $file)) {
                    $response = $transit->importFromRemote($overwrite, $attachment['curl']);

                // Local import
                } else if (file_exists($file)) {
                    $response = $transit->importFromLocal($overwrite);

                // Stream import
                } else if (!empty($file)) {
                    $response = $transit->importFromStream($overwrite);
                }

                // Successful upload or import
                if ($response) {
                    $dbColumnMap = array($attachment['dbColumn']);
                    $transportConfig = array($this->_prepareTransport($attachment));

                    // Rename and move file
                    $data[$attachment['dbColumn']] = $this->_renameAndMove($model, $transit->getOriginalFile(), $attachment);

                    // Fetch exif data before transforming
                    $metaData = array();

                    foreach ($transit->getOriginalFile()->toArray() as $key => $value) {
                        if (substr($key, 0, 4) === 'exif' && $value) {
                            $metaData[$key] = $value;
                        }
                    }

                    // Transform the files and save their path
                    if ($attachment['transforms']) {
                        $transit->transform();

                        $transformedFiles = $transit->getTransformedFiles();
                        $count = 0;

                        foreach ($attachment['transforms'] as $transform) {
                            if ($transform['self']) {
                                $tempFile = $transit->getOriginalFile();
                                $dbColumnMap[0] = $transform['dbColumn'];

                            } else {
                                $tempFile = $transformedFiles[$count];
                                $dbColumnMap[] = $transform['dbColumn'];
                                $count++;

                                $transportConfig[] = $this->_prepareTransport($transform);
                            }

                            $data[$transform['dbColumn']] = $this->_renameAndMove($model, $tempFile, $transform);
                        }
                    }

                    $metaData = array_merge($transit->getOriginalFile()->toArray(), $metaData);

                    // Transport the files and save their remote path
                    if ($attachment['transport']) {
                        if ($transportedFiles = $transit->transport($transportConfig)) {
                            foreach ($transportedFiles as $i => $transportedFile) {
                                $data[$dbColumnMap[$i]] = $transportedFile;
                            }
                        }
                    }
                }

            // Trigger form errors if validation fails
            } catch (ValidationException $e) {
                $dbColumns = array_merge(array($attachment['dbColumn']), array_keys($attachment['transforms']));

                foreach ($dbColumns as $dbCol) {
                    unset($model->data[$alias][$dbCol]);
                }

                // Allow empty uploads
                if ($attachment['allowEmpty']) {
                    continue;
                }

                // Invalidate and stop
                $model->invalidate($field, __d('uploader', $e->getMessage()));

                if ($attachment['stopSave']) {
                    return false;
                }

            // Log exceptions that shouldn't be shown to the client
            } catch (Exception $e) {
                $model->invalidate($field, __d('uploader', $e->getMessage()));

                $this->log($e->getMessage(), LOG_DEBUG);

                // Rollback the files since it threw errors
                $transit->rollback();

                if ($attachment['stopSave']) {
                    return false;
                }
            }

            // Save file meta data
            $cleanup = $data;

            if ($attachment['metaColumns'] && $data && !empty($metaData)) {
                foreach ($attachment['metaColumns'] as $method => $column) {
                    if (isset($metaData[$method]) && $column) {
                        $data[$column] = $metaData[$method];
                    }
                }
            }

            // Merge upload data with model data
            if ($data) {
                $model->data[$alias] = $data + $model->data[$alias];
            }

            // Keep it in a loop, so it will delete all files
            // If we are doing an update, delete the previous files that are being replaced
            if ($model->id && $cleanup) {
                $this->_cleanupOldFiles($model, $cleanup);
            }
        }

        return true;
    }
1030434
public function check(Model $model, array $parameters = [])
    {
        $this->model      = $model;
        $this->parameters = $parameters;

        return $this->performCheck();
    }
941371
protected function saveHasOneRelations(Model $model)
    {
        foreach ($model->getRelations() as $name => $relation) {
            if ($model->{$name}() instanceof HasOneOrMany && ! is_null($relation)) {
                if (is_array($relation) || $relation instanceof \Traversable) {
                    $model->{$name}()->saveMany($relation);
                } else {
                    $model->{$name}()->save($relation);
                }
            }
        }
    }