Example #1
0
 /**
  * Callback
  *
  * Requires `file` field to be present if a record is created.
  *
  * Handles deletion of a record and corresponding file if the `delete` field is
  * present and has not a value of either `null` or `'0'.`
  *
  * Prevents `dirname`, `basename`, `checksum` and `delete` fields to be written to
  * database.
  *
  * Parses contents of the `file` field if present and generates a normalized path
  * relative to the path set in the `baseDirectory` option.
  *
  * @param Model $Model
  * @return boolean
  */
 function beforeSave(&$Model)
 {
     if (!$Model->exists()) {
         if (!isset($Model->data[$Model->alias]['file'])) {
             unset($Model->data[$Model->alias]);
             return true;
         }
     } else {
         if (isset($Model->data[$Model->alias]['delete']) && $Model->data[$Model->alias]['delete'] !== '0') {
             $Model->delete();
             unset($Model->data[$Model->alias]);
             return true;
         }
     }
     $blacklist = array('dirname', 'basename', 'checksum', 'delete');
     $whitelist = array('id', 'file', 'model', 'foreign_key', 'created', 'modified', 'alternative');
     foreach ($Model->data[$Model->alias] as $key => $value) {
         if (in_array($key, $whitelist)) {
             continue;
         }
         if (in_array($key, $blacklist)) {
             unset($Model->data[$Model->alias][$key]);
         }
     }
     extract($this->settings[$Model->alias]);
     if (isset($Model->data[$Model->alias]['file'])) {
         $File = new File($Model->data[$Model->alias]['file']);
         /* `baseDirectory` may equal the file's directory or use backslashes */
         $dirname = substr(str_replace(str_replace('\\', '/', $baseDirectory), null, str_replace('\\', '/', Folder::slashTerm($File->Folder->pwd()))), 0, -1);
         $result = array('dirname' => $dirname, 'basename' => $File->name);
         $Model->data[$Model->alias] = array_merge($Model->data[$Model->alias], $result);
     }
     return true;
 }
 /**
  * 指定されたレコードの論理削除を行う
  * @param Model $Model 削除を行うモデルのインスタンス
  * @param type $id 削除レコードのID
  * @return boolean 論理削除の結果(true:成功、false:失敗)
  * @throws NotFoundException 指定されたデータが存在しない
  * @throws FatalErrorException テーブルに削除フラグが無い
  */
 public function logicalDelete(Model $Model, $id = null)
 {
     if (empty($id)) {
         $id = $Model->id;
     }
     // 対象データが存在するか
     if (!$Model->exists($id)) {
         throw new NotFoundException('そんなIDないよ');
     }
     // このテーブルに削除フラグがあるか
     $tableConst = $Model->getDataSource()->describe($Model);
     //debug($tableConst);
     if (!isset($tableConst['delete_flg'])) {
         throw new FatalErrorException('削除フラグがないよ');
     }
     // 更新データ組立
     $data = array($Model->alias => array('id' => $id, 'delete_flg' => true));
     //debug($data);
     // 更新
     $sts = $Model->save($data, array('validate' => false));
     if ($sts === false) {
         return false;
     } else {
         return true;
     }
 }
 public function changeStatus(Model $Model, $status, $id = null, $force = false)
 {
     if ($id === null) {
         $id = $Model->getID();
     }
     if ($id === false) {
         return false;
     }
     $force = true;
     $Model->id = $id;
     if (!$Model->exists()) {
         throw new NotFoundException();
     }
     if ($force !== true) {
         $modelData = $Model->read();
         if ($modelData[$Model->alias]['status'] === $status) {
             CakeLog::write(LOG_WARNING, __d('webshop', 'The status of %1$s with id %2$d is already set to %3$s. Not making a change', strtolower(Inflector::humanize(Inflector::underscore($Model->name))), $id, $status), array('webshop'));
             return false;
         }
     } else {
         CakeLog::write(LOG_WARNING, __d('webshop', 'Status change of %1$s with id %2$d is being forced to %3$s', strtolower(Inflector::humanize(Inflector::underscore($Model->name))), $id, $status), array('webshop'));
     }
     $Model->saveField('status', $status);
     CakeLog::write(LOG_INFO, __d('webshop', 'Changed status of %1$s with id %2$d to %3$s', strtolower(Inflector::humanize(Inflector::underscore($Model->name))), $id, $status), array('webshop'));
     $eventData = array();
     $eventData[Inflector::underscore($Model->name)]['id'] = $id;
     $eventData[Inflector::underscore($Model->name)]['status'] = $status;
     $overallEvent = new CakeEvent($Model->name . '.statusChanged', $this, $eventData);
     $specificEvent = new CakeEvent($Model->name . '.statusChangedTo' . Inflector::camelize($status), $this, $eventData);
     CakeEventManager::instance()->dispatch($overallEvent);
     CakeEventManager::instance()->dispatch($specificEvent);
     return true;
 }
 /**
  * beforeSave is called before a model is saved. Returning false from a beforeSave callback
  * will abort the save operation.
  *
  * @param Model $model Model using this behavior
  * @param array $options Options passed from Model::save().
  * @return mixed False if the operation should abort. Any other result will continue.
  * @see Model::save()
  */
 public function beforeSave(Model $model, $options = array())
 {
     if (!empty($model->hasMany['Audit'])) {
         if ($model->id = !empty($model->id) ? $model->id : (!empty($model->data[$model->alias]['id']) ? $model->data[$model->alias]['id'] : '')) {
             $this->data[$model->id]['Audit']['entity'] = (!empty($model->plugin) ? $model->plugin . '.' : '') . $model->name;
             $this->data[$model->id]['Audit']['entity_id'] = $model->id;
             $this->data[$model->id]['Audit']['event'] = $model->exists() ? 'UPDATE' : 'CREATE';
             $this->data[$model->id]['Audit']['new'] = $this->data[$model->id]['Audit']['old'] = array();
             $this->data[$model->id]['Audit']['creator_id'] = !empty($model->data['Creator']['id']) ? $model->data['Creator']['id'] : null;
             $model->data = Hash::remove($model->data, 'Creator');
             if ($this->data[$model->id]['Audit']['event'] == 'CREATE') {
                 $this->data[$model->id]['Audit']['old'] = json_encode(array());
                 $this->data[$model->id]['Audit']['new'] = json_encode($model->data[$model->alias]);
             } else {
                 if ($this->data[$model->id]['Audit']['event'] == 'UPDATE') {
                     $old = $model->find('first', array('conditions' => array($model->alias . '.id' => $model->id), 'recursive' => -1));
                     foreach ($model->data[$model->alias] as $field => $value) {
                         if ($field == 'updated') {
                             continue;
                         }
                         if ($model->hasField($field) && $old[$model->alias][$field] != $value) {
                             $this->data[$model->id]['Audit']['old'][$field] = $old[$model->alias][$field];
                             $this->data[$model->id]['Audit']['new'][$field] = $value;
                         }
                     }
                     if (!empty($this->data[$model->id]['Audit']['old']) && !empty($this->data[$model->id]['Audit']['new'])) {
                         $this->data[$model->id]['Audit']['old'] = json_encode($this->data[$model->id]['Audit']['old']);
                         $this->data[$model->id]['Audit']['new'] = json_encode($this->data[$model->id]['Audit']['new']);
                     }
                 }
             }
         }
     }
     return parent::beforeSave($model, $options);
 }
