/**
  * Generic edit action
  *
  * Triggers the following callbacks
  *	- Crud.init
  *	- Crud.beforeSave
  *	- Crud.afterSave
  *	- Crud.beforeFind
  *	- Crud.recordNotFound
  *	- Crud.afterFind
  *	- Crud.beforeRender
  *
  * @param string $id
  * @return void
  */
 protected function _editAction($id = null)
 {
     if (empty($id)) {
         $id = $this->getIdFromRequest();
     }
     $this->_validateId($id);
     if ($this->_request->is('put')) {
         $this->trigger('beforeSave', compact('id'));
         if ($this->_model->saveAll($this->_request->data, $this->_getSaveAllOptions())) {
             $this->_setFlash('update.success');
             $subject = $this->trigger('afterSave', array('id' => $id, 'success' => true));
             return $this->_redirect($subject, array('action' => 'index'));
         } else {
             $this->_setFlash('update.error');
             $this->trigger('afterSave', array('id' => $id, 'success' => false));
         }
     } else {
         $query = array();
         $query['conditions'] = array($this->_model->escapeField() => $id);
         $findMethod = $this->_getFindMethod(null, 'first');
         $subject = $this->trigger('beforeFind', compact('query', 'findMethod'));
         $query = $subject->query;
         $this->_request->data = $this->_model->find($subject->findMethod, $query);
         if (empty($this->_request->data)) {
             $subject = $this->trigger('recordNotFound', compact('id'));
             $this->_setFlash('find.error');
             return $this->_redirect($subject, array('action' => 'index'));
         }
         $this->trigger('afterFind', compact('id'));
         // Make sure to merge any changed data in the model into the post data
         $this->_request->data = Set::merge($this->_request->data, $this->_model->data);
     }
     // Trigger a beforeRender
     $this->trigger('beforeRender');
 }
Example #2
0
 public function salvar(Model $Model, $dados)
 {
     $Model->create();
     if ($Model->saveAll($dados)) {
         return true;
     }
     return $Model->validationErrors;
 }
Example #3
0
 public function saveAll($data = null, $options = array())
 {
     $this->useDbConfig = 'master';
     $status = parent::saveAll($data, $options);
     if (!isset($_SERVER['FORCEMASTER'])) {
         $this->useDbConfig = 'default';
     }
     return $status;
 }
Example #4
0
 /**
  * This will create weights based on display field. The purpose of the method is to create
  * weights for tables that existed before this behavior was added.
  *
  * @param Object $Model
  * @return boolean success
  */
 public function resetWeights(Model $Model)
 {
     if ($this->settings[$Model->alias]['foreign_key']) {
         $temp = $Model->find('all', array('fields' => $this->settings[$Model->alias]['foreign_key'], 'group' => $this->settings[$Model->alias]['foreign_key'], 'recursive' => -1));
         $foreignKeys = Hash::extract($temp, '{n}.' . $Model->alias . '.' . $this->settings[$Model->alias]['foreign_key']);
         foreach ($foreignKeys as $fk) {
             $all = $Model->find('all', array('conditions' => array($this->settings[$Model->alias]['foreign_key'] => $fk), 'fields' => array($Model->displayField, $Model->primaryKey, $this->settings[$Model->alias]['field'], $this->settings[$Model->alias]['foreign_key']), 'order' => $Model->displayField));
             $i = 1;
             foreach ($all as $key => $one) {
                 $all[$key][$Model->alias][$this->settings[$Model->alias]['field']] = $i++;
             }
             if (!$Model->saveAll($all)) {
                 return false;
             }
         }
     } else {
         $all = $Model->find('all', array('fields' => array($Model->displayField, $Model->primaryKey, $this->settings[$Model->alias]['field']), 'order' => $Model->displayField));
         $i = 1;
         foreach ($all as $key => $one) {
             $all[$key][$Model->alias][$this->settings[$Model->alias]['field']] = $i++;
         }
         if (!$Model->saveAll($all)) {
             return false;
         }
     }
     return true;
 }
