/** * Handle depreciation */ public function depreciate() { $depreciation_id = Model::find($this->model_id)->depreciation_id; if ($depreciation_id) { $depreciation_term = Depreciation::find($depreciation_id)->months; if ($depreciation_term > 0) { $purchase_date = strtotime($this->purchase_date); $todaymonthnumber = date("Y") * 12 + (date("m") - 1); //calculate the month number for today as YEAR*12 + (months-1) - number of months since January year 0 $purchasemonthnumber = date("Y", $purchase_date) * 12 + (date("m", $purchase_date) - 1); //purchase date calculated similarly $diff_months = $todaymonthnumber - $purchasemonthnumber; // fraction of value left $current_value = round(($depreciation_term - $diff_months) / $depreciation_term * $this->purchase_cost, 2); if ($current_value < 0) { $current_value = 0; } return $current_value; } else { return $this->purchase_cost; } } else { return $this->purchase_cost; } }
/** * Method used to read from a database session. * * @param int|string $id The key of the value to read * @return mixed The value of the key or false if it does not exist */ public function read($id) { $row = $this->_model->find('first', array('conditions' => array($this->_model->primaryKey => $id))); if (empty($row[$this->_model->alias]['data'])) { return false; } return $row[$this->_model->alias]['data']; }
/** * Find model by id * * @param int $id * @return Response */ public function find($id) { $model = $this->model->find($id); if (!$model) { array_push($this->errors, 'Could not find record with id = ' . $id . '.'); return false; } return $model; }
/** * Method used to read from a database session. * * @param int|string $id The key of the value to read * @return mixed The value of the key or false if it does not exist */ public function read($id) { $row = $this->_model->find('first', array('conditions' => array($this->_model->alias . '.' . $this->_model->primaryKey => $id))); if (empty($row[$this->_model->alias])) { return ''; } if (!is_numeric($row[$this->_model->alias]['data']) && empty($row[$this->_model->alias]['data'])) { return ''; } return (string) $row[$this->_model->alias]['data']; }
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++); } } }
/** * routineDrop * */ public function routineDrop(Model $model, $id, $conditions = array()) { $conditions["{$model->alias}.{$model->primaryKey}"] = $id; $current = $model->find('first', array('conditions' => $conditions)); if (empty($current)) { throw new NotFoundException(__('Invalid Access')); } // for SoftDeletable $model->set($current); $model->delete($id); $count = $model->find('count', array('conditions' => array("{$model->alias}.{$model->primaryKey}" => $id))); return $count === 0; }
/** * Clone model's data. * * @param Model $Model * @param array $options * @return [type] */ public function duplicate(Model $Model, $data, $config = array()) { $config = array_merge($this->settings[$Model->alias], $config); if (empty($Model->id) && empty($data[$Model->alias][$Model->primaryKey])) { throw new Exception(__d('common', "Missing primary key for duplicatable '%s' data", $Model->name)); } $id = $Model->id ? $Model->id : $data[$Model->alias][$Model->primaryKey]; $conditions = array($Model->primaryKey => $id) + (array) $this->settings[$Model->alias]['scope']; if (!empty($this->settings[$Model->alias]['scope']) && !$Model->find('count', compact('conditions'))) { return false; } $duplicateData = array($config['duplicatedKey'] => $id, $config['duplicatedModel'] => (!empty($Model->plugin) ? $Model->plugin . '.' : '') . $Model->name); $DuplicateModel = ClassRegistry::init($config['model']); $DuplicateModel->create(); $duplicateRecord = $DuplicateModel->find('first', array('conditions' => $duplicateData, 'recursive' => -1)); if (!empty($duplicateRecord)) { $DuplicateModel->id = $duplicateRecord[$DuplicateModel->alias][$DuplicateModel->primaryKey]; } foreach ((array) $config['mapFields'] as $field => $path) { $value = Hash::extract($data, $path); $duplicateData[$field] = array_pop($value); if (!empty($duplicateRecord[$DuplicateModel->alias][$field]) && $duplicateRecord[$DuplicateModel->alias][$field] === $duplicateData[$field]) { unset($duplicateData[$field]); } } if ((empty($duplicateRecord) || 1 < count($duplicateData)) && (!empty($DuplicateModel->id) || $DuplicateModel->create($duplicateData)) && !$DuplicateModel->save()) { return false; } return true; }
function find($type, $options = array()) { switch ($type) { case 'concatList': if (!isset($options['fields']) || count($options['fields']) < 2) { return parent::find('list', $options); } if (!isset($options['separator'])) { $options['separator'] = ' - '; } $options['recursive'] = -1; $list = parent::find('all', $options); for ($i = 1; $i <= 2; $i++) { $field[$i] = str_replace($this->alias . '.', '', $options['fields'][$i]); } /* return Set::combine($list, '{n}.'.$this->alias.'.'.$this->primaryKey, array('%s'.$options['separator'].'%s', '{n}.'.$this->alias.'.'.$field[1], '{n}.'.$this->alias.'.'.$field[2])); */ return Set::combine($list, '{n}.' . $this->alias . '.' . $this->{$field}[1], array('%s' . $options['separator'] . '%s', '{n}.' . $this->alias . '.' . $field[1], '{n}.' . $this->alias . '.' . $field[2])); break; default: return parent::find($type, $options); break; } }
public function makeModelStateCity($id) { $this->layout->body_class = ''; $make = Make::find(explode("-", $id)[0]); $model = Model::find(explode("-", $id)[1]); $state = null; foreach ($this->getStates() as $entity) { if (explode("-", $id)[2] == $entity['code']) { $state = $entity; break; } } $columns = array(array(), array(), array()); $cities = DB::select(DB::raw("SELECT DISTINCT city FROM vehicle WHERE make = :make AND model = :model AND state = :state ORDER BY city"), array('make' => $make->id, 'model' => $model->id, 'state' => $state['code'])); foreach ($cities as $key => $value) { $location = Location::where('state', '=', $state['code'])->where('city', '=', $value->city); if ($location->count()) { $zip = $location->first()->zip_code; $search = $make->make . ' ' . $model->model; $link = '/search?make=' . $make->id . '&model=' . $model->id . '&zip_code=' . $zip . '&search_text=' . $search . '&distance=50&page=1&sort=price-1'; $title = $make->make . ' ' . $model->model . ' for sale near ' . $value->city . ', ' . $state['code']; $city = array('link' => $link, 'title' => $title); array_push($columns[$key % 3], $city); } } $data = array('search_text' => '', 'make' => $make, 'model' => $model, 'state' => $state, 'columns' => $columns); $this->layout->contents = View::make('browse/make-model-state-city', $data); }
/** * 重构find方法,增加缓存的调用. * * @author 笨笨天才@20101127 * * $params['cache']=array('use'=>true,'config'=>'short'); * short是core.php定义的Cache:Config,默认为null * * @param string $type 输入类型 * @param mixed $params 输入参数 * @param bool $params['cache']['use'] 是否使用缓存标志 * @param string $params['cache']['config'] 缓存类型 * * @return mixed $data 返回值 */ public function find($type, $params = array()) { //!isset($params['cache']) if (isset($params['cache']) && $params['cache']['use'] !== false) { //判断是否不读取缓存数据 $cache_config = isset($params['cache']['config']) ? $params['cache']['config'] : null; $model = isset($this->name) ? '_' . $this->name : 'appmodel'; $paramsHash = md5(serialize($params)); $cache_key = $model . '_' . $type . '_' . $this->locale . '_' . $paramsHash; //根据模型名称,type参数,多语言,params组成缓存唯一序号 // echo $params['cache']['config']."----".$cache_key."<br />"; //pr($cache_config); $data = cache::read($cache_key, $cache_config); //print_r($params); if ($data) { // echo "cached:".$cache_key."<br /><pre>"; return $data; } else { //echo "not find cached:".$cache_key."<br /><pre>"; //print_r($params); $data = parent::find($type, $params); cache::write($cache_key, $data, $cache_config); //将数据库的值写入缓存 return $data; } } else { //echo "no cache:".$cache_key."<br /><pre>"; return parent::find($type, $params); } }
function find($conditions = null, $fields = array(), $order = null, $recursive = null) { if ($conditions != 'range') { return parent::find($conditions, $fields, $order, $recursive); } $file = Set::extract($fields, 'file'); if (empty($file)) { $file = ROOT . DS . APP_DIR . DS . 'plugins/mobileip/config/mobile_ips.yml'; } if (!file_exists($file)) { return false; } $cacheDir = $this->getCacheDir(); $folder = new Folder($cacheDir); $folder->create($cacheDir, 0777); $cacheFile = $this->getCacheFile(); if (file_exists($cacheFile) && $this->_getLastModified($file) <= filemtime($cacheFile)) { return include $cacheFile; } $mobile_ips =& Spyc::YAMLLoad($file); if (!is_array($mobile_ips)) { return false; } $data = $this->_get_ranges($mobile_ips); $file = new File($cacheFile, true); $file->write($data); $file->close(); return include $cacheFile; }
public function edit($id) { if (IS_POST) { //获取数据 if ($this->model->create() !== false) { //判断数据是否正确 if ($this->model->save() !== false) { $this->success('修改成功', cookie('__forward__')); return; //防止后面代码执行 } } $this->error('修改失败'); } else { //调用钩子函数 $this->_before_edit_view(); //给页面分配树的数据 $row = $this->model->find($id); //页面分配数据 $this->assign('meta_title', '编辑' . $this->meta_title); $this->assign('row', $row); $this->assign('id', $id); //加载视图 $this->display('add'); } }
public function refresh($record = null, $alias = null) { if ($record) { if (!$alias) { $alias = $this->_Model->alias; } if (isset($record[$alias])) { $this->_Record = $record[$alias]; } else { $this->_Record = $record; } foreach ($this->_associations as $associationName => $association) { if (isset($record[$associationName])) { $association->refresh($record[$associationName]); } else { $association->setInitialized(false); } } $this->_resetState(); } elseif (!empty($this->_Record[$this->getPrimaryKey()])) { $record = $this->_Model->find('first', array('recursive' => -1, 'conditions' => array($this->getPrimaryKey() => $this->_Record[$this->getPrimaryKey()]), 'activeRecord' => false)); if (!$record) { return $this; } $this->_Record = $record[$this->_Model->alias]; foreach ($this->_associations as $association) { $association->setInitialized(false); } $this->_resetState(); } return $this; }
/** * Tries do delete the versions that were generated from the file associated with the record. * * @param Model $Model Model using this behavior * @param boolean $cascade If true records that depend on this record will also be deleted * @return mixed False if the operation should abort. Any other result will continue. */ public function beforeDelete(Model $Model, $cascade = true) { if (!$cascade) { return true; } $result = $Model->find('first', array('conditions' => array($Model->primaryKey => $Model->id), 'fields' => array('dirname', 'basename'), 'recursive' => -1)); if (empty($result)) { return false; } if (empty($result[$Model->alias]['basename']) && empty($result[$Model->alias]['dirname'])) { return true; } $pattern = MEDIA_FILTER . '*' . DS . $result[$Model->alias]['dirname'] . DS; $pattern .= pathinfo($result[$Model->alias]['basename'], PATHINFO_FILENAME) . '.*'; $files = glob($pattern); // TODO There should be some safety precautions /* $versions = array_keys($Model->Generator->filter($Model, $result[$Model->alias]['basename'])); if (count($files) > count($versions)) { $message = 'GeneratedDeletable::beforeDelete - '; $message .= "Pattern `{$pattern}` matched more than number of versions. "; $message .= "Failing deletion of versions and record for `Media@{$Model->id}`."; CakeLog::write('warning', $message); return false; } */ foreach ($files as $file) { $file = new File($file); if (!$file->delete()) { return false; } } return true; }
/** * Main processing logic for DataTable * * @param mixed $object * @param mixed $scope */ public function process($object = null, $scope = array()) { if (is_array($object)) { $scope = $object; $object = null; } $settings = $this->_parseSettings($object); if (isset($settings['scope'])) { $scope = array_merge($settings['scope'], $scope); } if (isset($settings['findType'])) { $settings['type'] = $settings['findType']; } $query = array_diff_key($settings, array('conditions', 'columns', 'trigger', 'triggerAction', 'viewVar', 'maxLimit')); $total = $this->_object->find('count', $query); $this->_sort($settings); $this->_search($settings); $this->_paginate($settings); $this->settings[$this->_object->alias] = $settings; $results = parent::paginate($this->_object, $scope); $totalDisplayed = $this->Controller->request->params['paging'][$this->_object->alias]['count']; $dataTableData = array('iTotalRecords' => $total, 'iTotalDisplayRecords' => $totalDisplayed, 'sEcho' => isset($this->_params['sEcho']) ? intval($this->_params['sEcho']) : 0, 'aaData' => array()); $this->Controller->viewClass = 'DataTable.DataTableResponse'; $this->Controller->set($settings['viewVar'], $results); $this->Controller->set(compact('dataTableData')); if (isset($settings['view'])) { $this->Controller->view = $settings['view']; } }
function __updateCache(Model $model, $aggregate, $foreignKey, $foreignId) { $assocModel =& $model->{$aggregate['model']}; $calculations = array(); foreach ($aggregate as $function => $cacheField) { if (!in_array($function, $this->functions)) { continue; } $calculations[] = $function . '(' . $model->name . '.' . $aggregate['field'] . ') ' . $function . '_value'; } if (count($calculations) > 0) { $conditions = array($model->name . '.' . $foreignKey => $foreignId); if (array_key_exists('conditions', $aggregate)) { $conditions = am($conditions, $aggregate['conditions']); } else { $conditions = am($conditions, $model->belongsTo[$aggregate['model']]['conditions']); } $recursive = array_key_exists('recursive', $aggregate) ? $aggregate['recursive'] : null; $results = $model->find('first', array('fields' => $calculations, 'conditions' => $conditions, 'recursive' => $recursive, 'group' => $model->name . '.' . $foreignKey)); $newValues = array(); foreach ($aggregate as $function => $cacheField) { if (!in_array($function, $this->functions)) { continue; } $newValues[$cacheField] = $results[0][$function . '_value']; } $assocModel->id = $foreignId; $assocModel->save($newValues, false, array_keys($newValues)); } }
/** * Get mapping for the given type * * @param string $type Can be 'app' or a plugin name * @return mixed False in case of no file found or empty mapping, array with mapping */ public function getMapping($type) { if (!empty($this->__mapping[$type])) { return $this->__mapping[$type]; } $mapping = $this->__loadFile('map', $type); if (empty($mapping)) { return false; } $migrated = $this->Version->find('all', array( 'fields' => array('version', 'created'), 'conditions' => array($this->Version->alias . '.type' => $type), 'order' => array($this->Version->alias . '.version' => 'ASC'), 'recursive' => -1, )); $migrated = Set::combine($migrated, '/' . $this->Version->alias . '/version', '/' . $this->Version->alias . '/created'); ksort($mapping); foreach ($mapping as $version => $migration) { list($name, $class) = each($migration); $mapping[$version] = array( 'version' => $version, 'name' => $name, 'class' => $class, 'type' => $type, 'migrated' => null ); if (isset($migrated[$version])) { $mapping[$version]['migrated'] = $migrated[$version]; } } $this->__mapping[$type] = $mapping; return $mapping; }
public function find($id) { if (func_num_args() != 1) { exit("Wrong number of arguments in Comment::find()"); } return Model::find("Comment", $id); }
/** * Wrapper find to cache sql queries * @param array $conditions * @param array $fields * @param string $order * @param string $recursive * @return array */ function find($conditions = null, $fields = array(), $order = null, $recursive = null) { if (Configure::read('Cache.disable') === false && Configure::read('Cache.check') === true && (isset($fields['cache']) && $fields['cache'] !== false || $this->tempCache != null)) { if ($this->tempCache != null && isset($fields['cache']) && $fields['cache'] !== false) { $fields['cache'] = $this->tempCache; } $this->tempCache = null; $key = $fields['cache']; $expires = '+1 hour'; if (is_array($fields['cache'])) { $key = $fields['cache'][0]; if (isset($fields['cache'][1])) { $expires = $fields['cache'][1]; } } // Set cache settings Cache::config('sql_cache', array('prefix' => strtolower($this->name) . '-', 'duration' => $expires)); // Load from cache $results = Cache::read($key, 'sql_cache'); if (!is_array($results)) { $results = parent::find($conditions, $fields, $order, $recursive); Cache::write($key, $results, 'sql_cache'); } return $results; } // Not cacheing return parent::find($conditions, $fields, $order, $recursive); }
function find($conditions = null, $fields = array(), $order = null, $recursive = null) { $this->_trackQuery('find'); $res = parent::find($conditions, $fields, $order, $recursive); $this->_endQueryTrack(); return $res; }
/** * 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)); }
/** * Find the number of times each tag is used by it's id * Update the max value if a new high point is reached * @param int $id * @return int */ private function _findTagCount($id) { $count = $this->listModel->find('count', array('conditions' => array(strtolower($this->tagName) . '_id' => $id))); if ($count > $this->max) { $this->max = $count; } return $count; }
/** * See Model::find for the full docs. * * @param string $type * @param array $query * * @return array|null */ public function find($type = 'first', $query = array()) { $results = parent::find($type, $query); if (isset($query['objects']) && $query['objects'] === true) { $this->_toEntities($type, $query, $results); } return $results; }
private function setNewOriginal(Model $model, $duplicateKey) { $model->recursive = -1; $newOriginal = $model->find('neighbors', array('fields' => [$model->primaryKey, $this->getDuplicateKey($model)], 'conditions' => [$this->getDuplicateKey($model) => $duplicateKey], 'order' => ["{$model->primaryKey} ASC"]))['next'][$model->alias]; $newOriginal['duplicate'] = false; $model->create(); $model->save($newOriginal); }
/** * beforeSave callback * * @param Model $model The current model being used * @param array $options Callback options * * @return mixed */ public function beforeSave(Model $model, $options = array()) { $fields = (array) $this->__settings[$model->alias]['fields']; $scope = (array) $this->__settings[$model->alias]['scope']; $conditions = !empty($this->__settings[$model->alias]['conditions']) ? (array) $this->__settings[$model->alias]['conditions'] : array(); $slugfield = $this->__settings[$model->alias]['slugfield']; $hasFields = true; foreach ($fields as $field) { if (!$model->hasField($field)) { $hasFields = false; } if (!isset($model->data[$model->alias][$field])) { $hasFields = false; } } if ($hasFields && $model->hasField($slugfield) && ($this->__settings[$model->alias]['overwrite'] || empty($model->id))) { $toSlug = array(); foreach ($fields as $field) { $toSlug[] = $model->data[$model->alias][$field]; } $toSlug = join(' ', $toSlug); $slug = Inflector::slug($toSlug, $this->__settings[$model->alias]['separator']); if ($this->__settings[$model->alias]['lower']) { $slug = strtolower($slug); } if (strlen($slug) > $this->__settings[$model->alias]['length']) { $slug = substr($slug, 0, $this->__settings[$model->alias]['length']); } $conditions[$model->alias . '.' . $slugfield . ' LIKE'] = $slug . '%'; if (!empty($model->id)) { $conditions[$model->alias . '.' . $model->primaryKey . ' !='] = $model->id; } if (!empty($scope)) { foreach ($scope as $s) { if (isset($model->data[$model->alias][$s])) { $conditions[$model->alias . '.' . $s] = $model->data[$model->alias][$s]; } } } $sameUrls = $model->find('all', array('recursive' => -1, 'conditions' => $conditions)); $sameUrls = !empty($sameUrls) ? Hash::extract($sameUrls, '{n}.' . $model->alias . '.' . $slugfield) : array(); if (!empty($sameUrls)) { if (in_array($slug, $sameUrls)) { $begginingSlug = $slug; $index = 1; while ($index > 0) { if (!in_array($begginingSlug . $this->__settings[$model->alias]['separator'] . $index, $sameUrls)) { $slug = $begginingSlug . $this->__settings[$model->alias]['separator'] . $index; $index = -1; } $index++; } } } $model->data[$model->alias][$slugfield] = $slug; } return parent::beforeSave($model); }
/** * @param Model $Model * @param int $uid Facebook UID * @param array $params Model find() compatible params * @return mixed */ public function findUserByFacebookUid(Model $Model, $uid, $params = array()) { $settings = $this->settings[$Model->alias]; $scope = array($Model->alias . '.' . $settings['fields']['facebook_uid'] => $uid); if (isset($params['conditions']) && !empty($params['conditions'])) { $params['conditions'] = array_merge($params['conditions'], $scope); } return $Model->find('first', $params); }
/** * Executes stacked finders and returns the results. * `Model::find()` and the after states of the finders are executed at this time. * * @return array */ public function exec() { $options = $this->options->getOptions(); $results = $this->model->find('all', $options); foreach ($this->stack as $method) { $results = $this->model->dispatchMethod($method, array('after', $options, $results)); } return $results; }
public function find($type = 'first', $queryData = array()) { $results = parent::find($type, $queryData); if ($results || $type != 'first' && $type != '') { return $results; } else { return false; } }
public function find($id) { if ($instance = parent::find($id)) { $data = $this->relationSelect([$instance]); return current($data); } else { return $instance; } }
/** * キャビネットファイルのUnzip * * @param Model $model CabinetFile * @param array $cabinetFile CabinetFileデータ * @return bool * @throws InternalErrorException */ public function unzip(Model $model, $cabinetFile) { $model->begin(); try { // テンポラリフォルダにunzip $zipPath = WWW_ROOT . $cabinetFile['UploadFile']['file']['path'] . $cabinetFile['UploadFile']['file']['id'] . DS . $cabinetFile['UploadFile']['file']['real_file_name']; //debug($zipPath); App::uses('UnZip', 'Files.Utility'); $unzip = new UnZip($zipPath); $tmpFolder = $unzip->extract(); if ($tmpFolder === false) { throw new InternalErrorException('UnZip Failed.'); } $parentCabinetFolder = $model->find('first', ['conditions' => ['CabinetFileTree.id' => $cabinetFile['CabinetFileTree']['parent_id']]]); // unzipされたファイル拡張子のバリデーション // unzipされたファイルのファイルサイズバリデーション $files = $tmpFolder->findRecursive(); $unzipTotalSize = 0; foreach ($files as $file) { // $unzipTotalSize += filesize($file); // ここでは拡張子だけチェックする $extension = pathinfo($file, PATHINFO_EXTENSION); if (!$model->isAllowUploadFileExtension($extension)) { // NG $model->validationErrors = [__d('cabinets', 'Unzip failed. Contains does not allow file format.')]; return false; } } // ルームファイルサイズ制限 $maxRoomDiskSize = Current::read('Space.room_disk_size'); if ($maxRoomDiskSize !== null) { // nullだったらディスクサイズ制限なし。null以外ならディスクサイズ制限あり // 解凍後の合計 // 現在のルームファイルサイズ $roomId = Current::read('Room.id'); $roomFileSize = $model->getTotalSizeByRoomId($roomId); if ($roomFileSize + $unzipTotalSize > $maxRoomDiskSize) { $model->validationErrors[] = __d('cabinets', 'Failed to expand. The total size exceeds the limit.<br />' . 'The total size limit is %s (%s left).', CakeNumber::toReadableSize($roomFileSize + $unzipTotalSize), CakeNumber::toReadableSize($maxRoomDiskSize)); return false; } } // 再帰ループで登録処理 list($folders, $files) = $tmpFolder->read(true, false, true); foreach ($files as $file) { $this->_addFileFromPath($model, $parentCabinetFolder, $file); } foreach ($folders as $folder) { $this->_addFolderFromPath($model, $parentCabinetFolder, $folder); } } catch (Exception $e) { return $model->rollback($e); } $model->commit(); return true; }