Example #5
0
 public function exists($id = null)
 {
     if ($this->Behaviors->attached('SoftDelete')) {
         return $this->existsAndNotDeleted($id);
     } else {
         return parent::exists($id);
     }
 }
Example #6
0
 /**
  * Informa se o registro existe e esta ativo (não deletado).
  * Caso modelo não tenha o campo relacionado ao SoftDelete, apenas
  * retorna um Model::exists para o registro.
  *
  * @param  Model $Model
  * @param  int   $id    ID do registro
  * @return bool
  */
 public function active($Model, $id)
 {
     $schema = $Model->schema();
     if (!isset($schema[$this->settings[$Model->alias]['field']])) {
         return $Model->exists($id);
     }
     return (bool) $Model->find('count', array('conditions' => array($Model->alias . '.' . $Model->primaryKey => $id, $Model->alias . '.' . $this->settings[$Model->alias]['field'] => false), 'recursive' => -1, 'callbacks' => false));
 }
Example #7
0
function __autoload($modelname)
{
    if (Model::exists($modelname)) {
        include Model::getFullPath($modelname);
    }
    if (Form::exists($modelname)) {
        include Form::getFullPath($modelname);
    }
}
Example #8
0
 /**
  * Callback
  *
  * Adds metadata to be stored in table if a record is about to be created.
  *
  * @param Model $Model
  * @return boolean
  */
 function beforeSave(&$Model)
 {
     if ($Model->exists() || !isset($Model->data[$Model->alias]['file'])) {
         return true;
     }
     extract($this->settings[$Model->alias]);
     $Model->data[$Model->alias] += $this->metadata($Model, $Model->data[$Model->alias]['file'], $level);
     return true;
 }
 public function isLikedBy(Model $Model, $article_id, $user_id)
 {
     // If the item does not exist
     if (!$Model->exists($article_id)) {
         throw new NotFoundException();
     }
     $count = $Model->Like->find('count', array('conditions' => array('Like.article_id' => $article_id, 'Like.user_id' => $user_id)));
     return $count == 1;
 }
 /**
  * @param Model $Model
  * @param       $id
  *
  * @return bool
  */
 public function deactivate(Model $Model, $id)
 {
     if (empty($id)) {
         return false;
     }
     $Model->id = $id;
     if (!$Model->exists()) {
         return false;
     }
     if ($Model->saveField('active', false)) {
         return true;
     }
     return false;
 }
 function beforeSave(Model $model)
 {
     if ($this->settings[$model->alias]['has_created_by'] || $this->settings[$model->alias]['has_modified_by']) {
         $AuthSession = $this->settings[$model->alias]['auth_session'];
         $UserSession = $this->settings[$model->alias]['user_model'];
         $userId = Set::extract($_SESSION, $AuthSession . '.' . $UserSession . '.' . 'id');
         if ($userId) {
             $data = array($this->settings[$model->alias]['modified_by_field'] => $userId);
             if (!$model->exists()) {
                 $data[$this->settings[$model->alias]['created_by_field']] = $userId;
             }
             $model->set($data);
         }
     }
     return true;
 }
