Ejemplo 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();
 }
 /**
  * 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);
 }
Ejemplo n.º 3
0
Archivo: UfDAO.php Proyecto: cokita/srp
 public static function remover(Model $uf)
 {
     if ($uf->get("id")) {
         $sql = "delete from uf where id = :id";
     }
     return self::exec($sql, $uf);
 }
Ejemplo n.º 4
0
function create_topic($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die('', 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        $model = new Model();
        if (!isset($input_data['name'])) {
            $input_data['name'] = '';
        }
        $topic_id = $model->create_topic($input_data['name']);
        if ($topic_id) {
            http_response_code(201);
            header('Content-Type: text/plain');
            echo '/topics/' . $topic_id;
            die;
        } else {
            Util::output_errors_and_die('', 400);
        }
    } catch (ConflictException $e) {
        Util::output_errors_and_die($e->getMessage(), 409);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Ejemplo n.º 5
0
 /**
  * Adjust configs like: $Model->Behaviors-attach('Tools.DecimalInput', array('fields'=>array('xyz')))
  * leave fields empty to auto-detect all float inputs
  *
  * @return void
  */
 public function setup(Model $Model, $config = array())
 {
     $this->settings[$Model->alias] = $this->_defaultConfig;
     if (!empty($config['strict'])) {
         $this->settings[$Model->alias]['transform']['.'] = '#';
     }
     if ($this->settings[$Model->alias]['localeconv'] || !empty($config['localeconv'])) {
         // use locale settings
         $conv = localeconv();
         $loc = array('decimals' => $conv['decimal_point'], 'thousands' => $conv['thousands_sep']);
     } elseif ($configure = Configure::read('Localization')) {
         // Use configure settings
         $loc = (array) $configure;
     }
     if (!empty($loc)) {
         $this->settings[$Model->alias]['transform'] = array($loc['thousands'] => $this->settings[$Model->alias]['transform']['.'], $loc['decimals'] => $this->settings[$Model->alias]['transform'][',']);
     }
     $this->settings[$Model->alias] = $config + $this->settings[$Model->alias];
     $numberFields = array();
     $schema = $Model->schema();
     foreach ($schema as $key => $values) {
         if (isset($values['type']) && !in_array($key, $this->settings[$Model->alias]['fields']) && in_array($values['type'], $this->settings[$Model->alias]['observedTypes'])) {
             array_push($numberFields, $key);
         }
     }
     $this->settings[$Model->alias]['fields'] = array_merge($this->settings[$Model->alias]['fields'], $numberFields);
 }
Ejemplo n.º 6
0
 /**
  * Bind tag assocations
  *
  * @param Model $model Model instance that behavior is attached to
  * @return void
  */
 public function bindTagAssociations(Model $model)
 {
     extract($this->settings[$model->alias]);
     list($plugin, $withClass) = pluginSplit($withModel, true);
     $model->bindModel(array('hasAndBelongsToMany' => array($tagAlias => array('className' => $tagClass, 'foreignKey' => $foreignKey, 'associationForeignKey' => $associationForeignKey, 'unique' => true, 'conditions' => array($withClass . '.model' => $model->name), 'fields' => '', 'dependent' => true, 'with' => $withModel))), $resetBinding);
     $model->{$tagAlias}->bindModel(array('hasMany' => array($taggedAlias => array('className' => $taggedClass))), $resetBinding);
 }
 /**
  * Recursively parses joins
  *
  * @param Model $Model
  * @param array $joins
  * @return array
  */
 protected function _parseJoins(Model $Model, $joins, $defaults = array())
 {
     $ds = $Model->getDataSource();
     $defaults = array_merge($this->_defaults, $defaults);
     if (isset($joins['defaults'])) {
         $defaults = array_merge($defaults, $joins['defaults']);
         unset($joins['defaults']);
     }
     foreach ((array) $joins as $association => $options) {
         if (is_string($options)) {
             if (is_numeric($association)) {
                 $association = $options;
                 $options = array();
             } else {
                 $options = (array) $options;
             }
         }
         $AssociatedModel = $this->_associatedModel($Model, $association);
         $deeperAssociations = array_diff_key($options, $defaults);
         $options = array_merge($defaults, $options);
         $this->_join($Model, $association, $options['conditions'], $options['type']);
         $fields = false;
         if ($options['fields'] === true) {
             $fields = null;
         } elseif (!empty($options['fields'])) {
             $fields = $options['fields'];
         }
         if ($fields !== false) {
             $this->_query['fields'] = array_merge($this->_query['fields'], $ds->fields($AssociatedModel, null, $fields));
         }
         if (!empty($deeperAssociations)) {
             $this->_parseJoins($AssociatedModel, $deeperAssociations, $defaults);
         }
     }
 }
