Esempio n. 1
0
 /**
  * Transforms an object (model) to an integer (int).
  *
  * @param  \Model|null $model
  * @return int
  */
 public function transform($model)
 {
     if (empty($model)) {
         return 0;
     }
     return $model->getID();
 }
Esempio n. 2
0
 /**
  * Transforms an object (model) to an integer (int) .
  *
  * @param  Model|null $model
  * @return int
  */
 public function transform($model)
 {
     if (null === $model) {
         return 0;
     }
     return $model->getID();
 }
 public function createInvoice(Model $Model, $type = 'proforma', $id = null)
 {
     if ($id === null) {
         $id = $Model->getID();
     }
     if ($id === false) {
         return false;
     }
     $Model->id = $id;
     $Model->recursive = 2;
     $order = $Model->read();
     $invoice = array($this->Invoice->alias => array('type' => $type, 'status' => 'open', 'customer_id' => $order[$Model->alias]['customer_id']));
     foreach ($order['OrderProduct'] as $orderProduct) {
         $invoice[$this->Invoice->InvoiceProduct->alias][] = array('amount' => $orderProduct['amount'], 'price' => $orderProduct['price'], 'product_id' => $orderProduct['product_id'], 'tax_revision_id' => $orderProduct['tax_revision_id']);
     }
     foreach ($order['OrderShipment'] as $orderShipment) {
         $invoice[$this->Invoice->InvoiceShippingCost->alias][] = array('amount' => 15, 'shipment_id' => $orderShipment['shipment_id']);
     }
     foreach ($order['OrderPayment'] as $orderPayment) {
         $invoice[$this->Invoice->InvoiceTransactionCost->alias][] = array('amount' => 15, 'payment_id' => $orderPayment['payment_id']);
     }
     $status = $this->Invoice->saveAssociated($invoice, array('deep' => true));
     if (!$status) {
         return false;
     }
     return $this->Invoice->read();
 }
 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;
 }
Esempio n. 5
0
 /**
  * Checks to see if the current Model belongs to the User.
  *
  * @param Model $Model Model instance
  * @param int $userId The id of the user.
  * @param int $id The id of the current Model.  If null, will check if an id is set.
  * @return boolean True indicates it belongs to the user
  */
 public function ownedBy(Model $Model, $userId, $id = null)
 {
     if ($id === null) {
         $id = $Model->getID();
     }
     if ($id === false) {
         return false;
     }
     return (bool) $Model->find('count', array('conditions' => array($Model->alias . '.' . $Model->primaryKey => $id, $Model->alias . '.' . $this->settings['foreignKey'] => $userId), 'recursive' => -1, 'callbacks' => false));
 }
Esempio n. 6
0
 /**
  * Generates verification data for a Model.
  *
  * The verification key and code are two strings that can be used to verify a user is valid.
  * The verification timestamp can be used to check if the verification data has expired.
  *
  * @param Model $Model Model using this behavior
  * @param int $id The ID of the Model to generate verification data for
  * @return mixed On success Model::$data if its not empty or true, false on failure
  */
 public function generateVerification(Model $Model, $id = null)
 {
     if ($id) {
         $Model->id = $id;
     }
     // No ID, so cannot save the verification data
     if (!$Model->getID()) {
         return false;
     }
     // Generate verification data
     $data = array($Model->alias => array($Model->primaryKey => $id, $this->settings['fields']['key'] => Security::generateAuthKey(), $this->settings['fields']['code'] => uniqid(), $this->settings['fields']['timestamp'] => date("Y-m-d H:i:s"), 'modified' => false));
     return $Model->save($data, false, array($Model->primaryKey, $this->settings['fields']['key'], $this->settings['fields']['code'], $this->settings['fields']['timestamp']));
 }
Esempio n. 7
0
 public function comment(Model $Model, $id, $data = array())
 {
     $settings = $this->settings[$Model->alias];
     $commentAlias = $Model->alias . 'Comment';
     if (empty($data)) {
         $data = $id;
         $id = $Model->getID();
     }
     if (empty($id) || empty($data[$commentAlias])) {
         return false;
     }
     $data[$commentAlias] = array_merge(array('foreign_model' => $this->__pluginMerge($Model), 'foreign_key' => $id), $data[$commentAlias]);
     if (!empty($settings['validate'])) {
     }
     $Model->{$commentAlias}->create($data);
     if (!$Model->{$commentAlias}->save(null, !empty($settings['validate']))) {
         return false;
     }
     return true;
 }
 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;
 }
Esempio n. 9
0
 /**
  * Generates a query string using the same API Model::find() uses, calling the beforeFind process for the model
  *
  * @param Model $Model
  * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  * @return array Array of records
  * @link http://book.cakephp.org/view/1018/find
  */
 public function getQuery(Model $Model, $type = 'first', $query = array())
 {
     $Model->findQueryType = $type;
     $Model->id = $Model->getID();
     $query = $Model->buildQuery($type, $query);
     $this->findQueryType = null;
     return $this->_queryGet($Model, $query);
 }