Example #12
0
 /**
  * beforeSave
  *
  * @param Model $model
  * @param Model $options
  * @return void
  * @access public
  */
 function beforeSave(&$model, $options)
 {
     if (!$model->exists()) {
         $ret = $this->PluginContent->find(array('PluginContent.name' => $model->data[$model->alias]['name']));
         if ($ret) {
             // 新規登録で既に登録されている場合は、重複エラーとする
             $model->invalidate('name', '既に登録されています。');
             return false;
         }
         $pluginContent = $this->_generatePluginContentData($model);
         $this->PluginContent->create($pluginContent);
     } else {
         $pluginContent = $this->_generatePluginContentData($model, $model->data[$model->alias]['id']);
         $this->PluginContent->set($pluginContent);
     }
     // バリデーション
     return $this->PluginContent->validates();
 }
 /**
  * Before save callback
  *
  * @param object $model Model using this behavior
  * @return boolean True if the operation should continue, false if it should abort
  * @access public
  */
 function beforeSave(Model $model, $options = array())
 {
     //if($model->alias != 'History' && $model->alias != 'User' && $model->alias != 'UserSession')$this->redirect(array('controller'=>'user','action'=>'dashboard'));
     //$this->redirect(array('action'=>'index'));
     if ($this->settings[$model->alias]['has_created_by'] || $this->settings[$model->alias]['has_modified_by']) {
         // We can't use this as there is no Auth / Sessions in CMS,
         $AuthSession = $this->settings[$model->alias]['auth_session'];
         $UserSession = $this->settings[$model->alias]['user_model'];
         if (isset($_SESSION['User'])) {
             $userId = $_SESSION['User']['id'];
             $dept_id = $_SESSION['User']['department_id'];
             $bran_id = $_SESSION['User']['branch_id'];
             $comp_id = $_SESSION['User']['company_id'];
             if ($userId) {
                 $data = array($this->settings[$model->alias]['modified_by_field'] => $userId);
                 if (!$model->exists()) {
                     $data[$this->settings[$model->alias]['created_by_field']] = $userId;
                     $data[$this->settings[$model->alias]['department_id_field']] = $dept_id;
                     $data[$this->settings[$model->alias]['branch_id_field']] = $bran_id;
                     $data[$this->settings[$model->alias]['company_id_field']] = $comp_id;
                 }
                 $model->set($data);
             }
         } else {
             $userId = '0';
             $dept_id = '0';
             $bran_id = '0';
             $comp_id = '0';
             if ($userId) {
                 $data = array($this->settings[$model->alias]['modified_by_field'] => $userId);
                 if (!$model->exists()) {
                     $data[$this->settings[$model->alias]['created_by_field']] = $userId;
                     $data[$this->settings[$model->alias]['department_id_field']] = $dept_id;
                     $data[$this->settings[$model->alias]['branch_id_field']] = $bran_id;
                     $data[$this->settings[$model->alias]['company_id_field']] = $comp_id;
                 }
                 $model->set($data);
             }
         }
     }
     return true;
 }
 public function edit(Model $model, $id = 0)
 {
     $model->render = 'auto';
     if ($model->exists($id)) {
         $this->recursive = 0;
         $data = $model->findById($id);
         if ($model->request->is(array('post', 'put'))) {
             if ($model->save($model->request->data)) {
                 $model->Message->alert('general.edit.success');
                 return $model->redirect(array('action' => get_class($model), 'view', $id));
             } else {
                 $model->Message->alert('general.edit.failed');
             }
         } else {
             $model->request->data = $data;
         }
     } else {
         $model->Message->alert('general.view.notExists');
         return $model->redirect(array('action' => get_class($model)));
     }
 }