Ejemplo n.º 8
0
function getMsgList($parm = array())
{
    $M = new Model('member_msg');
    $pre = C('DB_PREFIX');
    $field = true;
    $orderby = " id DESC";
    if ($parm['pagesize']) {
        //分页处理
        import("ORG.Util.Page");
        $count = $M->where($parm['map'])->count('id');
        $p = new \Org\Util\Page($count, $parm['pagesize']);
        $page = $p->show();
        $Lsql = "{$p->firstRow},{$p->listRows}";
        //分页处理
    } else {
        $page = "";
        $Lsql = "{$parm['limit']}";
    }
    $data = M('member_msg')->field(true)->where($parm['map'])->order($orderby)->limit($Lsql)->select();
    $symbol = C('MONEY_SYMBOL');
    $suffix = C("URL_HTML_SUFFIX");
    foreach ($data as $key => $v) {
    }
    $row = array();
    $row['list'] = $data;
    $row['page'] = $page;
    $row['count'] = $count;
    return $row;
}
 public function addToBasket(Model $Model, $id, array $options = array())
 {
     $options = Hash::merge(array('basket' => $Model->ShoppingBasketItem->ShoppingBasket->currentBasketId(), 'amount' => 1, 'configuration' => array(), 'non_overridable' => array()), array_filter($options));
     $configurationGroupIds = $Model->ItemConfigurationGroup->find('list', array('fields' => array('ConfigurationGroup.id'), 'conditions' => array('ItemConfigurationGroup.foreign_key' => $id, 'ItemConfigurationGroup.model' => $Model->name), 'contain' => array('ConfigurationGroup')));
     $valueData = $Model->ShoppingBasketItem->ConfigurationValue->generateValueData($Model->ShoppingBasketItem->name, $configurationGroupIds, $options['configuration'], $options['non_overridable']);
     $stackable = $Model->field('stackable', array('id' => $id));
     if ($stackable) {
         $shoppingBasketItemId = $Model->ShoppingBasketItem->field('id', array('ShoppingBasketItem.shopping_basket_id' => $options['basket'], 'ShoppingBasketItem.product_id' => $id));
         if (!$shoppingBasketItemId) {
             $Model->ShoppingBasketItem->create();
             $data = $Model->ShoppingBasketItem->saveAssociated(array('ShoppingBasketItem' => array('shopping_basket_id' => $options['basket'], 'product_id' => $id, 'amount' => $options['amount']), 'ConfigurationValue' => $valueData));
             return $data;
         }
         $Model->ShoppingBasketItem->id = $shoppingBasketItemId;
         $amount = $Model->ShoppingBasketItem->field('amount');
         return $Model->ShoppingBasketItem->saveField('amount', $amount + $options['amount']);
     }
     for ($number = 1; $number <= $options['amount']; $number++) {
         $Model->ShoppingBasketItem->create();
         $data = $Model->ShoppingBasketItem->saveAssociated(array('ShoppingBasketItem' => array('shopping_basket_id' => $options['basket'], 'product_id' => $id, 'amount' => 1), 'ConfigurationValue' => $valueData));
         if (!$data) {
             return false;
         }
     }
     return true;
 }
 /**
  * beforeValidate is called before a model is validated, you can use this callback to
  * add behavior validation rules into a models validate array. Returning false
  * will allow you to make the validation fail.
  *
  * @param Model $model Model using this behavior
  * @param array $options Options passed from Model::save().
  * @return mixed False or null will abort the operation. Any other result will continue.
  * @see Model::save()
  */
 public function beforeValidate(Model $model, $options = array())
 {
     $model->loadModels(array('CircularNoticeContent' => 'CircularNotices.CircularNoticeContent', 'CircularNoticeTargetUser' => 'CircularNotices.CircularNoticeTargetUser', 'User' => 'Users.User'));
     if (!$model->data['CircularNoticeContent']['is_room_target']) {
         // 回覧先ユーザのバリデーション処理
         if (!isset($model->data['CircularNoticeTargetUser'])) {
             $model->data['CircularNoticeTargetUser'] = array();
         }
         $model->CircularNoticeTargetUser->set($model->data['CircularNoticeTargetUser']);
         // ユーザ選択チェック
         $targetUsers = Hash::extract($model->data['CircularNoticeTargetUser'], '{n}.user_id');
         if (!$model->CircularNoticeTargetUser->isUserSelected($targetUsers)) {
             $model->CircularNoticeTargetUser->validationErrors['user_id'] = sprintf(__d('circular_notices', 'Select user'));
             $model->validationErrors = Hash::merge($model->validationErrors, $model->CircularNoticeTargetUser->validationErrors);
             return false;
         }
         if (!$model->CircularNoticeTargetUser->validates()) {
             $model->validationErrors = Hash::merge($model->validationErrors, $model->CircularNoticeTargetUser->validationErrors);
             return false;
         }
         if (!$model->User->existsUser($targetUsers)) {
             $model->CircularNoticeTargetUser->validationErrors['user_id'][] = sprintf(__d('net_commons', 'Failed on validation errors. Please check the input data.'));
             $model->validationErrors = Hash::merge($model->validationErrors, $model->CircularNoticeTargetUser->validationErrors);
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 11
0
 function import($sFile)
 {
     if (!$this->bSpycReady) {
         return self::SPYC_CLASS_NOT_FOUND;
     }
     if (!file_exists($sFile)) {
         return self::YAML_FILE_NOT_FOUND;
     }
     $this->aTables = SPYC::YAMLload(file_get_contents($sFile));
     if (!is_array($this->aTables)) {
         return self::YAML_FILE_IS_INVALID;
     }
     uses('model' . DS . 'model');
     $oDB = $this->oDb;
     $aAllowedTables = $oDB->listSources();
     foreach ($this->aTables as $table => $records) {
         if (!in_array($oDB->config['prefix'] . $table, $aAllowedTables)) {
             return self::TABLE_NOT_FOUND;
         }
         $temp_model = new Model(false, $table);
         foreach ($records as $record_num => $record_value) {
             if (!isset($record_value['id'])) {
                 $record_value['id'] = $record_num;
             }
             if (!$temp_model->save($record_value)) {
                 return array('error' => array('table' => $table, 'record' => $record_value));
             }
         }
     }
     return true;
 }
Ejemplo n.º 12
0
 public function get_user_price_list($user_id)
 {
     $model = new Model();
     $condition['user_id'] = $user_id;
     $list = $model->table('ldh_price_user')->field('ldh_price.code,ldh_price.password,ldh_price_user.price_id')->join('ldh_price ON ldh_price_user.price_id = ldh_price.price_id')->where($condition)->select();
     return $list;
 }
Ejemplo n.º 13
0
 public function __construct($util, $get = null)
 {
     parent::__construct($util);
     $this->model();
     $this->setViewMenu();
     if (isset($get["vers"])) {
         $vers = $get["vers"];
     } else {
         $vers = 1;
     }
     if (isset($get["depuis"])) {
         $depuis = $get["depuis"];
     } else {
         $depuis = 1;
     }
     $model = new Model();
     if (isset($get["enregistrer"])) {
         //on a cliqué un bouton enregistrer
         if (isset($get["li"])) {
             //il y a des situs (inutile ici...)
             $model->validSitu($get["chk"], $this->util->getId(), $get["li"]);
         }
     }
     $data["lessitus"] = $model->getSitus($util->getId(), $util->getNumGroupe(), $vers);
     $data["auth"] = $this->util->estAuthent();
     $data["vers"] = $vers;
     $data["type"] = "V";
     //validations
     $this->view->init('dessitus.php', $data);
     $this->setViewBas();
     $model->close();
 }
Ejemplo n.º 14
0
 function __construct()
 {
     $model = new Model();
     $this->connection = $model->get_connection();
     //$this->connection = new mysqli('sql4.freemysqlhosting.net', 'sql497000', 'bGNjUbh2SS', 'sql497000');
     $this->check();
 }
Ejemplo n.º 15
0
 public function many_to_many(Model $reference)
 {
     $columns1 = parent::findConstraitn('PrimaryKey')->getColumns();
     $columns2 = $reference->findConstraitn('PrimaryKey')->getColumns();
     $mtm = ManyToMany::getInstance(parent::persistence(), $reference->persistence(), $columns1, $columns2);
     $this->weaks_entitys[get_class($mtm)] = $mtm;
 }
function update_programming_language($pl_id, $request)
{
    Authenticator::assert_manager($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die('', 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        $result = $model->edit_programming_language($pl_id, $input_data);
        header('Content-Type: text/plain');
        http_response_code($result ? 200 : 404);
        die;
    } catch (ConflictException $e) {
        Util::output_errors_and_die($e->getMessage(), 409);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Ejemplo n.º 17
0
 /**
  * Creates a unique slug and adds it to the object
  *
  * @param  Model  Model object subject of this observer method
  */
 public function before_insert(Model $obj)
 {
     // determine the slug
     $properties = (array) $this->_source;
     $source = '';
     foreach ($properties as $property) {
         $source .= '-' . $obj->{$property};
     }
     $slug = \Inflector::friendly_title(substr($source, 1), '-', true);
     // query to check for existence of this slug
     $query = $obj->query()->where($this->_property, 'like', $slug . '%');
     // is this a temporal model?
     if ($obj instanceof Model_Temporal) {
         // add a filter to only check current revisions excluding the current object
         $class = get_class($obj);
         $query->where($class::temporal_property('end_column'), '=', $class::temporal_property('max_timestamp'));
         foreach ($class::getNonTimestampPks() as $key) {
             $query->where($key, '!=', $obj->{$key});
         }
     }
     // do we have records with this slug?
     $same = $query->get();
     // make sure our slug is unique
     if (!empty($same)) {
         $max = -1;
         foreach ($same as $record) {
             if (preg_match('/^' . $slug . '(?:-([0-9]+))?$/', $record->{$this->_property}, $matches)) {
                 $index = isset($matches[1]) ? (int) $matches[1] : 0;
                 $max < $index and $max = $index;
             }
         }
         $max < 0 or $slug .= '-' . ($max + 1);
     }
     $obj->{$this->_property} = $slug;
 }
 public function beforeSave(Model $model, $options = array())
 {
     $columns = $model->getColumnTypes();
     foreach ($model->data as $modelClass => $values) {
         foreach ($values as $field => $value) {
             if (!isset($columns[$field]) or $columns[$field] != 'binary') {
                 continue;
             }
             if (is_array($value) and isset($value['size'])) {
                 if ($value["size"] > 0) {
                     $fileHandler = new BlobFileHandler();
                     $fileHandler->loadFromFile($value['tmp_name']);
                     if ($fileHandler->getImageWith() > $this->config['imageMaxWidth']) {
                         $fileHandler->modify('resize', $this->config['imageMaxWidth']);
                         // max image size
                         $fileData = $fileHandler->store(null, $fileHandler->resourceInfo[2], 90);
                     } else {
                         $fileData = file_get_contents($value['tmp_name']);
                     }
                     $model->data[$modelClass][$field] = $fileData;
                 } else {
                     unset($model->data[$modelClass][$field]);
                 }
             }
         }
     }
     return true;
 }
Ejemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 public function beforeValidate(Model $Model, $options = array())
 {
     $ModelValidator = $Model->validator();
     foreach ($Model->data[$Model->alias] as $field => $value) {
         if (!preg_match('/^([a-z0-9_]+)_confirm$/i', $field, $match)) {
             continue;
         }
         if (!array_key_exists($match[1], $Model->data[$Model->alias])) {
             continue;
         }
         if (!($Ruleset = $ModelValidator->getField($match[1]))) {
             $Ruleset = new CakeValidationSet($match[1], array());
         }
         $ruleset = array();
         foreach ($Ruleset->getRules() as $name => $Rule) {
             $ruleset[$name] = (array) $Rule;
             foreach (array_keys($ruleset[$name]) as $key) {
                 if (!preg_match('/^[a-z]/i', $key)) {
                     unset($ruleset[$name][$key]);
                 }
             }
         }
         $ModelValidator->add($field, new CakeValidationSet($field, array()));
         $ModelValidator->getField($field)->setRule('confirmed', array('rule' => 'isConfirmed', 'message' => __d('common', "No match.")));
     }
     return true;
 }
Ejemplo n.º 20
0
 /**
  * afterSave is called after a model is saved.
  *
  * @param Model $model Model using this behavior
  * @param bool $created True if this save created a new record
  * @param array $options Options passed from Model::save().
  * @return bool
  * @throws InternalErrorException
  * @see Model::save()
  */
 public function afterSave(Model $model, $created, $options = array())
 {
     if (!isset($model->data['Categories'])) {
         return true;
     }
     $model->loadModels(array('Category' => 'Categories.Category', 'CategoryOrder' => 'Categories.CategoryOrder'));
     $categoryKeys = Hash::combine($model->data['Categories'], '{n}.Category.key', '{n}.Category.key');
     //削除処理
     $conditions = array('block_id' => $model->data['Block']['id']);
     if ($categoryKeys) {
         $conditions[$model->Category->alias . '.key NOT'] = $categoryKeys;
     }
     if (!$model->Category->deleteAll($conditions, false)) {
         throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
     }
     $conditions = array('block_key' => $model->data['Block']['key']);
     if ($categoryKeys) {
         $conditions[$model->CategoryOrder->alias . '.category_key NOT'] = $categoryKeys;
     }
     if (!$model->CategoryOrder->deleteAll($conditions, false)) {
         throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
     }
     //登録処理
     foreach ($model->data['Categories'] as $category) {
         if (!($result = $model->Category->save($category['Category'], false))) {
             throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
         }
         $category['CategoryOrder']['category_key'] = $result['Category']['key'];
         if (!$model->CategoryOrder->save($category['CategoryOrder'], false)) {
             throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
         }
     }
     return parent::afterSave($model, $created, $options);
 }
Ejemplo n.º 21
0
 /**
  * Helper function to replace standard fields with multi lingual equivalents
  * @param  array $fields
  * @param  Model $model
  * @return array
  */
 protected function processFormMLFields($fields, $model)
 {
     $translatable = array_flip($model->getTranslatableAttributes());
     /*
      * Special: A custom field "markup_html" is used for Content templates.
      */
     if ($model instanceof Content && array_key_exists('markup', $translatable)) {
         $translatable['markup_html'] = true;
     }
     foreach ($fields as $name => $config) {
         if (!array_key_exists($name, $translatable)) {
             continue;
         }
         $type = array_get($config, 'type', 'text');
         if ($type == 'text') {
             $fields[$name]['type'] = 'mltext';
         } elseif ($type == 'textarea') {
             $fields[$name]['type'] = 'mltextarea';
         } elseif ($type == 'richeditor') {
             $fields[$name]['type'] = 'mlricheditor';
         } elseif ($type == 'markdown') {
             $fields[$name]['type'] = 'mlmarkdowneditor';
         } elseif ($type == 'repeater') {
             $fields[$name]['type'] = 'mlrepeater';
         }
     }
     return $fields;
 }
Ejemplo n.º 22
0
 function run()
 {
     global $database_config, $routing;
     $application = new Application();
     $model = new Model();
     $model->__connect_to_database($database_config[ENVIRONMENT]);
     // Load Up Controller
     $routing->params($_SERVER['REQUEST_URI']);
     if ($routing->current->events['nested_controller_path']) {
         $controller_path = $routing->current->events['nested_controllers'];
     } else {
         $path = explode("/", $routing->current->events['controller']);
         array_pop($path);
         $controller_path = $path;
     }
     // Require base controller if there is one
     $base_controller = $controller_path[count($controller_path) - 1];
     $base_controller = APPLICATION_ROOT . "/app/controllers/" . join($controller_path, "/") . "/{$base_controller}_controller.php";
     if (file_exists($base_controller)) {
         require_once $base_controller;
     }
     // Require needed controller
     require_once APPLICATION_ROOT . "/app/controllers/{$routing->current->events['nested_controller_path']}/{$routing->current->events['controller']}_controller.php";
     $controller_name = explode("/", $routing->current->events['controller']);
     $controller_name = array_pop($controller_name);
     $controller = ucwords($controller_name) . "Controller";
     $controller = new $controller();
     // Set Controller Params
     $controller->params = $this->params();
     $controller->route = $routing->current;
     return $controller->render(join("/", $controller_path), $controller_name, $routing->current->events['action']);
 }
Ejemplo n.º 23
0
 /**
  * 设置 Model 类型对象
  *
  * @param Model $model
  */
 public function setModelObject(Model $model)
 {
     $config = $model->getConnection();
     self::$table = $config['tablename'];
     $this->setConfig($config);
     self::$model = $model;
 }
Ejemplo n.º 24
0
 public function index()
 {
     $db = new Model('user');
     $select = $db->select();
     $this->assign('select', $select);
     $this->display();
 }
Ejemplo n.º 25
0
 public function setLimit(Model $Model, $data = array())
 {
     if (!empty($data)) {
         $Model->set($data);
     }
     if (empty($Model->data[$Model->alias])) {
         return false;
     }
     $limitField = $this->settings[$Model->alias]['limitField'];
     if (!isset($Model->data[$Model->alias][$limitField])) {
         $billingPlanModel = new BillingPlan();
         $limitValue = $billingPlanModel->field($limitField, array('id' => $Model->data[$Model->alias]['plan_id']));
         $Model->data[$Model->alias][$limitField] = $limitValue;
     }
     $scope = $this->settings[$Model->alias]['scope'];
     $remoteModel = $this->settings[$Model->alias]['remoteModel'];
     App::import('Model', $remoteModel);
     $remoteModel = new $remoteModel();
     if (in_array($Model->data[$Model->alias]['user_id'], $this->ownersWhitelist)) {
         $Model->data[$Model->alias][$limitField] = 199999999999;
     }
     $result = $remoteModel->updateAll(array($remoteModel->alias . '.' . $this->settings[$Model->alias]['remoteField'] => $Model->data[$Model->alias][$limitField]), array($remoteModel->alias . '.' . $scope => $Model->data[$Model->alias]['user_id']));
     if ($result) {
         //hardcoded group members manipulation
         if ($remoteModel == 'GroupLimit') {
             $this->membersOperate($Model);
         }
         return true;
     }
     return false;
 }
Ejemplo n.º 26
0
 public function get_list($lat, $long, $page, $pagesize, $activity_type)
 {
     $where = array("status" => 0, "invite_time" => array("gt", time()));
     if ($activity_type !== false) {
         $sql = "SELECT i.*, u.* FROM " . C("DB_PREFIX") . "user as u INNER JOIN " . C("DB_PREFIX") . "invitation as i ON i.uid=u.uid WHERE i.status=0 AND i.activity_type=" . $activity_type . " AND i.invite_time>" . time() . " ORDER BY i.pigcms_id DESC, u.sex DESC";
         $where["activity_type"] = intval($activity_type);
     } else {
         $sql = "SELECT i.*, u.* FROM " . C("DB_PREFIX") . "user as u INNER JOIN " . C("DB_PREFIX") . "invitation as i ON i.uid=u.uid WHERE i.status=0 AND i.invite_time>" . time() . " ORDER BY i.pigcms_id DESC, u.sex DESC";
     }
     $start = ($page - 1) * $pagesize;
     $count = $this->where($where)->count();
     $sql .= " limit {$start}, {$pagesize}";
     $mode = new Model();
     $res = $mode->query($sql);
     $today = strtotime(date("Y-m-d")) + 86400;
     $tomorrow = $today + 86400;
     $lastday = $tomorrow + 86400;
     foreach ($res as &$v) {
         $v["_time"] = date("Y-m-d H:i", $v["invite_time"]);
         $v["juli"] = ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat * PI() / 180 - $v["lat"] * PI() / 180) / 2), 2) + COS($lat * PI() / 180) * COS($v["lat"] * PI() / 180) * POW(SIN(($long * PI() / 180 - $v["long"] * PI() / 180) / 2), 2))) * 1000);
         $v["juli"] = 1000 < $v["juli"] ? number_format($v["juli"] / 1000, 1) . "km" : ($v["juli"] < 100 ? "<100m" : $v["juli"] . "m");
         $v["invite_time"] = $v["invite_time"] < $today ? "今天 " . date("H:i", $v["invite_time"]) : ($v["invite_time"] < $tomorrow ? "明天  " . date("H:i", $v["invite_time"]) : ($v["invite_time"] < $lastday ? "后天  " . date("H:i", $v["invite_time"]) : date("m-d H:i", $v["invite_time"])));
         $v["birthday"] && ($v["age"] = date("Y") - date("Y", strtotime($v["birthday"])));
         $v["age"] = 100 < $v["age"] || $v["age"] < 0 ? "保密" : $v["age"] . "岁";
     }
     return array("data" => $res, "total" => $count);
 }
