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; }
public function fixOrder(Model $model, $conditions) { $count = $model->find('count', array('conditions' => $conditions)); if ($count > 0) { $list = $model->find('list', array('conditions' => $conditions, 'order' => array($model->alias . '.order'))); $order = 1; foreach ($list as $id => $name) { $model->id = $id; $model->saveField('order', $order++); } } }
public function afterSave(Model $Model, $created, $options = array()) { $isTree = in_array('Tree', array_map('strtolower', $Model->Behaviors->attached())); if ($Model->brwConfig['sortable'] and $created and !$isTree) { $data = $Model->data; $Model->saveField($Model->brwConfig['sortable']['field'], $Model->id); $Model->data = $data; } if ($isTree) { $Model->recover(); } }
/** * afterSave callback * * @param Model $Model Model using this behavior * @param boolean $created True if this save created a new record * @return void */ public function afterSave(Model $Model, $created) { if ($created) { $default = $Model->getDefaultRole(); $role_id = $default[$this->roleModel]['id']; $Model->saveField('role_id', $role_id); $this->syncAclRole($Model, array('model' => $this->roleModel, 'foreign_key' => $role_id)); } else { $new_role = array('model' => $this->roleModel, 'foreign_key' => $Model->field('role_id')); $this->syncAclRole($Model, $new_role, $this->oldRole[$Model->alias]); } return true; }
public function afterSave(Model $model, $created, $options = array()) { if (!empty($model->data[$model->name]['thumb']['name'])) { $file = $model->data[$model->name]['thumb']; // Current thumb $media_id = $model->field('media_id'); if ($media_id != 0) { $model->Media->delete($media_id); } // Update thumb $model->Media->save(array('ref_id' => $model->id, 'ref' => $model->name, 'file' => $file)); $model->saveField('media_id', $model->Media->id); } }
/** * @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; }
public function increment(Model $Model, $id = null, $field = null) { if (!$field && key($this->settings[$Model->alias]['fields'])) { $field = key($this->settings[$Model->alias]['fields']); } if (!$field) { return false; } if ($id === null) { $id = $Model->getID(); } if ($id === false) { return false; } $Model->id = $id; $currentValue = $Model->field($field, array($Model->alias . '.id' => $id)); $result = $Model->saveField($field, $currentValue + 1); if (!$result) { return false; } return $currentValue + 1; }
/** * Save each file to folder and update db * * @param Model $Model * @param boolean $created */ public function afterSave(Model $Model, $created) { if ($this->_saving) { return true; } $this->_saving = true; if (!empty($this->_uploadLater)) { foreach ($this->_uploadLater as $key => $fields) { foreach ($fields as $name => $file) { if (!is_uploaded_file($file['tmp_name'])) { continue; } $ext = strtolower(strrchr($file['name'], '.')); $filename = md5($file['name'] . $file['size']) . $ext; $dest = $this->settings['uploadLocation'] . Inflector::tableize($Model->alias) . DS; if (!file_exists($dest)) { new Folder($dest, true); } move_uploaded_file($file['tmp_name'], $dest . $filename); $Model->saveField($name, $filename); } } $this->_uploadLater = array(); } $this->_saving = false; $Model->data = $Model->findById($Model->id); return true; }
/** * Updates the model's state when a $model->save() call is performed * * @param Model $model The model being acted on * @param boolean $created Whether or not the model was created * @param array $options Options passed to save * @return boolean */ public function afterSave(Model $model, $created, $options = array()) { if ($created) { $model->read(); $model->saveField('state', $model->initialState); } return true; }
/** * Gets the current schema version from the DB. If schema_info doesn't exist - it tries to create it. * * @access protected * @return int Current schema version */ function _getMigrationVersion() { //load tables and see if schema_info already exists. If not, create it $sTables = $this->oMigrations->oDb->listSources(); if (!in_array($this->oMigrations->oDb->config['prefix'] . 'schema_info', $sTables)) { $this->oMigrations->oDb->query($this->oMigrations->create_table('schema_info', array(0 => 'no_id', 1 => 'no_dates', 'version' => array('type' => 'int', 'length' => 3, 'default' => '0')))); //feed it with some data App::import('model'); $oTemp_model = new Model(false, 'schema_info'); $oTemp_model->saveField('version', '0'); $this->iCurrent_version = 0; } else { App::import('model'); $oTemp_model = new Model(false, 'schema_info'); $this->iCurrent_version = $oTemp_model->field('version'); } }
public function afterSave(Model $model, $created, $options = array()) { $allowed = true; if (empty($model->data)) { $model->data = $model->read(); } if (!empty($this->settings[$model->alias]['scope'])) { foreach ($this->settings[$model->alias]['scope'] as $field => $value) { if ($model->data[$model->alias][$field] != $value) { $allowed = false; } } } if (!$this->settings[$model->alias]['calendarId']) { $allowed = false; } if (empty($model->data[$model->alias]['title'])) { $allowed = false; } $startTime = false; $endTime = false; if ($allowed && !empty($model->data[$model->alias]['date'])) { $startDate = strtotime($model->data[$model->alias]['date']); $startDate = date('Y-m-d', $startDate); if (!empty($model->data[$model->alias]['date_to'])) { $endDate = strtotime($model->data[$model->alias]['date_to']) + 24 * 3600; $endDate = date('Y-m-d', $endDate); } else { $endDate = strtotime($model->data[$model->alias]['date']) + 24 * 3600; $endDate = date('Y-m-d', $endDate); } } if ($allowed && !empty($model->data[$model->alias]['days'])) { date_default_timezone_set('UTC'); $until = gmdate("Ymd\\THis\\Z", strtotime($model->data[$model->alias]['date_to'])); $byDay = implode(',', $model->data[$model->alias]['days']); $recurrence = array(sprintf('RRULE:FREQ=WEEKLY;UNTIL=%s;BYDAY=%s', $until, $byDay)); $endDate = $startDate; } if (empty($startDate) || empty($endDate)) { $allowed = false; } if ($allowed) { $calendarId = $this->settings[$model->alias]['calendarId']; $data = array('summary' => $model->data[$model->alias]['title'], 'start' => array('date' => $startDate), 'end' => array('date' => $endDate)); if (!empty($recurrence)) { $data['recurrence'] = $recurrence; } if (!empty($model->data[$model->alias]['content'])) { $description = $model->data[$model->alias]['content']; $description = str_replace('<br />', PHP_EOL, $description); $description = strip_tags($description); $data['description'] = $description; } if (!empty($model->data[$model->alias]['location'])) { $location = $model->data[$model->alias]['location']; $location = strip_tags($location); $data['location'] = $location; } if (!empty($model->data[$model->alias]['color_id'])) { $data['colorId'] = $model->data[$model->alias]['color_id']; } $Events = ClassRegistry::init('Google.GoogleCalendarEvents'); if (empty($model->data[$model->alias]['google_event_id'])) { $saved = $Events->insert($calendarId, $data); $model->id = $model->data[$model->alias]['id']; return $model->saveField('google_event_id', $saved['id']); } else { $eventId = $model->data['Event']['google_event_id']; $data['sequence'] = $model->data['Event']['google_event_sequence'] + 1; $saved = $Events->update($calendarId, $eventId, $data); if ($saved) { $model->id = $model->data[$model->alias]['id']; $model->Behaviors->disable('GoogleCalendarEvent'); return $model->saveField('google_event_sequence', $data['sequence']); } } } else { if (!$allowed && !empty($model->data[$model->alias]['google_event_id'])) { $deleteAllowed = true; if (!$this->settings[$model->alias]['calendarId']) { $deleteAllowed = false; } if (empty($model->data[$model->alias]['google_event_id'])) { $deleteAllowed = false; } if ($deleteAllowed) { $Events = ClassRegistry::init('Google.GoogleCalendarEvents'); $calendarId = $this->settings[$model->alias]['calendarId']; $eventId = $model->data[$model->alias]['google_event_id']; $Events->delete($calendarId, $eventId); } } } return true; }
public function saveField($name, $value, $validate = false) { $this->useMasterDb(); return parent::saveField($name, $value, $validate); }
/** * Toggle field status * * @param $model Model instance * @param $id integer Model id * @param $status integer current status * @param $field string field name to toggle * @throws CakeException */ public function fieldToggle(Model $model, $id, $status, $field = 'status') { if (empty($id) || $status === null) { throw new CakeException(__d('croogo', 'Invalid content')); } $model->id = $id; $status = (int) (!$status); $this->_controller->layout = 'ajax'; if ($model->saveField($field, $status)) { $this->_controller->set(compact('id', 'status')); $this->_controller->render('Common/admin_toggle'); } else { throw new CakeException(__d('croogo', 'Failed toggling field %s to %s', $field, $status)); } }
/** * Método para "desdeletar" uma entrada do modelo. * * @param Model $Model * @param int $id */ public function unDelete(&$Model, $id) { $Model->id = $id; return $Model->saveField($this->settings[$Model->alias]['field'], false) !== false; }
/** * @param Model $Model * @param string $direction * @param int $steps Steps to jump. Defaults to 1. * @return bool Success */ protected function _moveUpDown(Model $Model, $direction, $id, $steps = 1) { // FIXME: Sort over more than one placement. if ($direction === 'down' && empty($this->settings[$Model->alias]['reverse'])) { $order = '<='; $findOrder = 'DESC'; } else { $order = '>='; $findOrder = 'ASC'; } $sort = $Model->find('list', array('fields' => array($this->settings[$Model->alias]['field']), 'conditions' => array('id' => $id))); if (empty($sort)) { return false; } list($sort) = array_values($sort); $data = $Model->find('list', array('fields' => array('id', $this->settings[$Model->alias]['field']), 'conditions' => array($this->settings[$Model->alias]['field'] . ' ' . $order => $sort), 'order' => array($this->settings[$Model->alias]['field'] => $findOrder), 'limit' => $steps + 1)); $value = end($data); $key = key($data); if ($key == $id) { return; } $lastId = $Model->id; if ($sort == $value) { if ($direction === 'down' && empty($this->settings[$Model->alias]['reverse'])) { $value++; } else { $value--; } } $Model->id = $key; $Model->saveField($this->settings[$Model->alias]['field'], $sort); $Model->id = $id; $Model->saveField($this->settings[$Model->alias]['field'], $value); $Model->id = $lastId; return true; }
/** * Remove the current node from the tree, and reparent all children up one level. * * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted * after the children are reparented. * * @param Model $Model Model instance * @param mixed $id The ID of the record to remove * @param boolean $delete whether to delete the node after reparenting children (if any) * @return boolean true on success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree */ public function removeFromTree($Model, $id = null, $delete = false) { if (is_array($id)) { extract(array_merge(array('id' => null), $id)); } extract($this->settings[$Model->alias]); list($node) = array_values($Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive))); if ($node[$right] == $node[$left] + 1) { if ($delete) { return $Model->delete($id); } else { $Model->id = $id; return $Model->saveField($parent, null); } } elseif ($node[$parent]) { list($parentNode) = array_values($Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $node[$parent]), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive))); } else { $parentNode[$right] = $node[$right] + 1; } $db = ConnectionManager::getDataSource($Model->useDbConfig); $Model->updateAll(array($parent => $db->value($node[$parent], $parent)), array($Model->escapeField($parent) => $node[$Model->primaryKey])); $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1)); $this->_sync($Model, 2, '-', '> ' . $node[$right]); $Model->id = $id; if ($delete) { $Model->updateAll(array($Model->escapeField($left) => 0, $Model->escapeField($right) => 0, $Model->escapeField($parent) => null), array($Model->escapeField() => $id)); return $Model->delete($id); } else { $edge = $this->_getMax($Model, $scope, $right, $recursive); if ($node[$right] == $edge) { $edge = $edge - 2; } $Model->id = $id; return $Model->save(array($left => $edge + 1, $right => $edge + 2, $parent => null), array('callbacks' => false)); } }
/** * Undeletes a record * * @param Model $Model using this behavior of model * @param int $id record id * @return bool */ public function undelete(Model $Model, $id = null) { if ($id) { $Model->id = $id; } if (!$Model->id) { return false; } $deleteCol = 'deleted'; if (!$Model->hasField($deleteCol)) { return false; } $Model->set($deleteCol, null); return $Model->saveField($deleteCol, null); }
/** * Confirm * * @param Model $Model * @param string $field * @param int $id * @param array $data * * @throws InvalidArgumentException * @return boolean */ public function confirm(Model $Model, $field, $id, $data = array()) { if (empty($field) || empty($id) || !$Model->hasField($field) || !$Model->hasField('confirm_' . $field)) { throw new InvalidArgumentException('Invalid arguments'); } $user = $Model->find('first', array('conditions' => array($Model->alias . '.' . $Model->primaryKey => $id))); $Model->id = $id; if ($Model->saveField('confirm_' . $field, true) && $Model->Tokenization->deleteAll(array($Model->Tokenization->alias . '.user_id' => $user[$Model->alias][$Model->primaryKey], $Model->Tokenization->alias . '.field' => $field))) { return $user[$Model->alias][$Model->primaryKey]; } return false; }
/** * 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; }