Example #15
0
 /**
  * [isOwner description]
  *
  * @param Model $Model Model using this behavior.
  * @return boolean
  */
 public function isOwner(Model $Model)
 {
     if (!$Model->exists()) {
         return false;
     }
     if (!($owner = Hash::get($Model->data, $Model->alias . '.' . $this->settings[$Model->alias]['owner']['path']))) {
         $requireAuth = $Model->requireAuth;
         $Model->requireAuth = false;
         $owner = $Model->field($this->settings[$Model->alias]['owner']['path'], array($Model->alias . '.' . $Model->primaryKey => $Model->getID()));
         $Model->requireAuth = $requireAuth;
     }
     return $this->getCurrentUser($Model, $this->settings[$Model->alias]['owner']['auth']) == $owner;
 }
Example #16
0
 /**
  * Before save callback.
  *
  * Checks if at least one field is available.
  * Reads the current user id from the session.
  * If a user id is set it will fill...
  * ... the created_by field only when creating a record
  * ... the modified by field only if it is not in the data array
  * or the "force_modified" setting is set to true.
  *
  * @param Model $Model The model using this behavior.
  * @return bool True
  */
 public function beforeSave(Model $Model, $options = array())
 {
     $config = $this->settings[$Model->alias];
     if (!$config['has_created_by'] && !$config['has_modified_by']) {
         return true;
     }
     $authSession = $config['auth_session'];
     list($plugin, $userSession) = pluginSplit($config['user_model']);
     $userId = CakeSession::read($authSession . '.' . $userSession . '.id');
     if (!$userId) {
         return true;
     }
     $data = array();
     $modifiedByField = $config['modified_by_field'];
     if (!isset($Model->data[$Model->alias][$modifiedByField]) || $config['force_modified']) {
         $data[$config['modified_by_field']] = $userId;
     } else {
         $pos = strpos($config['modified_by_field'], '_');
         $field = substr($config['modified_by_field'], 0, $pos);
         $data[$field] = false;
     }
     if (!$Model->exists()) {
         $data[$config['created_by_field']] = $userId;
     }
     if ($data) {
         $Model->set($data);
     }
     return true;
 }