Example #5
0
 /**
  * Restore data from a version_id
  *
  * @example
  *  $this->Model->restoreVersion('50537471-ba08-44ae-a606-24e5e017215a'); //restores version id 50537471-ba08-44ae-a606-24e5e017215a
  *  $this->Model->restoreVersion('50537471-ba08-44ae-a606-24e5e017215a', false); //restores version id 50537471-ba08-44ae-a606-24e5e017215a and won't create a new version before restoring.
  *  $this->Model->restoreVersion(2, 3); //restores the second version back from most recent on Model id 3
  *  $this->Model->restoreVersion(2, 3, false); //restores the second version back from most recent on Model id 3 and doesn't create a new version before saving
  *
  * @param int $version_id or the $count_of_versions_ago
  * @param model_id of the id to reversion if version is an int.
  * @param boolean create a new version on restore. boolean true
  * @return boolean result of saveAll on model
  */
 public function restoreVersion(Model $Model, $version_id, $model_id = 0, $create_new_version = true)
 {
     if ($model_id === false) {
         $create_new_version = false;
         $model_id = 0;
     }
     $restore = false;
     if (is_numeric($version_id) && !empty($model_id)) {
         $restore = $this->IcingVersion->findVersionBack($Model->alias, $version_id, $model_id);
     } else {
         $restore = $this->IcingVersion->findById($version_id);
     }
     if (!empty($restore)) {
         $model_data = json_decode($restore['IcingVersion']['json'], true);
         if ($Model->alias == $restore['IcingVersion']['model']) {
             return $Model->saveAll($model_data, array('create_version' => $create_new_version));
         } else {
             $this->addError($Model, "Restore found was for different model. {$restore['IcingVersion']['model']} != {$Model->alias}");
         }
     } else {
         $this->addError($Model, "No restore version found for params.");
     }
     return false;
 }