Esempio n. 10
0
 /**
  * Method to generated DML SQL queries using find* style.
  *
  * Specifying 'fields' for new-notation 'list':
  *  - If no fields are specified, then 'id' is used for key and Model::$displayField is used for value.
  *  - If a single field is specified, 'id' is used for key and specified field is used for value.
  *  - If three fields are specified, they are used (in order) for key, value and group.
  *  - Otherwise, first and second fields are used for key and value.
  *
  * @param array $conditions SQL conditions array, or type of find operation (all / first / count / neighbors / list / threaded)
  * @param mixed $fields Either a single string of a field name, or an array of field names, or options for matching
  * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
  * @param integer $recursive The number of levels deep to fetch associated records
  * @return string SQL query string.
  * @access public
  * @link http://book.cakephp.org/view/449/find
  */
 public function getQuery(Model $model, $conditions = null, $fields = array(), $order = null, $recursive = null)
 {
     if (!is_string($conditions) || is_string($conditions) && !array_key_exists($conditions, $model->_findMethods)) {
         $type = 'first';
         $query = compact('conditions', 'fields', 'order', 'recursive');
     } else {
         list($type, $query) = array($conditions, $fields);
     }
     $db =& ConnectionManager::getDataSource($model->useDbConfig);
     $model->findQueryType = $type;
     $model->id = $model->getID();
     $query = array_merge(array('conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null, 'offset' => null, 'order' => null, 'page' => null, 'group' => null, 'callbacks' => true), (array) $query);
     if ($type != 'all') {
         if ($model->_findMethods[$type] === true) {
             $query = $model->{'_find' . ucfirst($type)}('before', $query);
         }
     }
     if (!is_numeric($query['page']) || intval($query['page']) < 1) {
         $query['page'] = 1;
     }
     if ($query['page'] > 1 && !empty($query['limit'])) {
         $query['offset'] = ($query['page'] - 1) * $query['limit'];
     }
     if ($query['order'] === null && $model->order !== null) {
         $query['order'] = $model->order;
     }
     $query['order'] = array($query['order']);
     if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
         $return = $model->Behaviors->trigger($model, 'beforeFind', array($query), array('break' => true, 'breakOn' => false, 'modParams' => true));
         $query = is_array($return) ? $return : $query;
         if ($return === false) {
             return null;
         }
         $return = $model->beforeFind($query);
         $query = is_array($return) ? $return : $query;
         if ($return === false) {
             return null;
         }
     }
     return $this->__queryGet($model, $query, $recursive);
 }
Esempio n. 11
0
 /**
  * Tokenizes a save transaction by checking if it contains any tokenizable fields.
  *
  * @param Model $Model
  * @param array $data Data to save.
  * @param boolean|array $validate Either a boolean, or an array.
  *   If a boolean, indicates whether or not to validate before saving.
  *   If an array, can have following keys:
  *
  *   - flash: An array of `CommonAppController::flash()` options to use on token verification.
  *   - validate: Set to true/false to enable or disable validation.
  *   - fieldList: An array of fields you want to allow for saving.
  *   - callbacks: Set to false to disable callbacks. Using 'before' or 'after'
  *      will enable only those callbacks.
  *
  * @param array $fieldList List of fields to allow to be saved
  * @return mixed On success Model::$data if its not empty or true, false on failure
  */
 public function tokenize(Model $Model, $data = null, $validate = true, $fieldList = array())
 {
     $config = $this->settings[$Model->alias];
     $flash = array();
     if (is_array($validate)) {
         $validate = array_merge(array('validate' => true), $validate);
         if (array_key_exists('flash', (array) $validate)) {
             $flash = $validate['flash'];
             unset($validate['flash']);
         }
     }
     if ($Model->getID()) {
         $initialState = $Model->find('first', array('conditions' => array($Model->primaryKey => $Model->id), 'recursive' => -1));
     } else {
         $Model->create();
     }
     $result = $Model->save($data, $validate, $fieldList);
     if (!$result) {
         return false;
     } else {
         if (!isset($initialState) && !in_array($config['on'], array(true, 'create'))) {
             return $result;
         }
     }
     $tokenizable = 0;
     foreach (array_keys($config['fields']) as $key) {
         if (array_key_exists($key, $data[$Model->alias])) {
             $tokenizable++;
             $field = $key;
         }
     }
     if (!$tokenizable) {
         return $result;
     }
     if (!empty($flash['redirect'])) {
         if (is_array($flash['redirect'])) {
             foreach ($flash['redirect'] as $k => $v) {
                 $flash['redirect'][$k] = str_replace('{$__cakeID__$}', $Model->id, $v);
             }
         } else {
             $flash['redirect'] = str_replace('{$__cakeID__$}', $Model->id, $flash['redirect']);
         }
     }
     $this->bindSecurityToken($Model);
     $token = array($Model->SecurityToken->alias => array('foreign_model' => $Model->className(), 'foreign_key' => $Model->id, 'foreign_data' => isset($initialState) ? $result : null, 'foreign_field' => null, 'foreign_flash' => $flash, 'expires' => '+3 days'));
     if (1 === $tokenizable) {
         $token[$Model->SecurityToken->alias]['foreign_field'] = $field;
         if (!empty($config['fields'][$field])) {
             $token[$Model->SecurityToken->alias]['foreign_flash'] = (array) $config['fields'][$field];
         }
     } else {
         if ($tokenizable && !empty($config['foreignData'])) {
             $token[$Model->SecurityToken->alias]['foreign_data'] = $config['foreignData'];
         }
     }
     if (isset($initialState)) {
         $Model->set($Model->save($initialState, false));
     } else {
         $Model->set($result);
     }
     $Model->SecurityToken->create($token);
     $Model->SecurityToken->set($Model->SecurityToken->save());
     $Model->triggerEvent('Model.' . $Model->alias . '.afterTokenize', $Model, array('token' => $Model->SecurityToken->data[$Model->SecurityToken->alias]));
     if (!empty($Model->SecurityToken->data)) {
         return $result;
     }
     return false;
 }
Esempio n. 12
0
 /**
  * Custom method to find all attached details or by section.
  *
  * @param Model $model Model to query.
  * @param string $func
  * @param string $state Either "before" or "after"
  * @param array $query
  * @param array $result
  * @return array
  */
 public function details(Model $Model, $queryData = null, $schema = false, $format = true)
 {
     $DetailModel = ClassRegistry::init($this->settings[$Model->alias]['alias']);
     if (is_string($queryData)) {
         $queryData = array('section' => $queryData);
     }
     $conditions = array($DetailModel->alias . '.foreign_key' => $Model->getID());
     if (!empty($queryData['section'])) {
         $section = $queryData['section'];
         $conditions[$DetailModel->alias . '.field LIKE'] = $section . '.%';
         unset($queryData['section']);
     }
     if (!empty($queryData['conditions'])) {
         $queryData['conditions'] = Hash::merge($conditions, $queryData['conditions']);
     }
     $fields = array($DetailModel->alias . '.field', $DetailModel->alias . '.value', $DetailModel->alias . '.label', 'foreign_key', 'foreign_model');
     if ($schema) {
         $fields = array($DetailModel->alias . '.field', $DetailModel->alias . '.input', $DetailModel->alias . '.data_type', $DetailModel->alias . '.label');
     }
     $order = array('position' => 'ASC');
     $recursive = -1;
     $results = $DetailModel->find('all', array_merge(compact('conditions', 'fields', 'order', 'recursive'), $queryData));
     return $this->detailsExtractSections($Model, $results, $section, $schema, $format);
 }
Esempio n. 13
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;
 }
