Exemplo n.º 1
0
 public function onSave()
 {
     try {
         // open a transaction with database
         TTransaction::open($this->database);
         // get the form data
         $object = $this->form->getData($this->activeRecord);
         // validate data
         $this->form->validate();
         // stores the object
         $object->store();
         // fill the form with the active record data
         $this->form->setData($object);
         // close the transaction
         TTransaction::close();
         // shows the success message
         //new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
         parent::add(new TAlert('info', AdiantiCoreTranslator::translate('Record saved')));
         // reload the listing
         $this->onReload();
         return $object;
     } catch (Exception $e) {
         // get the form data
         $object = $this->form->getData($this->activeRecord);
         // fill the form with the active record data
         $this->form->setData($object);
         // shows the exception error message
         new TMessage('error', $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }
 /**
  * method onEdit()
  * Executed whenever the user clicks at the edit button da datagrid
  */
 function onView($param)
 {
     try {
         if (isset($param['key'])) {
             // get the parameter $key
             $key = $param['key'];
             // open a transaction with database 'changeman'
             TTransaction::open('changeman');
             // instantiates object Document
             $object = new Document($key);
             $element = new TElement('div');
             $element->add($object->content);
             parent::add($element);
             // close the transaction
             TTransaction::close();
         } else {
             $this->form->clear();
         }
     } catch (Exception $e) {
         // shows the exception error message
         new TMessage('error', '<b>Error</b> ' . $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }
 /**
  * Autenticates the User
  */
 function onLogin()
 {
     try {
         TTransaction::open('permission');
         $data = $this->form->getData('StdClass');
         $this->form->validate();
         $user = SystemUser::autenticate($data->login, $data->password);
         if ($user) {
             $programs = $user->getPrograms();
             $programs['LoginForm'] = TRUE;
             TSession::setValue('logged', TRUE);
             TSession::setValue('login', $data->login);
             TSession::setValue('username', $user->name);
             TSession::setValue('frontpage', '');
             TSession::setValue('programs', $programs);
             $frontpage = $user->frontpage;
             if ($frontpage instanceof SystemProgram and $frontpage->controller) {
                 TApplication::gotoPage($frontpage->controller);
                 // reload
                 TSession::setValue('frontpage', $frontpage->controller);
             } else {
                 TApplication::gotoPage('EmptyPage');
                 // reload
                 TSession::setValue('frontpage', 'EmptyPage');
             }
         }
         TTransaction::close();
     } catch (Exception $e) {
         new TMessage('error', $e->getMessage());
         TSession::setValue('logged', FALSE);
         TTransaction::rollback();
     }
 }
Exemplo n.º 4
0
 /**
  * Overloaded method onSave()
  * Executed whenever the user clicks at the save button
  */
 public function onSave()
 {
     // first, use the default onSave()
     $object = parent::onSave();
     // if the object has been saved
     if ($object instanceof Product) {
         $source_file = 'tmp/' . $object->photo_path;
         $target_file = 'images/' . $object->photo_path;
         $finfo = new finfo(FILEINFO_MIME_TYPE);
         // if the user uploaded a source file
         if (file_exists($source_file) and $finfo->file($source_file) == 'image/png') {
             // move to the target directory
             rename($source_file, $target_file);
             try {
                 TTransaction::open($this->database);
                 // update the photo_path
                 $object->photo_path = 'images/' . $object->photo_path;
                 $object->store();
                 TTransaction::close();
             } catch (Exception $e) {
                 new TMessage('error', '<b>Error</b> ' . $e->getMessage());
                 TTransaction::rollback();
             }
         }
     }
 }
Exemplo n.º 5
0
 /**
  * Validate the login
  */
 function onLogin()
 {
     try {
         TTransaction::open('changeman');
         $data = $this->form->getData('StdClass');
         // validate form data
         $this->form->validate();
         $auth = Member::authenticate($data->user, md5($data->password));
         if ($auth) {
             TSession::setValue('logged', TRUE);
             TSession::setValue('login', $data->user);
             TSession::setValue('language', $data->language);
             // reload page
             TApplication::gotoPage('NewIssueForm', 'nonono');
         }
         TTransaction::close();
         // finaliza a transação
     } catch (Exception $e) {
         TSession::setValue('logged', FALSE);
         // exibe a mensagem gerada pela exceção
         new TMessage('error', '<b>Erro</b> ' . $e->getMessage());
         // desfaz todas alterações no banco de dados
         TTransaction::rollback();
     }
 }
Exemplo n.º 6
0
 /** @param PDOStatement $query_result */
 private function treat_success($query_result)
 {
     if ($query_result->rowCount() > 0) {
         (new Insert_user_dummy(array('id_user' => $this->connected, 'id_dummy' => TTransaction::get_last_inserted_id())))->run();
     } else {
         TTransaction::rollback();
     }
 }
 /** @param PDOStatement $query_result */
 private function treat_success($query_result)
 {
     if ($query_result->rowCount() > 0) {
         (new Delete_invitation(array('id' => parent::get_input('id_invitation'))))->run();
     } else {
         TTransaction::rollback();
     }
 }
Exemplo n.º 8
0
 /**
  * @param PDOStatement $query_result
  */
 private function treat_success($query_result)
 {
     if ($query_result->rowCount() > 1) {
         parent::set_error(1, "Mais de um item foi removido, assim, a remoção foi cancelada.");
         TTransaction::rollback();
     } elseif ($query_result->rowCount() == 0) {
         parent::set_error(1, "Nenhum item foi removido.");
     }
 }
Exemplo n.º 9
0
 /** @param PDOStatement $query_result */
 private function treat_success($query_result)
 {
     if ($query_result->rowCount() > 0 && TSession::try_get_value('id_user', $id_user)) {
         (new Insert_user_event(array('id_user' => $id_user, 'id_event' => TTransaction::get_last_inserted_id())))->run();
     } else {
         parent::set_error(102);
         TTransaction::rollback();
     }
 }
Exemplo n.º 10
0
 public function action()
 {
     $attrs_cond = array('id');
     $sql = TTransaction::get_delete_query('event', $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = parent::get_input_values($attrs_cond);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     }
     return parent::get_result();
 }
 public function action()
 {
     $attrs = array('id_user', 'id_dummy');
     $sql = TTransaction::get_insert_query('user_dummy', $attrs);
     // Parâmetros em ordem de aparição da query
     $query_values = parent::get_input_values($attrs);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     }
     return parent::get_result();
 }
Exemplo n.º 12
0
 public function action()
 {
     $attrs = array('name', 'username', 'email', 'password');
     $attrs_cond = array('id');
     $sql = TTransaction::get_update_query('user', $attrs, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = parent::get_input_values(array_merge($attrs, $attrs_cond));
     $query_values[3] = sha1($query_values[3]);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     }
     return parent::get_result();
 }
Exemplo n.º 13
0
 public static function run()
 {
     self::$time_start = microtime(true);
     $log_msg = "";
     // TODO: Substituir por $_POST
     if (isset($_GET['class'])) {
         $class_name = $_GET['class'];
         if (class_exists($class_name)) {
             try {
                 /** @var SimpleAction $action */
                 $action = new $class_name();
                 $result = $action->run();
                 self::$result = array_merge(self::$result, $result);
                 TTransaction::close();
             } catch (PDOException $pdo_e) {
                 // Grava a excessão que ocorreu.
                 $log_msg = $pdo_e->getMessage();
                 switch ($pdo_e->errorInfo[1]) {
                     case 1062:
                     case 1452:
                         self::$result["error"] = $pdo_e->errorInfo[1];
                         break;
                     default:
                         self::$result["error"] = 101;
                 }
                 TTransaction::rollback();
             } catch (Exception $e) {
                 // Grava a excessão que ocorreu.
                 $log_msg = $e->getMessage();
                 self::$result["error"] = 1;
                 TTransaction::rollback();
             }
         } else {
             self::$result["error"] = 2;
         }
         if (self::$result["msg"] == null) {
             self::$result["msg"] = Tools::get_error_msg(self::$result["error"]);
         }
         $log_msg = $log_msg ? $log_msg : self::$result["msg"];
         if (isset(self::$result["error"]) && self::$result["error"] != 0) {
             TTransaction::log($log_msg, 'error');
         }
         self::addCurrentTime('Fim de chamada');
         self::$result['time'] = self::$times;
         echo json_encode(self::$result);
     }
 }
 public function action()
 {
     $attrs = array('id_event', 'id_transaction');
     $sql = TTransaction::get_insert_query('event_transaction', $attrs);
     // Parâmetros em ordem de aparição da query
     $query_values = parent::get_input_values($attrs);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result !== false) {
         // Sucesso!
         TTransaction::close();
     } else {
         parent::set_error(101);
         TTransaction::rollback();
     }
     return parent::get_result();
 }
Exemplo n.º 15
0
 public function action()
 {
     $attrs = array();
     $attrs_cond = array();
     $sql = TTransaction::get_update_query('table', $attrs, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = parent::get_input_values(array_merge($attrs, $attrs_cond));
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     } else {
         //$this->treat_success($query_result);
     }
     return parent::get_result();
 }
 public function action()
 {
     $attrs = array('id', 'id_user2');
     $attrs_cond = array('id_user1');
     $sql = TTransaction::get_select_query('invitation', $attrs, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = array($this->connected);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     } else {
         $this->treat_success($query_result);
     }
     return parent::get_result();
 }
Exemplo n.º 17
0
 public function action()
 {
     $attrs = array('id, name');
     $attrs_cond = array('%name');
     $sql = TTransaction::get_select_query('user', $attrs, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = array('%' . parent::get_input('name_frag') . '%');
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     } else {
         $this->treat_success($query_result);
     }
     return parent::get_result();
 }
Exemplo n.º 18
0
 public function action()
 {
     $attrs = array('id', 'name');
     $attrs_cond = array($this->get_login_type(), 'password');
     $sql = TTransaction::get_select_query('user', $attrs, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = parent::get_input_values(array('login', 'password'));
     $query_values[1] = sha1($query_values[1]);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     } else {
         $this->treat_success($query_result);
     }
     return parent::get_result();
 }
Exemplo n.º 19
0
 public function action()
 {
     $attrs = array('name', 'start', 'end');
     $attrs_cond = array('id_user');
     $join = array('user_event' => array('id_event', 'event.id'));
     $sql = TTransaction::get_select_query('event', $attrs, $join, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = array($this->connected);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     } else {
         $this->treat_success($query_result);
     }
     return parent::get_result();
 }
Exemplo n.º 20
0
 /**
  * method onSave()
  * Executed whenever the user clicks at the save button
  */
 function onSave()
 {
     try {
         TTransaction::open('lacenrh');
         $this->form->validate();
         $servidor = $this->form->getData('Servidor');
         $servidor->store();
         new TMessage('info', 'Registro salvo.');
         $this->form->clear();
         TTransaction::close();
     } catch (Exception $e) {
         if ($e->getCode() == 23000) {
             new TMessage('error', '<b>Erro:</b> ' . 'Servidor já cadastrado.');
         } else {
             new TMessage('error', '<b>Erro:</b> ' . $e->getMessage());
         }
         TTransaction::rollback();
     }
 }
 /** Checa se o usuário conectado foi convidado por quem ele deseja convidar. Caso positivo, é executado como se
  * tivesse aceitado a solicitação. */
 private function check_invitation()
 {
     $attrs = array('id');
     $attrs_cond = array('id_user1', 'id_user2');
     $sql = TTransaction::get_select_query('invitation', $attrs, $attrs_cond);
     // Parâmetros em ordem de aparição da query
     $query_values = array(parent::get_input('id_user2'), $this->connected);
     // Resultado da query
     $query_result = TTransaction::safe_execute($sql, $query_values);
     if ($query_result === false) {
         parent::set_error(101);
         TTransaction::rollback();
     } else {
         if ($query_obj = $query_result->fetchObject()) {
             (new Insert_user_user(array('id_user1' => parent::get_input('id_user2'), 'id_invitation' => $query_obj->id)))->run();
             return true;
         }
     }
     return false;
 }
 function salvar($dados)
 {
     try {
         // inicia transação com o banco 'sq_livro'
         TTransaction::open('sq_livro');
         // define um arquivo de log
         TTransaction::setLogger(new TLoggerTXT('/tmp/log.txt'));
         // instancia um Active Record para cliente
         $cliente = new Cliente();
         // alimenta o registro com dados do array
         $cliente->fromArray($dados);
         $cliente->store();
         // armazena o objeto
         // fecha transação
         TTransaction::close();
     } catch (Exception $e) {
         // caso ocorra erros, volta a transação
         TTransaction::rollback();
         // retorna o erro na forma de um objeto SoapFault
         return new SoapFault("Server", $e->getMessage());
     }
 }
Exemplo n.º 23
0
 /**
  * Executed when the user chooses the record
  */
 public function onSelect($param)
 {
     try {
         $key = $param['key'];
         TTransaction::open('library');
         // load the active record
         $rep = new TRepository('Item');
         $criteria = new TCriteria();
         $criteria->add(new TFilter('barcode', '=', $key));
         $objects = $rep->load($criteria);
         if ($objects) {
             $item = $objects[0];
             $object = new StdClass();
             $object->barcode_input = $item->barcode;
             $object->book_title_input = $item->title;
             TForm::sendData('form_Loan', $object);
         } else {
             $object = new StdClass();
             $object->barcode_input = '';
             $object->book_title_input = '';
             TForm::sendData('form_Loan', $object);
         }
         // closes the transaction
         TTransaction::close();
         parent::closeWindow();
         // closes the window
     } catch (Exception $e) {
         // exibe a mensagem gerada pela exceção
         new TMessage('error', $e->getMessage());
         // desfaz todas alterações no banco de dados
         TTransaction::rollback();
     }
 }
 function onEdit($param)
 {
     try {
         // get the parameter $key
         $field = $param['field'];
         $key = $param['key'];
         $value = $param['value'];
         // open a transaction with database 'samples'
         TTransaction::open('samples');
         // instantiates object Customer
         $customer = new Customer($key);
         $customer->{$field} = $value;
         $customer->store();
         // close the transaction
         TTransaction::close();
         // reload the listing
         $this->onReload($param);
         // shows the success message
         new TMessage('info', "Record Updated");
     } catch (Exception $e) {
         // shows the exception error message
         new TMessage('error', '<b>Error</b> ' . $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }
    // obtém a conexão ativa
    $conn = TTransaction::get();
    // executa a instrução SQL
    $result = $conn->Query($sql->getInstruction());
    // escreve mensagem de LOG
    TTransaction::log($sql->getInstruction());
    // define a estratégia de LOG
    TTransaction::setLogger(new TLoggerXML('/tmp/arquivo.xml'));
    // escreve mensagem de LOG
    TTransaction::log("Inserindo registro Albert Einstein");
    // cria uma instrução de INSERT
    $sql = new TSqlInsert();
    // define o nome da entidade
    $sql->setEntity('famosos');
    // atribui o valor de cada coluna
    $sql->setRowData('codigo', 10);
    $sql->setRowData('nome', 'Albert Einstein');
    // obtém a conexão ativa
    $conn = TTransaction::get();
    // executa a instrução SQL
    $result = $conn->Query($sql->getInstruction());
    // escreve mensagem de LOG
    TTransaction::log($sql->getInstruction());
    // fecha a transação, aplicando todas as operações
    TTransaction::close();
} catch (Exception $e) {
    // exibe a mensagem de erro
    echo $e->getMessage();
    // desfaz operações realizadas durante a transação
    TTransaction::rollback();
}
Exemplo n.º 26
0
 /**
  * method onEdit()
  * Executed whenever the user clicks at the edit button da datagrid
  */
 function onView($param)
 {
     try {
         if (isset($param['key'])) {
             // get the parameter $key
             $key = $param['key'];
             // open a transaction with database 'changeman'
             TTransaction::open('changeman');
             // instantiates object Release
             $object = new Release($key);
             // fill the form with the active record data
             $this->form->setData($object);
             // close the transaction
             TTransaction::close();
         } else {
             $this->form->clear();
         }
     } catch (Exception $e) {
         // shows the exception error message
         new TMessage('error', '<b>Error</b> ' . $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }
Exemplo n.º 27
0
 function onSave()
 {
     try {
         // inicia transação com o banco 'pg_livro'
         TTransaction::open('pg_livro');
         // lê os dados do formulário e instancia um objeto Cliente
         $cliente = $this->form->getData('Cliente');
         // armazena o objeto no banco de dados
         $cliente->store();
         // finaliza a transação
         TTransaction::close();
         // exibe mensagem de sucesso
         new TMessage('info', 'Dados armazenados com sucesso');
     } catch (Exception $e) {
         // exibe a mensagem gerada pela exceção
         new TMessage('error', '<b>Erro</b>' . $e->getMessage());
         // desfaz todas alterações no banco de dados
         TTransaction::rollback();
     }
 }
 /**
  * method Delete()
  * Delete a record
  */
 function Delete($param)
 {
     try {
         // get the parameter $key
         $key = $param['key'];
         // open a transaction with database 'samples'
         TTransaction::open('samples');
         // instantiates object Customer
         $customer = new Customer($key);
         // deletes the object from the database
         $customer->delete();
         // close the transaction
         TTransaction::close();
         // reload the listing
         $this->onReload($param);
         // shows the success message
         new TMessage('info', "Record Deleted");
     } catch (Exception $e) {
         // shows the exception error message
         new TMessage('error', '<b>Error</b> ' . $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }
Exemplo n.º 29
0
 /**
  * method onSave()
  * Executed whenever the user clicks at the save button
  */
 function onSave()
 {
     try {
         // open a transaction with database 'changeman'
         TTransaction::open('changeman');
         // get the form data into an active record Issue
         $object = $this->form->getData();
         // form validation
         $this->form->validate();
         $member = Member::newFromLogin(TSession::getValue('login'));
         if ($member->password !== md5($object->current_password)) {
             throw new Exception(_t('Current password does not match'));
         }
         if ($object->new_password1 !== $object->new_password2) {
             throw new Exception(_t('New password does not match the confirm password'));
         }
         // stores the object
         $member->password = md5($object->new_password1);
         $member->store();
         // fill the form with the active record data
         $this->form->setData($object);
         // close the transaction
         TTransaction::close();
         // shows the success message
         new TMessage('info', _t('Password changed successfully'));
         // reload the listing
     } catch (Exception $e) {
         // shows the exception error message
         new TMessage('error', '<b>Error</b> ' . $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }
 /**
  * method onGenerate()
  * Executed whenever the user clicks at the generate button
  */
 function onGenerate()
 {
     try {
         // open a transaction with database 'samples'
         TTransaction::open('samples');
         // get the form data into an active record Customer
         $object = $this->form->getData();
         $repository = new TRepository('Customer');
         $criteria = new TCriteria();
         if ($object->name) {
             $criteria->add(new TFilter('name', 'like', "%{$object->name}%"));
         }
         if ($object->city_id) {
             $criteria->add(new TFilter('city_id', '=', "{$object->city_id}"));
         }
         if ($object->category_id) {
             $criteria->add(new TFilter('category_id', '=', "{$object->category_id}"));
         }
         $customers = $repository->load($criteria);
         $format = $object->output_type;
         if ($customers) {
             $widths = array(40, 150, 80, 120, 80);
             switch ($format) {
                 case 'html':
                     $tr = new TTableWriterHTML($widths);
                     break;
                 case 'pdf':
                     $tr = new TTableWriterPDF($widths);
                     break;
                 case 'rtf':
                     if (!class_exists('PHPRtfLite_Autoloader')) {
                         PHPRtfLite::registerAutoloader();
                     }
                     $tr = new TTableWriterRTF($widths);
                     break;
             }
             // create the document styles
             $tr->addStyle('title', 'Arial', '10', 'BI', '#ffffff', '#407B49');
             $tr->addStyle('datap', 'Arial', '10', '', '#000000', '#869FBB');
             $tr->addStyle('datai', 'Arial', '10', '', '#000000', '#ffffff');
             $tr->addStyle('header', 'Times', '16', 'BI', '#ff0000', '#FFF1B2');
             $tr->addStyle('footer', 'Times', '12', 'BI', '#2B2B2B', '#B5FFB4');
             // add a header row
             $tr->addRow();
             $tr->addCell('Customers', 'center', 'header', 5);
             // add titles row
             $tr->addRow();
             $tr->addCell('Code', 'left', 'title');
             $tr->addCell('Name', 'left', 'title');
             $tr->addCell('Category', 'left', 'title');
             $tr->addCell('Email', 'left', 'title');
             $tr->addCell('Birthdate', 'left', 'title');
             // controls the background filling
             $colour = FALSE;
             // data rows
             foreach ($customers as $customer) {
                 $style = $colour ? 'datap' : 'datai';
                 $tr->addRow();
                 $tr->addCell($customer->id, 'left', $style);
                 $tr->addCell($customer->name, 'left', $style);
                 $tr->addCell($customer->category_name, 'left', $style);
                 $tr->addCell($customer->email, 'left', $style);
                 $tr->addCell($customer->birthdate, 'left', $style);
                 $colour = !$colour;
             }
             // footer row
             $tr->addRow();
             $tr->addCell(date('Y-m-d h:i:s'), 'center', 'footer', 5);
             // stores the file
             if (!file_exists("app/output/tabular.{$format}") or is_writable("app/output/tabular.{$format}")) {
                 $tr->save("app/output/tabular.{$format}");
             } else {
                 throw new Exception(_t('Permission denied') . ': ' . "app/output/tabular.{$format}");
             }
             parent::openFile("app/output/tabular.{$format}");
             // shows the success message
             new TMessage('info', 'Report generated. Please, enable popups in the browser (just in the web).');
         } else {
             new TMessage('error', 'No records found');
         }
         // fill the form with the active record data
         $this->form->setData($object);
         // close the transaction
         TTransaction::close();
     } catch (Exception $e) {
         // shows the exception error message
         new TMessage('error', '<b>Error</b> ' . $e->getMessage());
         // undo all pending operations
         TTransaction::rollback();
     }
 }