Example #6
0
 public function send_mail($locale, $status, $mailsendqueue, $mail_config, $mailsendname = '')
 {
     if (isset($status) && $status != 1) {
         $this_model = new Model(false, 'mail_send_queues');
         $this_model->deleteAll(array('flag' => '5'));
         $mail_send_queue_info = $this_model->find('all', array('limit' => '10', 'order' => 'id asc'));
         $this_model->saveAll($mailsendqueue);
         return false;
     } else {
         $this->set_appconfigs($locale);
         $this->smtpauth = isset($mail_config['mail-requires-authorization']) ? trim($mail_config['mail-requires-authorization']) : 1;
         $this->is_ssl = trim($mail_config['mail-ssl']);
         $this->is_mail_smtp = trim($mail_config['mail-service']);
         $this->smtp_port = trim($mail_config['mail-port']);
         $this->smtpHostNames = trim($mail_config['mail-smtp']);
         $this->smtpUserName = trim($mail_config['mail-account']);
         $this->smtpPassword = trim($mail_config['mail-password']);
         $this->from = $mail_config['mail-address'];
         $this_model = new Model(false, 'mail_send_histories');
         $this->sendAs = $mailsendqueue['sendas'];
         $this->fromName = $mailsendqueue['sender_name'];
         $subject = $mailsendqueue['title'];
         $this->subject = $mailsendqueue['title'];
         //eval("\$subject = \"$subject\";");
         //$this->subject="=?utf-8?B?".base64_encode($subject)."?=";
         if (is_array($mailsendqueue['receiver_email'])) {
             $to_email_and_name_arr = $mailsendqueue['receiver_email'];
             $i = 0;
             foreach ($to_email_and_name_arr as $k => $v) {
                 if (strpos($v, ';')) {
                     $to_email_and_name = explode(';', $v);
                     $to_name[$i] = $to_email_and_name[0];
                     $to_email[$i] = $to_email_and_name[1];
                     ++$i;
                 }
             }
         } else {
             $to_email_and_name = explode(';', $mailsendqueue['receiver_email']);
             $to_name[] = $to_email_and_name[0];
             $to_email[] = $to_email_and_name[1];
         }
         $mailsendqueue['receiver_email'] = json_encode($mailsendqueue['receiver_email']);
         if (is_array($mailsendqueue['cc_email'])) {
             $addcc_to_email_and_name_arr = $mailsendqueue['cc_email'];
             $i = 0;
             foreach ($addcc_to_email_and_name_arr as $k => $v) {
                 if (strpos($v, ';')) {
                     $addcc_to_email_and_name = explode(';', $v);
                     $addcc_to_name[$i] = $addcc_to_email_and_name[0];
                     //�ռ�������
                     $addcc_to_email[$i] = $addcc_to_email_and_name[1];
                     //�ռ���email
                     ++$i;
                 }
             }
         } else {
             if (trim($mailsendqueue['cc_email']) != '' && trim($mailsendqueue['cc_email']) != ';') {
                 $addcc_to_email_and_name = explode(';', $mailsendqueue['cc_email']);
                 if (trim($addcc_to_email_and_name[0]) != '' && trim($addcc_to_email_and_name[1]) != ';') {
                     $addcc_to_name[] = $addcc_to_email_and_name[0];
                     //�ռ�������
                     $addcc_to_email[] = $addcc_to_email_and_name[1];
                     //�ռ���email
                 }
             }
         }
         $mailsendqueue['cc_email'] = json_encode($mailsendqueue['cc_email']);
         if (is_array($mailsendqueue['bcc_email'])) {
             $addbcc_to_email_and_name_arr = $mailsendqueue['bcc_email'];
             $i = 0;
             foreach ($addbcc_to_email_and_name_arr as $k => $v) {
                 if (strpos($v, ';')) {
                     $addbcc_to_email_and_name = explode(';', $v);
                     $addbcc_to_name[$i] = $addbcc_to_email_and_name[0];
                     //�ռ�������
                     $addbcc_to_email[$i] = $addbcc_to_email_and_name[1];
                     //�ռ���email
                     ++$i;
                 }
             }
         } else {
             if (trim($mailsendqueue['bcc_email']) != '' && trim($mailsendqueue['bcc_email']) != ';') {
                 $addbcc_to_email_and_name = explode(';', $mailsendqueue['bcc_email']);
                 if (trim($addbcc_to_email_and_name[0]) != '' && trim($addbcc_to_email_and_name[1]) != ';') {
                     $addbcc_to_name[] = $addbcc_to_email_and_name[0];
                     //�ռ�������
                     $addbcc_to_email[] = $addbcc_to_email_and_name[1];
                     //�ռ���email
                 }
             }
         }
         $mailsendqueue['bcc_email'] = json_encode($mailsendqueue['bcc_email']);
         $this->html_body = $mailsendqueue['html_body'];
         $this->text_body = $mailsendqueue['text_body'];
         for ($i = 0; $i < count($to_email); ++$i) {
             $this->toName[$i] = trim($to_name[$i]);
             $this->to[$i] = trim($to_email[$i]);
         }
         if (isset($addcc_to_name)) {
             for ($i = 0; $i < count($addcc_to_name); ++$i) {
                 $this->addcctoName[$i] = trim($addcc_to_name[$i]);
                 $this->addccto[$i] = trim($addcc_to_email[$i]);
             }
         }
         if (isset($addbcc_to_name)) {
             for ($i = 0; $i < count($addbcc_to_name); ++$i) {
                 $this->addbcctoname[$i] = trim($addbcc_to_name[$i]);
                 $this->addbccto[$i] = trim($addbcc_to_email[$i]);
             }
         }
         $mail_status = $this->send($mailsendname);
         if ($mail_status === true) {
             $mailsendqueue['flag'] = $mail_status;
         } else {
             $mailsendqueue['flag'] = 0;
             $mailsendqueue['error_msg'] = $mail_status;
         }
         $this_model->saveAll($mailsendqueue);
         if ($mail_status) {
             return true;
         } else {
             return false;
         }
     }
 }