Example #17
0
 /**
  * Increment or decrement the comment count cache on the associated model
  *
  * @param Object $model Model to change count of
  * @param mixed $id The id to change count of
  * @param string $direction 'up' or 'down'
  * @return null
  */
 public function changeCommentCount(Model $model, $id = null, $direction = 'up')
 {
     if ($model->hasField('comments')) {
         if ($direction == 'up') {
             $direction = '+ 1';
         } elseif ($direction == 'down') {
             $direction = '- 1';
         } else {
             $direction = null;
         }
         $model->id = $id;
         if (!is_null($direction) && $model->exists(true)) {
             return $model->updateAll(array($model->alias . '.comments' => $model->alias . '.comments ' . $direction), array($model->alias . '.id' => $id));
         }
     }
     return false;
 }
Example #18
0
 /**
  * Creates a default set of conditions from the model if $conditions is null/empty.
  * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
  * were provided either null or false will be returned based on what was input.
  *
  * @param Model             $Model      The model to get conditions for.
  * @param string|array|bool $conditions Array of conditions, conditions string, null or false. If an array of
  *                                      conditions, or string conditions those conditions will be returned. With
  *                                      other values the model's existence will be checked. If the model doesn't
  *                                      exist a null or false will be returned depending on the input value.
  * @param bool              $useAlias   Use model aliases rather than table names when generating conditions
  *
  * @return mixed Either null, false, $conditions or an array of default conditions to use.
  * @see DboSource::update()
  * @see DboSource::conditions()
  */
 public function defaultConditions(Model $Model, $conditions, $useAlias = TRUE)
 {
     if (!empty($conditions)) {
         return $conditions;
     }
     $exists = $Model->exists();
     if (!$exists && ($conditions !== NULL || !empty($Model->__safeUpdateMode))) {
         return FALSE;
     } elseif (!$exists) {
         return NULL;
     }
     $alias = $Model->alias;
     if (!$useAlias) {
         $alias = $this->fullTableName($Model, FALSE);
     }
     return array("{$alias}.{$Model->primaryKey}" => $Model->getID());
 }
 /**
  * Checks if a model record exists
  *
  * @param Model $Model
  * @param array $data
  * @return bool
  */
 public function isBuyable(Model $Model, $data)
 {
     $Model->id = $data['CartsItem']['foreign_key'];
     return $Model->exists();
 }
 /**
  * convenience methods, just delete and then return $this.getLastSaveResult();
  */
 public function deleteAndReturn(Model $model)
 {
     if (!$model->exists()) {
         throw new NotFoundException(__('Invalid user'));
     }
     $model->delete();
     return $this->getLastSaveResult();
 }
Example #21
0
/**
 * Creates a default set of conditions from the model if $conditions is null/empty.
 * If conditions are supplied then they will be returned.  If a model doesn't exist and no conditions
 * were provided either null or false will be returned based on what was input.
 *
 * @param Model $model
 * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions,
 *   or string conditions those conditions will be returned.  With other values the model's existance will be checked.
 *   If the model doesn't exist a null or false will be returned depending on the input value.
 * @param boolean $useAlias Use model aliases rather than table names when generating conditions
 * @return mixed Either null, false, $conditions or an array of default conditions to use.
 * @see DboSource::update()
 * @see DboSource::conditions()
 */
	public function defaultConditions($model, $conditions, $useAlias = true) {
		if (!empty($conditions)) {
			return $conditions;
		}
		$exists = $model->exists();
		if (!$exists && $conditions !== null) {
			return false;
		} elseif (!$exists) {
			return null;
		}
		$alias = $model->alias;

		if (!$useAlias) {
			$alias = $this->fullTableName($model, false);
		}
		return array("{$alias}.{$model->primaryKey}" => $model->getID());
	}