Ejemplo n.º 27
0
 private function imdata($filename)
 {
     $Boolean = preg_match("/_part/", $filename);
     $datadir = 'backupdata/';
     if ($Boolean) {
         $fn = explode("_part", $filename);
         $backup = scandir($datadir);
         for ($i = 0; $i < count($backup); $i++) {
             $part = preg_match("/{$fn[0]}/", $backup[$i]);
             if ($part) {
                 $filenames[] = $backup[$i];
             }
         }
     }
     if (is_array($filenames)) {
         foreach ($filenames as $fn) {
             $data .= file_get_contents($datadir . $fn);
             //获取数据
         }
     } else {
         $data = file_get_contents($datadir . $filename);
     }
     $data = str_replace("\r", "\n", $data);
     $regular = "/;\n/";
     $data = preg_split($regular, trim($data));
     $obj = new Model();
     foreach ($data as $val) {
         $obj->query($val);
     }
     return true;
 }
Ejemplo n.º 28
0
 public function checkLogin()
 {
     //用户登陆检测,若成功,把登陆时间与IP插入数据库
     $verify = $this->_param('verify');
     //$_POST['verify'];
     if ($_SESSION['verify'] != md5($verify)) {
         $this->error('验证码错误!');
     }
     $admin_name = $this->_param('admin_name');
     $admin_pw = $this->_param('admin_pw');
     $m = new Model('admin');
     //查看管理员表中有没有该用户信息 注:管理员与普通用户为2个表!!!
     $where = 'user_name="' . $admin_name . '" AND password="******" AND state=0';
     $res = $m->where($where)->find();
     if (count($res) > 0) {
         //判断是否有管理员信息
         $data['last_login_ip'] = get_client_ip();
         $data['last_login_time'] = time();
         $where = 'id=' . $res['id'];
         $m->where($where)->save($data);
         session_start();
         $_SESSION['username'] = $res['user_name'];
         $_SESSION['islogin'] = 1;
         //$_SESSION['level']=2;
         $this->redirect('Index/main');
     } else {
         $this->error('密码错误或账号不存在或者已经被禁用!', U('Escape/login'));
     }
 }
 /**
  * UserAttributesRoleのデフォルト値
  *
  * * パスワード=自分/他人とも読み取り不可
  * * ラベル項目=自分/他人とも書き込み不可
  * * 会員管理が使用可=上記以外、自分・他人とも自分/他人の読み・書き可
  * * 会員管理が使用不可
  * ** 管理者以外、読み取り不可項目とする=自分/他人の読み・書き不可。※読めないのに書けるはあり得ないため。
  * ** 管理者以外、書き込み不可項目とする=自分/他人の書き込み不可。
  * ** 上記以外
  * *** ハンドル・アバター=自分は、読み・書き可。他人は、読み取り可/書き込み不可。
  * *** それ以外=自分は、読み・書き可。他人は、読み・書き不可。
  *
  * @param Model $model Model using this behavior
  * @param array|string $userAttrSetting 配列:ユーザ属性設定データ、文字列:ユーザ属性キー
  * @param bool $enableUserManager 有効かどうか
  * @return array ユーザ属性ロールデータ
  */
 public function defaultUserAttributeRole(Model $model, $userAttrSetting, $enableUserManager)
 {
     $model->loadModels(['UserAttributeSetting' => 'UserAttributes.UserAttributeSetting']);
     $userAttrSetting = $model->UserAttributeSetting->create($userAttrSetting);
     $userAttributeRole = array();
     $userAttributeRole['UserAttributesRole']['self_readable'] = true;
     $userAttributeRole['UserAttributesRole']['self_editable'] = true;
     $userAttributeKey = $userAttrSetting['UserAttributeSetting']['user_attribute_key'];
     if ($userAttributeKey === UserAttribute::PASSWORD_FIELD) {
         $userAttributeRole['UserAttributesRole']['self_readable'] = false;
         $userAttributeRole['UserAttributesRole']['other_readable'] = false;
     } elseif ($enableUserManager) {
         $userAttributeRole['UserAttributesRole']['other_readable'] = true;
     } elseif (Hash::get($userAttrSetting, 'UserAttributeSetting.only_administrator_readable')) {
         $userAttributeRole['UserAttributesRole']['self_readable'] = false;
         $userAttributeRole['UserAttributesRole']['other_readable'] = false;
         $userAttrSetting['UserAttributeSetting']['only_administrator_editable'] = true;
     } else {
         $userAttributeRole['UserAttributesRole']['self_readable'] = true;
         $userAttributeRole['UserAttributesRole']['other_readable'] = in_array($userAttributeKey, $this->readableDefault, true);
     }
     $userAttributeRole['UserAttributesRole']['other_editable'] = false;
     if ($userAttrSetting['UserAttributeSetting']['data_type_key'] === DataType::DATA_TYPE_LABEL) {
         $userAttributeRole['UserAttributesRole']['self_editable'] = false;
     } elseif ($enableUserManager) {
         $userAttributeRole['UserAttributesRole']['other_editable'] = true;
     } elseif (Hash::get($userAttrSetting, 'UserAttributeSetting.only_administrator_editable')) {
         $userAttributeRole['UserAttributesRole']['self_editable'] = false;
     }
     return $userAttributeRole;
 }
 /**
  * Creates the different versions of images that are configured
  *
  * @param Model $Model
  * @param array $record
  * @param array $operations
  * @throws Exception
  * @return void
  */
 protected function _createVersions(Model $Model, $record, $operations)
 {
     $Storage = StorageManager::adapter($record['adapter']);
     $path = $this->_buildPath($record, true);
     $tmpFile = $this->_tmpFile($Storage, $path);
     foreach ($operations as $version => $imageOperations) {
         $hash = $Model->hashOperations($imageOperations);
         $string = $this->_buildPath($record, true, $hash);
         if ($this->adapterClass === 'AmazonS3' || $this->adapterClass === 'AwsS3') {
             $string = str_replace('\\', '/', $string);
         }
         if ($Storage->has($string)) {
             return false;
         }
         try {
             $image = $Model->processImage($tmpFile, null, array('format' => $record['extension']), $imageOperations);
             $result = $Storage->write($string, $image->get($record['extension'], $this->options['imageOptions']), true);
         } catch (Exception $e) {
             $this->log($e->getMessage(), 'file_storage');
             unlink($tmpFile);
             throw $e;
         }
     }
     unlink($tmpFile);
 }