Example #7
0
File: Batch.php Project: xJakub/LCE
    public function makeMatches() {

        $teams = Team::find('1=1');
        $teamIdByName = Model::pluck($teams, 'teamid', 'name');

        $week = 0;
        $matches = [];

        foreach (explode("\n", file_get_contents("matches.txt")) as $line) {
            $parts = explode("VS", $line);
            if (count($parts) == 1 && substr(trim($line), 0, 2) == '--') {
                $week++;
            }
            if (count($parts) != 2) continue;

            list($name1, $name2) = $parts;
            $name1 = trim($name1);
            $name2 = trim($name2);

            $match = Match::create();
            $match->team1id = $teamIdByName[$name1];
            $match->team2id = $teamIdByName[$name2];
            $match->week = $week;
            $matches[] = $match;

            if (!$match->team1id) {
                die("Equipo desconocido: $name1");
            }
            if (!$match->team2id) {
                die("Equipo desconocido: $name2");
            }

        }

        if (count($matches) >= 1 && count($matches) != count(Match::find('1=1'))) {
            Match::truncate(true);
            Model::saveAll($matches);
            ?>Enfrentamientos actualizados.<br><?
        }
        else {
            ?>No hay cambios en los enfrentamientos.<br><?
        }

    }
Example #8
0
    /**
     * @return void
     */
    public function show()
    {
        if (!Team::isSuperAdmin()) {
            HTMLResponse::exitWithRoute('/');
        }

        if (!($csrf = $_SESSION['csrf'])) {
            $_SESSION['csrf'] = $csrf = rand(1, 1000000);
        }
        $postCsrf = HTMLResponse::fromPOST('csrf', '');

        $totalWeeks = $this->season->getWeeksCount();
        if ($csrf == $postCsrf) {
            $this->season->mainweeks = HTMLResponse::fromPOST('mainweeks', $this->season->mainweeks);
            $this->season->playoffsweeks = HTMLResponse::fromPOST('playoffsweeks', $this->season->playoffsweeks);
            $this->season->save();
        }

        ?>
        <div class="inblock middle">
        <form action="<?=HTMLResponse::getRoute()?>" method="post">
            <table style="width:640px; margin: 0 auto; text-align: left">
                <thead>
                <tr style="text-align: center">
                    <td>
                        Propiedad
                    </td>
                    <td>
                        Valor
                    </td>
                </tr>
                </thead>
                <tr>
                    <td>
                        <b>Número de jornadas (principales)</b>
                    </td><td>
                        <input name="mainweeks" type="number" value="<?=htmlentities($this->season->mainweeks)?>">
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Número de jornadas (playoffs)</b>
                    </td><td>
                        <input name="playoffsweeks" type="number" value="<?=htmlentities($this->season->playoffsweeks)?>">
                    </td>
                </tr>
            </table>

            <?
            $teams = $this->season->getTeams(false);
            $maxMatches = ceil(count($teams)/2);

            $matches =
                Model::groupBy(
                    Match::find('seasonid = ? order by week asc, matchid asc', [$this->season->seasonid]),
                    'week'
                );

            if ($csrf == $postCsrf) {
                for ($week=1; $week<=$totalWeeks; $week++) {
                    $name = HTMLResponse::fromPOST("week{$week}name");
                    $date = HTMLResponse::fromPOST("week{$week}date");
                    $this->season->setWeekName($week, $name);
                    $this->season->setWeekDate($week, $date);
                }
                $this->season->save();

                $newMatches = [];
                $oldMatches = [];
                for ($week=1; $week<=$this->season->getWeeksCount(); $week++) {
                    for ($i=0; $i<$maxMatches; $i++) {
                        $team1id = HTMLResponse::fromPOST("week{$week}match{$i}team1id");
                        $team2id = HTMLResponse::fromPOST("week{$week}match{$i}team2id");
                        if ($team1id === null || $team2id === null) continue;

                        $team1id *= 1;
                        $team2id *= 1;

                        if ($team1id && $team2id) {
                            if (isset($matches[$week][$i])) {
                                $match = $matches[$week][$i];
                                $match->team1id = "$team1id";
                                $match->team2id = "$team2id";
                                $oldMatches[] = $match;
                            }
                            else {
                                $match = Match::create();
                                $match->result = 0;
                                $match->week = $week;
                                $match->seasonid = $this->season->seasonid;
                                $match->team1id = $team1id;
                                $match->team2id = $team2id;
                                $newMatches[] = $match;
                            }
                        }
                        else {
                            if (isset($matches[$week][$i])) {
                                $matches[$week][$i]->delete();
                            }
                        }
                    }
                }
                Model::saveAll($newMatches);
                Model::saveAll($oldMatches);

                $matches =
                    Model::groupBy(
                        Match::find('seasonid = ? order by week asc, matchid asc', [$this->season->seasonid]),
                        'week'
                    );
            }


            for ($week=1; $week<=$totalWeeks; $week++) {
                ?>
                <br>
                <table style="width:640px; margin: 0 auto; text-align: left">
                    <thead>
                    <tr>
                        <td colspan="2" style="text-align: center">Jornada Nº<?=$week?></td>
                    </tr>
                    </thead>
                    <tr>
                        <td>
                            <b>Nombre de la jornada</b>
                        </td><td>
                            <input name="week<?=$week?>name" value="<?=htmlentities($this->season->getWeekName($week))?>">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <b>Fecha de publicación</b>
                        </td><td>
                            <input name="week<?=$week?>date" type="date" value="<?=htmlentities($this->season->getWeekDate($week))?>">
                        </td>
                    </tr>
                    <?
                    for ($i=0; $i<$maxMatches; $i++) {
                        ?>
                        <tr>
                            <td>
                                <b>- Enfrentamiento #<?=$i+1?></b>
                            </td>
                            <td>
                                <select name="week<?=$week?>match<?=$i?>team1id">
                                    <option value="0">-- Elige equipo --</option>
                                    <?
                                    foreach($teams as $team) {
                                        $selected = isset($matches[$week][$i])
                                            ? (
                                            $matches[$week][$i]->team1id == $team->teamid
                                                ? 'selected'
                                                : ''
                                            )
                                            : '';
                                        ?>
                                        <option value="<?=$team->teamid?>" <?=$selected?>>
                                            <?=htmlentities($team->name)?>
                                        </option>
                                        <?
                                    }
                                    ?>
                                </select>
                                VS
                                <select name="week<?=$week?>match<?=$i?>team2id">
                                    <option value="0">-- Elige equipo --</option>
                                    <?
                                    foreach($teams as $team) {
                                        $selected = isset($matches[$week][$i])
                                            ? (
                                            $matches[$week][$i]->team2id == $team->teamid
                                                ? 'selected'
                                                : ''
                                            )
                                            : '';
                                        ?>
                                        <option value="<?=$team->teamid?>" <?=$selected?>>
                                            <?=htmlentities($team->name)?>
                                        </option>
                                        <?
                                    }
                                    ?>
                                </select>
                            </td>
                        </tr>
                        <?
                    }
                    ?>
                </table>
                <?
            }
            ?>

            <input type="hidden" name="csrf" value="<?= $csrf ?>"><br>
            <button type="submit">Guardar cambios</button><br><br>

        </form>
        </div><?
    }