Esempio n. 14
0
 /**
  * Check if a record exists for the given id
  *
  * @param Model $model
  * @param id
  * @return mixed
  */
 public function existsAndNotDeleted(Model $model, $id)
 {
     if ($id === null) {
         $id = $model->getID();
     }
     if ($id === false) {
         return false;
     }
     $exists = $model->find('count', array('conditions' => array($model->alias . '.' . $model->primaryKey => $id)));
     return $exists ? true : false;
 }
Esempio n. 15
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;
 }
Esempio n. 16
0
        HTMLstuff::RefererRedirect();
    }
} else {
    $Model = new Model(NULL, $lang->g('NavigationNewModel'));
}
if (array_key_exists('hidAction', $_POST) && $_POST['hidAction'] == 'ModelView') {
    $Model->setFirstName(Utils::NullIfEmpty($_POST['txtFirstName']));
    $Model->setLastName(Utils::NullIfEmpty($_POST['txtLastName']));
    if ($_POST['txtBirthDate'] && $_POST['txtBirthDate'] != 'YYYY-MM-DD' && strtotime($_POST['txtBirthDate']) !== FALSE) {
        $Model->setBirthDate(strtotime($_POST['txtBirthDate']));
    } else {
        $Model->setBirthDate(-1);
    }
    $tags = Tag::GetTagArray($_POST['txtTags']);
    $Model->setRemarks(Utils::NullIfEmpty($_POST['txtRemarks']));
    if ($Model->getID()) {
        if ($DeleteModel) {
            if ($CurrentUser->hasPermission(RIGHT_MODEL_DELETE) && Model::Delete($Model, $CurrentUser)) {
                header('location:index.php');
                exit;
            }
        } else {
            if ($CurrentUser->hasPermission(RIGHT_MODEL_EDIT) && Model::Update($Model, $CurrentUser)) {
                Tag2All::HandleTags($tags, $TagsThisModel, $TagsInDB, $CurrentUser, $Model->getID(), NULL, NULL, NULL);
                header('location:index.php');
                exit;
            }
        }
    } else {
        if ($CurrentUser->hasPermission(RIGHT_MODEL_ADD) && Model::Insert($Model, $CurrentUser)) {
            Tag2All::HandleTags($tags, $TagsThisModel, $TagsInDB, $CurrentUser, $Model->getID(), NULL, NULL, NULL);