Example #22
0
 /**
  * Baseado no Modelo passado e seus dados, retorna true
  * caso seja a criação de um novo registro ou modificação
  * de um registro já existente.
  *
  * @param Model $Model
  *
  * @return string 'create' ou 'modify' dependendo da operação
  */
 private function getAction(Model $Model)
 {
     $isCreate = true;
     $id = null;
     if (isset($Model->data[$Model->alias][$Model->primaryKey]) && !empty($Model->data[$Model->alias][$Model->primaryKey])) {
         $id = $Model->data[$Model->alias][$Model->primaryKey];
     } elseif (!empty($Model->id)) {
         $id = $Model->id;
     }
     if (!empty($id)) {
         $isCreate = !$Model->exists($id);
     }
     return $isCreate ? 'create' : 'modify';
 }
 /**
  * Callback
  *
  * Requires `file` field to be present if a record is created.
  *
  * Handles deletion of a record and corresponding file if the `delete` field is
  * present and has not a value of either `null` or `'0'.`
  *
  * Prevents `dirname`, `basename`, `checksum` and `delete` fields to be written to
  * database.
  *
  * Parses contents of the `file` field if present and generates a normalized path
  * relative to the path set in the `baseDirectory` option.
  *
  * @param Model $Model
  * @return boolean
  */
 function beforeSave(&$Model)
 {
     if (!$Model->exists()) {
         if (!isset($Model->data[$Model->alias]['file'])) {
             unset($Model->data[$Model->alias]);
             return true;
         }
     } else {
         if (isset($Model->data[$Model->alias]['delete']) && $Model->data[$Model->alias]['delete'] !== '0') {
             $Model->delete();
             unset($Model->data[$Model->alias]);
             return true;
         }
     }
     $blacklist = array('dirname', 'basename', 'checksum', 'delete');
     $whitelist = array('id', 'file', 'model', 'foreign_key', 'created', 'modified', 'alternative');
     foreach ($Model->data[$Model->alias] as $key => $value) {
         if (in_array($key, $whitelist)) {
             continue;
         }
         if (in_array($key, $blacklist)) {
             unset($Model->data[$Model->alias][$key]);
         }
     }
     extract($this->settings[$Model->alias]);
     if (isset($Model->data[$Model->alias]['file'])) {
         $File = $Model->alias . 's/' . $Model->data[$Model->alias];
         /* `baseDirectory` may equal the file's directory or use backslashes */
         $baseDirectory = 'files/';
         $result = array('dirname' => $dirname, 'basename' => $File->name);
         $Model->data[$Model->alias] = array_merge($Model->data[$Model->alias], $result);
     }
     return true;
 }
Example #24
0
 /**
  * Map 'change' and 'get' methods.
  *
  * @param Model $Model Model using this behavior.
  * @param string $method Real method's name.
  * @return mixed For 'change' operations, returns TRUE on success and FALSE otherwise. For
  *   'get' operations, returns a boolean when a state is provided by comparing it to the
  *   record's state field result, or returns the record's state field result.
  * @throws FatalErrorException If the state's field is not configured as such.
  * @see StateableBehaviorTest for examples of how arguments can be passed.
  */
 public function __call(Model $Model, $method)
 {
     foreach (array('change', 'get') as $do) {
         $field = str_replace($do, '', $method);
         if ($field != $method) {
             $field = Inflector::underscore($field);
             break;
         }
     }
     if (!array_key_exists($field, $this->settings[$Model->alias]['fields'])) {
         throw new FatalErrorException(__d('common', "Missing state field configuration ('%s')", $field));
     }
     $args = func_get_args();
     $id = $Model->getID();
     $state = isset($args[2]) ? $args[2] : null;
     $validate = isset($args[4]) ? $args[4] : true;
     if (isset($args[3])) {
         if (!is_bool($args[3])) {
             $id = $args[2];
             $state = $args[3];
         } else {
             $validate = $args[3];
         }
     } else {
         if (empty($id) && (isset($args[2]) || 'get' == $do) && $Model->exists($state)) {
             $id = $state;
             $state = null;
         }
     }
     if (empty($id) || !$Model->exists($id)) {
         return false;
     }
     $current = $Model->field($field, array($Model->alias . '.' . $Model->primaryKey => $id));
     if ('get' == $do) {
         if (!empty($state)) {
             return $state == $current;
         }
         return $current;
     }
     $Model->id = $id;
     $eventName = 'Model.' . $Model->name . '.';
     $fieldName = Inflector::camelize($field);
     $Event = new CakeEvent($eventName . 'beforeChange' . $fieldName, $Model, compact('field', 'state', 'validate'));
     list($Event->break, $Event->breakOn) = array(true, false);
     $result = $Model->triggerEvent($Event);
     if (false === $result || !($ret = $state != $current && $Model->saveField($field, $state, $validate))) {
         return false;
     }
     $Model->triggerEvent($eventName . 'afterChange' . $fieldName, $Model);
     return true;
 }