Example #9
0
 /**
  * Fix for non atomic queries (MyISAM  etc) and saveAll to still return just the boolean result
  * Otherwise you would have to iterate over all result values to find out if the save was successful.
  *
  * Use Configure::read('Model.atomic') to modify atomic behavior.
  * Additional options:
  *
  * - returnArray: bool
  *
  * @param mixed $data
  * @param array $options
  * @return bool Success
  */
 public function saveAll($data = null, $options = array())
 {
     if (!isset($options['atomic']) && Configure::read('Model.atomic') !== null) {
         $options['atomic'] = (bool) Configure::read('Model.atomic');
     }
     $res = parent::saveAll($data, $options);
     if (is_array($res) && empty($options['returnArray'])) {
         $res = Utility::isValidSaveAll($res);
     }
     return $res;
 }
 public function saveAll($data = null, $options = array())
 {
     $this->useMasterDb();
     return parent::saveAll($data, $options);
 }
Example #11
0
 /**
  * Performs the actual creation and save.
  *
  * @param object $Model Model object
  * @return mixed
  */
 protected function _copyRecord(Model $Model)
 {
     $Model->create();
     $saved = $Model->saveAll($this->record, array('validate' => false, 'deep' => true));
     if ($this->settings[$Model->alias]['masterKey']) {
         $record = $this->_updateMasterKey($Model);
         $Model->saveAll($record, array('validate' => false, 'deep' => true));
     }
     return $saved;
 }
Example #12
0
 private static function afterLogin()
 {
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
     $json = $connection->get('users/show', ['user_id' => $_SESSION['twitter-userid']]);
     $_SESSION['twitter-avatar'] = isset($json->profile_image_url) ? $json->profile_image_url : '';
     Avatar::setUsersAvatar($_SESSION['twitter-userid'], $_SESSION['twitter-username'], $_SESSION['twitter-avatar']);
     $oldAvatars = Avatar::find('1=1 order by dateline asc limit 100');
     if ($oldAvatars) {
         $oldAvatarsIds = Model::pluck($oldAvatars, 'userid');
         $json = $connection->get('users/lookup', ['user_id' => implode(',', $oldAvatarsIds)]);
         foreach ($json as $userdata) {
             $newavatars[$userdata->id_str] = $userdata->profile_image_url;
         }
         foreach ($oldAvatars as $avatar) {
             $avatar->url = $newavatars[$avatar->userid];
             $avatar->dateline = time();
         }
         Model::saveAll($oldAvatars);
     }
 }
Example #13
0
 protected function __installData($basePrefix = '', $sample = false)
 {
     if (isset($this->fixtures)) {
         $Model = new Model(false, false, $this->connection);
         foreach ($this->fixtures as $type => $fixtures) {
             if ($type != 'sample' || $type == 'sample' && $sample == true) {
                 foreach ($fixtures as $model => $data) {
                     if (is_array($data) && !empty($data)) {
                         $tableName = $this->__getTableName($model);
                         $Model->tablePrefix = $this->__getTablePrefix($tableName, $basePrefix);
                         $Model->setSource($tableName);
                         $Model->saveAll($data, array('validate' => false));
                     }
                 }
             }
         }
     }
 }
Example #14
0
 /**
  * Save with meta
  *
  * @param Model $model
  * @param array $data
  * @param array $options
  * @return void
  * @deprecated Use standard Model::saveAll()
  */
 public function saveWithMeta(Model $model, $data, $options = array())
 {
     $data = $this->_prepareMeta($data);
     return $model->saveAll($data, $options);
 }
Example #15
0
 public function saveAll($data = null, $options = array())
 {
     $options['atomic'] = false;
     return parent::saveAll($data, $options);
 }
Example #16
0
 /**
  * Register new user
  * 
  * @param Model $Model
  * @param mixed $source
  * @param string $type
  * 
  * @return boolean|int
  */
 public function register(Model $Model, $source, $type = null)
 {
     $event = new CakeEvent("Model.{$Model->alias}.beforeRegister", $Model, compact('type', 'source'));
     $Model->getEventManager()->dispatch($event);
     if ($event->isStopped()) {
         return false;
     }
     extract($event->result, EXTR_OVERWRITE);
     if ($Model->saveAll($data, compact('validate', 'fieldList'))) {
         $event = new CakeEvent("Model.{$Model->alias}.afterRegister", $Model, array('type' => $type, 'id' => $Model->id));
         $Model->getEventManager()->dispatch($event);
         if (!$event->isStopped()) {
             return $Model->id;
         }
     }
     return false;
 }
Example #17
0
 /**
  * CSV定義のデータを保存する
  * @param Model $model
  * @param String $csvFile
  * @return boolean
  */
 private static function csvDataSave(Model $model, $csvFile)
 {
     $saveCnt = 50;
     $alias = $model->alias;
     $results = array();
     // CSVファイルを開く
     $csv = fopen($csvFile, 'r');
     // CSVヘッダの配列を取得する
     $header = fgetcsv($csv);
     $saveAllData = array();
     while ($line = fgetcsv($csv)) {
         // 1件文のデータフォーマットを取得する
         $data = self::getCsvRowData($line, $header);
         $saveAllData[] = array($alias => $data);
         if (count($saveAllData) % $saveCnt == 0) {
             $results[] = $model->saveAll($saveAllData);
             $saveAllData = array();
         }
     }
     if (!empty($saveAllData)) {
         $results[] = $model->saveAll($saveAllData);
     }
     // CSVファイルを閉じる
     fclose($csv);
     return !in_array(false, $results);
 }