Herramientas Informaticas

Categoría: CURSOS PHP

Creando CRUD de categorías usando AutoCrud #05

Ya vimos como crear módulos y catalogo ahora mostraremos como automatizar esa parte del proceso de desarrollo para ser un poco mas eficientes para ello escribimos un código que escribe el código repetitivo

Creamos el archivo app/controller/AutoCrudController.php con el siguiente código

Leer Mas: Creando CRUD de categorías usando AutoCrud #05
<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Controllers\Time;
use CodeIgniter\API\ResponseTrait;
use Faker\Provider\zh_CN\DateTime;

class AutoCrudController extends BaseController {

    use ResponseTrait;

    protected $db;

    public function __construct() {
        $this->db = \Config\Database::connect();
        helper('utilerias');
    }

    public function index($table) {
     /*
       $this->generateModel($table);
       $this->generateController($table);
       $this->generateView($table);
       $this->generateViewModal($table);
       $this->generateLanguage($table);
        */
        $this->generateMigration($table);
       
     //$this->generateLanguageES($table);

        $tableUpCase = ucfirst($table);
        $route = <<<EOF
                 \$routes->resource('$table', [
                                'filter' => 'permission:$table-permission',
                                'controller' => '{$table}Controller',
                                'except' => 'show'
                            ]);
                \$routes->post('$table/save', '{$tableUpCase}Controller::save');
                \$routes->post('{$table}/get{$tableUpCase}', '{$tableUpCase}Controller::get$tableUpCase');
        EOF;

        echo $route;
    }

    /**
     * Generate Model
     */
    public function generateModel($table) {

        $tableUpCase = ucfirst($table);
        $query = $this->db->getFieldNames($table);

        $fields = "";

        foreach ($query as $field) {
            $fields .= "'" . $field . "'" . ",";
        }


        $fields = substr($fields, 0, strlen($fields) - 1);

        $nombreClase = ucfirst($table) . "Model";

        $model = <<<EOF
        <?php
        namespace App\Models;
        use CodeIgniter\Model;
        class $nombreClase extends Model{
            protected \$table      = '$table';
            protected \$primaryKey = 'id';
            protected \$useAutoIncrement = true;
            protected \$returnType     = 'array';
            protected \$useSoftDeletes = true;
            protected \$allowedFields = [$fields];
            protected \$useTimestamps = true;
            protected \$createdField  = 'created_at';
            protected \$deletedField  = 'deleted_at';
            protected \$validationRules    =  [
            ];
            protected \$validationMessages = [];
            protected \$skipValidation     = false;
        }
                
        EOF;

        file_put_contents(ROOTPATH . "app/Models/$nombreClase.php", $model);
    }

    /**
     * Generate Controller
     * 
     */

    /**
     * Generate Controller
     */
    public function generateController($table) {

        $query = $this->db->getFieldNames($table);

        $fields = "";

        foreach ($query as $field) {
            $fields .= $field . ",";
        }


        $fields = substr($fields, 0, strlen($fields) - 1);

        $nameClassModel = ucfirst($table) . "Model";

        $tableUpCase = ucfirst($table);

        $controller = <<<EOF
        <?php
         namespace App\Controllers;
         use App\Controllers\BaseController;
         use \App\Models\{$nameClassModel};
         use App\Models\LogModel;
         use CodeIgniter\API\ResponseTrait;
         class {$tableUpCase}Controller extends BaseController {
             use ResponseTrait;
             protected \$log;
             protected $$table;
             public function __construct() {
                 \$this->$table = new $nameClassModel();
                 \$this->log = new LogModel();
                 helper('menu');
             }
             public function index() {
                 if (\$this->request->isAJAX()) {
                     \$datos = \$this->{$table}->select('$fields')->where('deleted_at', null);
                     return \Hermawan\DataTables\DataTable::of(\$datos)->toJson(true);
                 }
                 \$titulos["title"] = lang('$table.title');
                 \$titulos["subtitle"] = lang('$table.subtitle');
                 return view('$table', \$titulos);
             }
             /**
              * Read $tableUpCase
              */
             public function get$tableUpCase() {
                 \$id$tableUpCase = \$this->request->getPost("id$tableUpCase");
                 \$datos$tableUpCase = \$this->{$table}->find(\$id$tableUpCase);
                 echo json_encode(\$datos$tableUpCase);
             }
             /**
              * Save or update $tableUpCase
              */
             public function save() {
                 helper('auth');
                 \$userName = user()->username;
                 \$idUser = user()->id;
                 \$datos = \$this->request->getPost();
                 if (\$datos["id$tableUpCase"] == 0) {
                     try {
                         if (\$this->{$table}->save(\$datos) === false) {
                             \$errores = \$this->{$table}->errors();
                             foreach (\$errores as \$field => \$error) {
                                 echo \$error . " ";
                             }
                             return;
                         }
                         \$dateLog["description"] = lang("vehicles.logDescription") . json_encode(\$datos);
                         \$dateLog["user"] = \$userName;
                         \$this->log->save(\$dateLog);
                         echo "Guardado Correctamente";
                     } catch (\PHPUnit\Framework\Exception \$ex) {
                         echo "Error al guardar " . \$ex->getMessage();
                     }
                 } else {
                     if (\$this->{$table}->update(\$datos["id$tableUpCase"], \$datos) == false) {
                         \$errores = \$this->{$table}->errors();
                         foreach (\$errores as \$field => \$error) {
                             echo \$error . " ";
                         }
                         return;
                     } else {
                         \$dateLog["description"] = lang("$table.logUpdated") . json_encode(\$datos);
                         \$dateLog["user"] = \$userName;
                         \$this->log->save(\$dateLog);
                         echo "Actualizado Correctamente";
                         return;
                     }
                 }
                 return;
             }
             /**
              * Delete $tableUpCase
              * @param type \$id
              * @return type
              */
             public function delete(\$id) {
                 \$info$tableUpCase = \$this->{$table}->find(\$id);
                 helper('auth');
                 \$userName = user()->username;
                 if (!\$found = \$this->{$table}->delete(\$id)) {
                     return \$this->failNotFound(lang('$table.msg.msg_get_fail'));
                 }
                 \$this->{$table}->purgeDeleted();
                 \$logData["description"] = lang("{$table}.logDeleted") . json_encode(\$info$tableUpCase);
                 \$logData["user"] = \$userName;
                 \$this->log->save(\$logData);
                 return \$this->respondDeleted(\$found, lang('$table.msg_delete'));
             }
         }
                
        EOF;

        file_put_contents(ROOTPATH . "app/Controllers/{$tableUpCase}Controller.php", $controller);
    }

    /**
     * Generate View
     */
    public function generateView($table) {

        $tableUpCase = ucfirst($table);
        $query = $this->db->getFieldNames($table);

        $fields = "";

        $columnaDatatable = "";
        $datosDatatable = "";
        $variablesGuardar1 = "";
        $variablesFormData = "";
        $inputsEdit = "";
        $contador = 0;
        foreach ($query as $field) {
            $fields .= $field . ",";

            if ($contador > 0) {

                $columnaDatatable .= "<th><?= lang('$table.fields.$field') ?></th>" . PHP_EOL;

                $datosDatatable .= <<<EOF
                         
                        {
                            'data': '$field'
                        },
                        EOF . PHP_EOL;
                if ($field <> "created_at" && $field <> "updated_at" && $field <> "deleted_at") {
                    $variablesGuardar1 .= "var $field = $(\"#$field\").val();" . PHP_EOL;
                    $variablesFormData .= "datos.append(\"$field\", $field);" . PHP_EOL;
                    $inputsEdit .= "$(\"#$field\").val(respuesta[\"$field\"]);" . PHP_EOL;
                    ;
                }
            } else {
                $variablesGuardar1 .= <<<EOF
                    
                    var id$tableUpCase = $("#id$tableUpCase").val();
                    EOF . PHP_EOL;

                $variablesFormData .= <<<EOF
                        var datos = new FormData();
                        datos.append("id$tableUpCase", id$tableUpCase);
                        EOF . PHP_EOL;
            }
            $contador++;
        }
        $fields = substr($fields, 0, strlen($fields) - 1);
        $nameClassModel = ucfirst($table) . "Model";
        $view = <<<EOF
        <?= \$this->include('julio101290\boilerplate\Views\load\select2') ?>
        <?= \$this->include('julio101290\boilerplate\Views\load\datatables') ?>
        <?= \$this->include('julio101290\boilerplate\Views\load\\nestable') ?>
        <!-- Extend from layout index -->
        <?= \$this->extend('julio101290\boilerplate\Views\layout\index') ?>

        <!-- Section content -->
        <?= \$this->section('content') ?>

        <?= \$this->include('modules$tableUpCase/modalCapture$tableUpCase') ?>

        <!-- SELECT2 EXAMPLE -->
        <div class="card card-default">
         <div class="card-header">
             <div class="float-right">
                 <div class="btn-group">

                     <button class="btn btn-primary btnAdd$tableUpCase" data-toggle="modal" data-target="#modalAdd$tableUpCase"><i class="fa fa-plus"></i>

                         <?= lang('$table.add') ?>

                     </button>

                 </div>
             </div>
         </div>
         <div class="card-body">
             <div class="row">
                 <div class="col-md-12">
                     <div class="table-responsive">
                         <table id="table$tableUpCase" class="table table-striped table-hover va-middle table$tableUpCase">
                             <thead>
                                 <tr>

                                     <th>#</th>
                                     $columnaDatatable
                                     <th><?= lang('$table.fields.actions') ?> </th>

                                 </tr>
                             </thead>
                             <tbody>
                             </tbody>
                         </table>
                     </div>
                 </div>
             </div>
         </div>
        </div>
        <!-- /.card -->

        <?= \$this->endSection() ?>


        <?= \$this->section('js') ?>
        <script>

         /**
          * Cargamos la tabla
          */

         var table{$tableUpCase} = $('#table{$tableUpCase}').DataTable({
             processing: true,
             serverSide: true,
             responsive: true,
             autoWidth: false,
             order: [[1, 'asc']],

             ajax: {
                 url: '<?= base_url(route_to('admin/$table')) ?>',
                 method: 'GET',
                 dataType: "json"
             },
             columnDefs: [{
                     orderable: false,
                     targets: [$contador],
                     searchable: false,
                     targets: [$contador]

                 }],
             columns: [{
                     'data': 'id'
                 },
                
                 $datosDatatable
                 {
                     "data": function (data) {
                         return `<td class="text-right py-0 align-middle">
                                 <div class="btn-group btn-group-sm">
                                     <button class="btn btn-warning btnEdit$tableUpCase" data-toggle="modal" id$tableUpCase="\${data.id}" data-target="#modalAdd$tableUpCase">  <i class=" fa fa-edit"></i></button>
                                     <button class="btn btn-danger btn-delete" data-id="\${data.id}"><i class="fas fa-trash"></i></button>
                                 </div>
                                 </td>`
                     }
                 }
             ]
         });



         $(document).on('click', '#btnSave$tableUpCase', function (e) {

             $variablesGuardar1
             $("#btnSave$tableUpCase").attr("disabled", true);

             $variablesFormData

             $.ajax({

                 url: "<?= route_to('admin/$table/save') ?>",
                 method: "POST",
                 data: datos,
                 cache: false,
                 contentType: false,
                 processData: false,
                 success: function (respuesta) {
                     if (respuesta.match(/Correctamente.*/)) {
                
                         Toast.fire({
                             icon: 'success',
                             title: "Guardado Correctamente"
                         });

                         table$tableUpCase.ajax.reload();
                         $("#btnSave$tableUpCase").removeAttr("disabled");


                         $('#modalAdd$tableUpCase').modal('hide');
                     } else {

                         Toast.fire({
                             icon: 'error',
                             title: respuesta
                         });

                         $("#btnSave$tableUpCase").removeAttr("disabled");
                        

                     }

                 }

             }

             )

         });



         /**
          * Carga datos actualizar
          */


         /*=============================================
          EDITAR $tableUpCase
          =============================================*/
         $(".table$tableUpCase").on("click", ".btnEdit$tableUpCase", function () {

             var id$tableUpCase = $(this).attr("id$tableUpCase");
                
             var datos = new FormData();
             datos.append("id$tableUpCase", id$tableUpCase);

             $.ajax({

                 url: "<?= base_url(route_to('admin/$table/get$tableUpCase')) ?>",
                 method: "POST",
                 data: datos,
                 cache: false,
                 contentType: false,
                 processData: false,
                 dataType: "json",
                 success: function (respuesta) {
                     $("#id$tableUpCase").val(respuesta["id"]);
                     
                     $inputsEdit

                 }

             })

         })


         /*=============================================
          ELIMINAR $table
          =============================================*/
         $(".table$tableUpCase").on("click", ".btn-delete", function () {

             var id$tableUpCase = $(this).attr("data-id");

             Swal.fire({
                 title: '<?= lang('boilerplate.global.sweet.title') ?>',
                 text: "<?= lang('boilerplate.global.sweet.text') ?>",
                 icon: 'warning',
                 showCancelButton: true,
                 confirmButtonColor: '#3085d6',
                 cancelButtonColor: '#d33',
                 confirmButtonText: '<?= lang('boilerplate.global.sweet.confirm_delete') ?>'
             })
                     .then((result) => {
                         if (result.value) {
                             $.ajax({
                                 url: `<?= base_url(route_to('admin/$table')) ?>/` + id$tableUpCase,
                                 method: 'DELETE',
                             }).done((data, textStatus, jqXHR) => {
                                 Toast.fire({
                                     icon: 'success',
                                     title: jqXHR.statusText,
                                 });


                                 table$tableUpCase.ajax.reload();
                             }).fail((error) => {
                                 Toast.fire({
                                     icon: 'error',
                                     title: error.responseJSON.messages.error,
                                 });
                             })
                         }
                     })
         })

         $(function () {
            $("#modalAdd$tableUpCase").draggable();
            
        });


        </script>
        <?= \$this->endSection() ?>
                
        EOF;

        file_put_contents(ROOTPATH . "app/Views/{$table}.php", $view);
    }

    /**
     * Generate ViewModal
     */
    public function generateViewModal($table) {

        $tableUpCase = ucfirst($table);
        $query = $this->db->getFieldNames($table);

        $fields = "";

        $campos = "";
        $contador = 0;
        foreach ($query as $field) {
            $fields .= $field . ",";

            if ($contador > 0) {




                if ($field <> "created_at" && $field <> "updated_at" && $field <> "deleted_at") {

                    $campos .= <<<EOF
                        <div class="form-group row">
                            <label for="$field" class="col-sm-2 col-form-label"><?= lang('$table.fields.$field') ?></label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-pencil-alt"></i></span>
                                    </div>
                                    <input type="text" name="$field" id="$field" class="form-control <?= session('error.$field') ? 'is-invalid' : '' ?>" value="<?= old('$field') ?>" placeholder="<?= lang('$table.fields.$field') ?>" autocomplete="off">
                                </div>
                            </div>
                        </div>
                        EOF . PHP_EOL;
                }
            }




            $contador++;
        }


        $fields = substr($fields, 0, strlen($fields) - 1);

        $nameClassModel = ucfirst($table) . "Model";

        $viewModal = <<<EOF
        <!-- Modal $tableUpCase -->
          <div class="modal fade" id="modalAdd$tableUpCase" tabindex="-1" role="dialog" aria-labelledby="modalAdd$tableUpCase" aria-hidden="true">
              <div class="modal-dialog modal-lg" role="document">
                  <div class="modal-content">
                      <div class="modal-header">
                          <h5 class="modal-title"><?= lang('$table.createEdit') ?></h5>
                          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                          </button>
                      </div>
                      <div class="modal-body">
                          <form id="form-$table" class="form-horizontal">
                              <input type="hidden" id="id$tableUpCase" name="id$tableUpCase" value="0">

                              $campos
                
                          </form>
                      </div>
                      <div class="modal-footer">
                          <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal"><?= lang('boilerplate.global.close') ?></button>
                          <button type="button" class="btn btn-primary btn-sm" id="btnSave$tableUpCase"><?= lang('boilerplate.global.save') ?></button>
                      </div>
                  </div>
              </div>
          </div>

          <?= \$this->section('js') ?>


          <script>

              $(document).on('click', '.btnAdd$tableUpCase', function (e) {


                  $(".form-control").val("");

                  $("#id$tableUpCase").val("0");

                  $("#btnSave$tableUpCase").removeAttr("disabled");

              });

              /* 
               * AL hacer click al editar
               */



              $(document).on('click', '.btnEdit$tableUpCase', function (e) {


                  var id$tableUpCase = $(this).attr("id$tableUpCase");

                  //LIMPIAMOS CONTROLES
                  $(".form-control").val("");

                  $("#id$tableUpCase").val(id$tableUpCase);
                  $("#btnGuardar$tableUpCase").removeAttr("disabled");

              });




          </script>


          <?= \$this->endSection() ?>
                
        EOF;

        $path = ROOTPATH . "app/Views/modules$tableUpCase/";
        if (!is_dir($path))
            mkdir($path, 0777, TRUE);

        file_put_contents($path . "modalCapture{$tableUpCase}.php", $viewModal);
    }

    /**
     * Generate Languaje EN
     */
    public function generateLanguage($table) {

        $tableUpCase = ucfirst($table);
        $query = $this->db->getFieldNames($table);

        $fields = "";

        $campos = "";
        $contador = 0;
        foreach ($query as $field) {
            $fields .= $field . ",";

            if ($contador > 0) {






                $campos .= "\${$table}[\"fields\"][\"$field\"] = \"" . ucfirst($field) . "\";" . PHP_EOL;
            }




            $contador++;
        }


        $fields = substr($fields, 0, strlen($fields) - 1);

        $nameClassModel = ucfirst($table) . "Model";

        $languaje = <<<EOF
         <?php

        \${$table}["logDescription"] = "The $table was saved with the following data:";
        \${$table}["logUpdate"] = "The $table was updated  with the following data:";
        \${$table}["logDeleted"] = "The $table was deleted  with the following data:";
        \${$table}["msg_delete"] = "The $table was deleted  correctly:";

        \${$table}["add"] = "Add $tableUpCase";
        \${$table}["edit"] = "Edit $table";
        \${$table}["createEdit"] = "Create / Edit";
        \${$table}["title"] = "$table management";
        \${$table}["subtitle"] = "$table list";
        $campos
        \${$table}["fields"]["actions"] = "Actions";
        \${$table}["msg"]["msg_insert"] = "The $table has been correctly added.";
        \${$table}["msg"]["msg_update"] = "The $table has been correctly modified.";
        \${$table}["msg"]["msg_delete"] = "The $table has been correctly deleted.";
        \${$table}["msg"]["msg_get"] = "The $tableUpCase has been successfully get.";
        \${$table}["msg"]["msg_get_fail"] = "The $table not found or already deleted.";

        return $$table;
                
        EOF;

        $path = ROOTPATH . "app/Language/en/";
        if (!is_dir($path))
            mkdir($path, 0777, TRUE);

        file_put_contents($path . "$table.php", $languaje);
    }

    /**
     * Lenguaje ES
     * @param type $table
     */
    public function generateLanguageES($table) {

        $tableUpCase = ucfirst($table);
        $query = $this->db->getFieldNames($table);

        $fields = "";

        $campos = "";
        $contador = 0;
        foreach ($query as $field) {
            $fields .= $field . ",";

            if ($contador > 0) {


                $campos .= "\${$table}[\"fields\"][\"$field\"] = \"" . ucfirst($field) . "\";" . PHP_EOL;
            }




            $contador++;
        }


        $fields = substr($fields, 0, strlen($fields) - 1);

        $nameClassModel = ucfirst($table) . "Model";

        $languaje = <<<EOF
         <?php
        \${$table}["logDescription"] = "El registro en $table fue guardado con los siguientes datos:";
        \${$table}["logUpdate"] = "El registro en $table fue actualizado con los siguientes datos:";
        \${$table}["logDeleted"] = "El registro en $table fue eliminado con los siguientes datos:";
        \${$table}["msg_delete"] = "El Registro en $table fue eliminado correctamente:";
        \${$table}["add"] = "Agregar $tableUpCase";
        \${$table}["edit"] = "Editar $table";
        \${$table}["createEdit"] = "Crear / Editar";
        \${$table}["title"] = "Admon. $table";
        \${$table}["subtitle"] = "Lista $table";
        $campos
         \${$table}["fields"]["actions"] = "Acciones";       
        \${$table}["msg"]["msg_insert"] = "Registro agregado correctamente.";
        \${$table}["msg"]["msg_update"] = "Registro modificado correctamente.";
        \${$table}["msg"]["msg_delete"] = "Registro eliminado correctamente.";
        \${$table}["msg"]["msg_get"] = "Registro obtenido correctamente.";
        \${$table}["msg"]["msg_get_fail"] = "Registro no encontrado o eliminado.";
        return $$table;
                
        EOF;

        $path = ROOTPATH . "app/Language/es/";
        if (!is_dir($path))
            mkdir($path, 0777, TRUE);

        file_put_contents($path . "$table.php", $languaje);
    }

    /**
     * Generate Migration
     * @param type $table
     */
    public function generateMigration($table) {

        $tableUpCase = ucfirst($table);
        $query = $this->db->getFieldData($table);

        $campos = "";
        $contador = 0;
        foreach ($query as $field) {


            
            if ($contador > 0) {

                
                if($field->nullable==1){
                    
                    $nullable="true";
                    
                }   else{
                    
                    $nullable="false";
                    
                } 
                if ($field->name <> "created_at" && $field->name <> "updated_at" && $field->name <> "deleted_at") {
                    $campos .= "'{$field->name}'             => ['type' => '{$field->type}', 'constraint' => {$field->max_length}, 'null' => $nullable]," . PHP_EOL;
                }
            } else {

                    $campos .= "'id'                    => ['type' => 'int', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true]," . PHP_EOL;
            }



            $contador++;
        }




        $nameClassModel = ucfirst($table) . "Model";

        $migration = <<<EOF
            <?php
            namespace App\Database\Migrations;
            use CodeIgniter\Database\Migration;
            class $tableUpCase extends Migration
            {
            public function up()
            {
             // $tableUpCase
            \$this->forge->addField([
                $campos
                'created_at'       => ['type' => 'datetime', 'null' => true],
                'updated_at'       => ['type' => 'datetime', 'null' => true],
                'deleted_at'       => ['type' => 'datetime', 'null' => true],
            ]);
            \$this->forge->addKey('id', true);
            \$this->forge->createTable('$table', true);
            }
            public function down(){
                \$this->forge->dropTable('$table', true);
                }
            }
        EOF;

        $path = ROOTPATH . "app/Database/Migrations/";
        if (!is_dir($path))
            mkdir($path, 0777, TRUE);

        $fechaActual = fechaParaMigraciones(fechaHoraActual());

        file_put_contents($path . "{$fechaActual}_{$tableUpCase}.php", $migration);

        //file_put_contents($path . "2023-02-07-165411_$tableUpCase.php", $viewModal);
    }
    
    

}

Creamos el archivo app/helpers/utilerias_helper.php con el siguiente codigo

<?php

function strMenuActivo($strMenu1, $strMenu2) {
    if ($strMenu1 == $strMenu2) {
        $respuesta = 'class="active"';
    } else {
        $respuesta = "";
    }
    return $respuesta;
}

//SI LA VARIABLE ESTA VACIA O NO SETA DECLARADA MANDARA CERO SIEMPRE, ES COMO EL VAL DE VISUAL BASIC 6.0

function esCero($value) {

    if (empty($value)) {
        return "0";
    } else {
        return $value;
    }
}

//FECHA SQL PARA GUARDAR EN BASE DE DATOS

function fechaSQL($fecha) {

    return date("Ymd", strtotime($fecha));
}

// CONVIERTE FECHA MYSQLDATETIME A HTML5
function fechaMySQLADateTimeHTML5($fecha) {

    return date("Y-m-d", strtotime($fecha)) . "T" . date("H:i:s", strtotime($fecha));
}

function agregarMinutos($fecha, $minutos) {


    return date("Y/m/d h:i:s", strtotime($fecha . "+ $minutos minutes"));

    /*
      $fecha1= new DateTime($fecha);
      $fecha1->add(new DateInterval('PT10H30S'));
      return $date->format('Y-m-d H:i:s') . "\n";
     * 
     */
}

//CONVIERTE LA FECHA EN PERIODO
function fechaPeriodo($fecha) {

    return date("Ym", strtotime($fecha));
}

//OBTIENE FECHA ACTUAL
function fechaActual() {

    return date("Y/m/d");
}

//OBTIENE FECHA HORA ACTUAL

function fechaHoraActual() {

    return date("Y-m-d H:i:s ", time());
}

//DIFERENCIA ENTRE MINUTOS
function diferenciaMinutos($fecha_i, $fecha_f) {
    $minutos = (strtotime($fecha_i) - strtotime($fecha_f)) / 60;

    $minutos = abs($minutos);
    $minutos = floor($minutos);

    return $minutos;
}

function strSellar($llave, $password, $cadenaOriginal) {


    $archivoPem = "/tmp/llave.key.pem";
    $comando = "openssl pkcs8 -inform DER -in $llave -passin pass:$password -out $archivoPem";

    exec($comando);
    $sello = "ok";

    //Sellar
    $archivo = openssl_pkey_get_private(file_get_contents($archivoPem));
    $sig = "";
    openssl_sign($cadenaOriginal, $sig, $archivo, OPENSSL_ALGO_SHA256);

    $sello = base64_encode($sig);

    return $sello;
}

//SOLO DIA
function dia($fecha) {

    return date("d", strtotime($fecha));
}

//SOLO MES
function mes($fecha) {

    return date("m", strtotime($fecha));
}

//SOLO AÑO
function año($fecha) {

    return date("Y", strtotime($fecha));
}

//GENERA UUID
function generaUUID() {


    $uuid = service('uuid');
    $uuid4 = $uuid->uuid4();
    $string = $uuid4->toString();

    return $string;
}

function satinizar($var, $type) {
    switch ($type) {
        case 'html':
            $safe = htmlspecialchars($var);
            break;
        case 'sql':
            $safe = mysql_real_escape_string($var);
            break;
        case 'file':
            $safe = preg_replace('/(\/|-|_)/', '', $var);
            break;
        case 'shell':
            $safe = escapeshellcmd($var);
            break;
        default:
            $safe = htmlspecialchars($var);
    }
    return $safe;
}

function limpiaCadena($cadena) {

    $cadena = str_replace('"', "", $cadena);
    $cadena = str_replace('\n', "", $cadena);
    $cadena = str_replace('\t', "", $cadena);
    $cadena = trim($cadena);

    $cadena = preg_replace("[\n|\r|\n\r]", "", $cadena);

    $descripcion = preg_replace("[\n|\r|\n\r]", "", $descripcion);

    return $cadena;
}


// CONVIERTE FECHA MYSQLDATETIME A HTML5
function fechaParaMigraciones($fecha) {

    return date("Y-m-d", strtotime($fecha)) . date("His", strtotime($fecha));
    
}

En rutas ponemos el siguiente codigo

$routes->get('generateCRUD/(:any)', 'AutoCrudController::index/$1');

Creamos la tabla de categorías

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 21-04-2023 a las 20:19:25
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 7.4.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de datos: `ci4jcpos`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `categorias`
--

CREATE TABLE `categorias` (
  `id` int(11) NOT NULL,
  `descripcion` varchar(128) COLLATE utf8mb4_spanish2_ci DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish2_ci;

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `categorias`
--
ALTER TABLE `categorias`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `categorias`
--
ALTER TABLE `categorias`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Corremos la siguiente URL en el navegador para crear todo el catalogo

http://localhost:8080/admin/generateCRUD/categorias

Esto nos generara los archivos necesarios y ademas la ruta para agregarlo en routes.php


         $routes->resource('categorias', [
                        'filter' => 'permission:categorias-permission',
                        'controller' => 'categoriasController',
                        'except' => 'show'
                    ]);
        $routes->post('categorias/save', 'CategoriasController::save');
        $routes->post('categorias/getCategorias', 'CategoriasController::getCategorias');
Ya solo hacemos los cambios estéticos necesarios, agregamos los permisos necesarios corregimos la ruta en el menú y listo
Video Demostrativo

Creando modulo de configuración de correo electrónico #04

Ya creamos el catalogo de empresas, ahora vamos a ir creando un modulo de configuración de correo electrónico

Primero creamos el archivo del modelo en app/Models/SettingsMailModel.php con el siguiente contenido

<?php

namespace App\Models;

use CodeIgniter\Model;

class SettingsMailModel extends Model
{
    protected $table      = 'mailsettings';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    protected $returnType     = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['id', 'email', 'host', 'smtpDebug', 'SMTPAuth', 'port', 'created_at', 'deleted_at', 'updated_at', 'smptSecurity', 'pass'];
}

Para la tabla donde se guardara la información corremos el siguiente código SQL en PHPMYADMIN en nuestra base de datos, en publicaciones posteriores les dejare los archivos de migración para que no tengan la necesidad de correr archivos SQL y sirva para diferentes motores de base de datos

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 18-04-2023 a las 00:56:17
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 7.4.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de datos: `wheelsoft`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `mailsettings`
--

CREATE TABLE `mailsettings` (
  `id` int(11) NOT NULL,
  `email` varchar(512) DEFAULT NULL,
  `host` varchar(128) DEFAULT NULL,
  `smtpDebug` varchar(16) DEFAULT NULL,
  `SMTPAuth` varchar(16) DEFAULT NULL,
  `port` varchar(16) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `smptSecurity` varchar(64) DEFAULT NULL,
  `pass` varchar(128) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Volcado de datos para la tabla `mailsettings`
--

INSERT INTO `mailsettings` (`id`, `email`, `host`, `smtpDebug`, `SMTPAuth`, `port`, `created_at`, `deleted_at`, `updated_at`, `smptSecurity`, `pass`) VALUES
(1, 'mail@domain.com', 'mail.host5.com', '1', '1', '587', NULL, NULL, NULL, 'tls', 'password');

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `mailsettings`
--
ALTER TABLE `mailsettings`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `mailsettings`
--
ALTER TABLE `mailsettings`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creamos el archivo app/controllers/SettingsMailController.php con el siguiente contenido

<?php

namespace julio101290\boilerplate\Controllers\Users;

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use App\Models\SettingsMailModel;
use App\Models\LogModel;
use julio101290\boilerplate\Controllers\BaseController;
use julio101290\boilerplate\Entities\Collection;
use julio101290\boilerplate\Models\GroupModel;
use CodeIgniter\Config\Services;
use App\Models\RegisterModel;
use App\Controllers\RegisterController;
use PHPMailer\PHPMailer;

/**
 * Class UserController.
 */
class SettingsMailController extends BaseController
{

    use ResponseTrait;

    /** @var \agungsugiarto\boilerplate\Models\GroupModel */
    protected $group;
    protected $settingsMail;
    protected $log;
    protected $register;
    protected $registerController;
    protected $custumer;

    /** @var \agungsugiarto\boilerplate\Models\UserModel */
    protected $users;

    public function __construct()
    {
        $this->group = new GroupModel();
        $this->log = new LogModel();
        $this->settingsMail = new SettingsMailModel();
        $autorize = $this->authorize = Services::authorization();
        helper('menu');
    }

    public function index()
    {




        $datos = $this->settingsMail->where("id", 1)->first();

        $data["title"] = "Correo Electronicos";
        $data["subtitle"] = "Configuraciones de Correo Electronico";
        $data["data"] = $datos;

        return view('mailSettings', $data);
    }

    /** 
    public function sendMailPDF($uuid)
    {

        //DATOS CORREO
        $datos = $this->settingsMail->where("id", 1)->first();

        //DATOS  REGISTRO

        $register = $this->register->select("*")->where("uuid", $uuid)->first();

        $custumer = $this->custumer->select("*")->where("id", $register["custumer"])->first();

        $mailsTarjets = "";

        $correo = $datos["email"];
        $SMTPDebug = $datos["smtpDebug"];
        $host = $datos["host"];

        if ($datos["SMTPAuth"] == 1) {
            $SMTPAuth = true;
        } else {
            $SMTPAuth = false;
        }

        $puerto = $datos["port"];
        $clave = $datos["pass"];

        $SMTPSeguridad = $datos["smptSecurity"];

        // Load Composer's autoloader
        // Instantiation and passing `true` enables exceptions
        $mail = new PHPMailer\PHPMailer();

        try {


            //Server settings
            $mail->SMTPDebug = $SMTPDebug;                      // Enable verbose debug output
            $mail->isSMTP();                                            // Send using SMTP
            $mail->Host = $host;                    // Set the SMTP server to send through
            $mail->SMTPAuth = $SMTPAuth;                                   // Enable SMTP authentication
            $mail->Username = $correo;                     // SMTP username
            $mail->Password = $clave;                               // SMTP password
            $mail->SMTPSecure = $SMTPSeguridad;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
            $mail->Port = $puerto;

            $nombreEmpresa = "";
            // TCP port to connect to
            //Recipients
            $mail->setFrom($correo, $nombreEmpresa);

            if ($custumer["email1"] != "") {
                try {
                    $mailAddress = $mail->addAddress($custumer["email1"], '');

                    if (!$mailAddress) {

                        echo "Error con el correo Electronico";
                        return;
                    }
                } catch (Exception $ex) {

                    echo $ex->getMessage();
                }
            }

            if ($custumer["email2"] != "") {

                try {
                    $mailAddress = $mail->addAddress($custumer["email2"], '');

                    if (!$mailAddress) {

                        echo "Error con el correo Electronico";
                        return;
                    }
                } catch (Exception $ex) {

                    echo $ex->getMessage();
                }
            }

            if ($custumer["email3"] != "") {

                try {
                    $mailAddress = $mail->addAddress($custumer["email3"], '');

                    if (!$mailAddress) {

                        echo "Error con el correo Electronico";
                        return;
                    }

                    if (!$mailAddress) {

                        echo "Error con el correo Electronico";
                        return;
                    }
                } catch (Exception $ex) {

                    echo $ex->getMessage();
                }
            }

            if ($custumer["email4"] != "") {

                try {
                    $mailAddress = $mail->addAddress($custumer["email4"], '');

                    if (!$mailAddress) {

                        echo "Error con el correo Electronico";
                        return;
                    }
                } catch (Exception $ex) {

                    echo $ex->getMessage();
                }
            }

            if ($custumer["email5"] != "") {

                try {
                    $mailAddress = $mail->addAddress($custumer["email5"], '');

                    if (!$mailAddress) {

                        echo "Error con el correo Electronico";
                        return;
                    }
                } catch (Exception $ex) {

                    echo $ex->getMessage();
                }
            }
            // Add a recipient
            //$mail->addReplyTo('info@example.com', 'Information');
            //mail->addCC('cc@example.com');
            //$mail->addBCC('bcc@example.com');
            // Attachments
            $attachment = $this->registerController->report($uuid, 1);
            $mail->AddStringAttachment($attachment, 'registro' . $register["codeCustumer"] . '.pdf', 'base64', 'application/pdf');

            // Add attachments
            //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
            // Content
            $mail->isHTML(true);                                  // Set email format to HTML
            $mail->Subject = "Envio de Registro";
            $mail->Body = "Adjuntamos el registro de verificación de neumaticos";
            $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            try {
                $send = $mail->send();
            } catch (Exception $ex) {

                echo $ex->getMessage();
                return;
            }

            if ($send) {
                echo 'Correo Enviado Correctamente';
            } else {
                echo 'Error al enviar el correo';
            }
        } catch (Exception $e) {
            echo "Error al enviar el correo: {$e->ErrorInfo}";
        }
    }
*/
    public function guardar()
    {


        helper('auth');
        $userName = user()->username;
        $idUser = user()->id;

        //GUARDA CONFIGURACIONES
        $this->settingsMail->update(1, $_POST);

        //  return redirect()->to("/admin/hospital");
        return redirect()->back()->with('sweet-success', 'Actualizado Correctamente');
        // return redirect()->back()->with('sweet-success','Guardado Correctamente');
    }
}

Creamos el archivo app/views/mailSettings.php con el siguiente contenido

<?= $this->extend('julio101290\boilerplate\Views\layout\index') ?>

<!-- Section content -->
<?= $this->section('content') ?>



<section class="content">
    <div class="container-fluid">
        <div class="row">

            <div class="col-md-12">

                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Configuración Correo Electrónico</h3>
                    </div>



                    <form action="<?= base_url('admin/mailSettings') ?>/save" method="post">
                        <?= csrf_field() ?>

                        <div class="card-body">


                            <div class="form-group">
                                <label for="nombreEmpresa">E-Mail</label>
                                <input type="text" class="form-control" id="email" value="<?= $data["email"] ?>" name="email" placeholder="Inserte el Email">
                            </div>

                            <div class="form-group">
                                <label for="correoElectronico">Host</label>
                                <input type="text" class="form-control" value="<?= $data["host"] ?>" id="host" name="host" placeholder="Host">
                            </div>

                            <div class="form-group">
                                <label for="smtpDebug">Debug Client</label>
                                <select id="smtpDebug" name="smtpDebug">

                                    <option value="0">DEBUG_OFF</option>

                                    <option value="1">DEBUG_CLIENT</option>

                                    <option value="2">DEBUG_SERVER</option>

                                </select>

                            </div>

                            <div class="form-group">
                                <label for="SMTPAuth">SMTP Auth</label>
                                <select id="SMTPAuth" name="SMTPAuth">


                                    <option value=""></option>

                                    <option value="0">Sin autentificación</option>

                                    <option value="1">Con autentificación</option>


                                </select>

                            </div>


                            <div class="form-group">
                                <label for="smptSecurity">Seguridad</label>
                                <select id="smptSecurity" name="smptSecurity">


                                    <option value="">Sin Seguridad</option>
                                    <option value="ssl">Seguridad SSL</option>
                                    <option value="tls">Seguridad TLS</option>

                                </select>

                            </div>


                            <div class="form-group">
                                <label for="port">Puerto</label>
                                <input type="number" class="form-control" value="<?= $data["port"] ?>" id="port" name="port" placeholder="Puerto">
                            </div>

                            <div class="form-group">
                                <label for="port">Contraseña</label>
                                <input type="password" class="form-control" value="<?= $data["pass"] ?>" id="pass" name="pass" placeholder="Contraseña">
                            </div>


                        </div>

                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary btnGuardar">Guardar</button>
                        </div>
                    </form>
                </div>





            </div>



        </div>

    </div>
</section>


<?= $this->endSection() ?>


<?= $this->section('js') ?>
<script>
    $("#smptSecurity").val("<?= $data["smptSecurity"] ?>");
    $("#SMTPAuth").val("<?= $data["SMTPAuth"] ?>");
    $("#smtpDebug").val("<?= $data["smtpDebug"] ?>");
</script>
<?= $this->endSection() ?>

en app/config/routes.php agregamos el siguiente codigo

 $routes->resource('emailSettings', [
        'filter' => 'permission:email-permiso',
        'controller' => 'SettingsMailController',
    ]);
    
    $routes->post('mailSettings/save', 'SettingsMailController::guardar');
    
    //Para futuros envios
    //$routes->get('mailSettings/sendMail/(:any)', 'SettingsMailController::sendMailPDF/$1');
Y listo ya tenemos nuestro modulo de configuración solo tenemos que ajustar unos permisos y roles
Video Demostrativo

Nuevo Cambio boilerplate para CodeIgniter 4 Responsive Datatable

Se realizo un pequeño cambio en el proyecto boilerplate para CodeIgniter 4, en el cual las tablas podrán ser responsivas

Si ya están usando este proyecto solo hay que actualizar via composer

composer update

Y en la llamada del datatable agregar responsive:true por ejemplo

 var tableUser = $('#table-user').DataTable({
        processing: true,
        serverSide: true,
        responsive: true,
        autoWidth: false,
        order: [[1, 'asc']],

Y el resultado será el siguiente

Saludos y espero que les sea útil

Como convertir Web hecha en PHP8 con FrameWork CodeIgniter 4 en una APP de Escritorio

code

git clone https://github.com/electron/electron-quick-start.git

en el archivo package.json lo dejamos de la siguiente manera

	{

	"build": {
	"appId": "com.electron.example",
	"compression": "maximum"
	},
	"name": "XML2PDF CFDI",

	"version": "2.0.0",

	"description": "Una pequeña aplicación para convertir el CFDI XML a PDF",

	"main": "main.js",

	"compression": "maximum",

	"scripts": {

	"***": null,
	"pro:windows": "electron-builder --win"

	},
	"repository": "https://github.com/electron/electron-quick-start",  

	"keywords": [
	"CFDI",
	"XML",
	"PDF",
	"tutorial"
	],
	"author": "Julio Cesar Leyva Rodriguez",
	"license": "CC0-1.0",
	"devDependencies": {
	"electron": "^21.2.3",
	"electron-builder": "^22.14.13",
	"electron-packager": "^17.1.1"
	},
	"dependencies": {
	"modclean": "^3.0.0-beta.1"
	}
	}

en main.js lo dejamos haci lo que hara es cargar la url y levantar el servicio de php

	// Modules to control application life and create native browser window

	const {app, BrowserWindow} = require('electron')

	const path = require('path')

	const exec = require('child_process').exec;

	  
	  

	function execute(command, callback) {

	exec(command, (error, stdout, stderr) => {

	callback(stdout);

	});

	};

	  
	  

	// call the function

	execute('Ejecutar.bat', (output) => {

	console.log(output);

	});

	  

	function createWindow () {

	// Create the browser window.

	const mainWindow = new BrowserWindow({

	width: 800,

	height: 600,

	webPreferences: {

	preload: path.join(__dirname, 'preload.js')

	}

	})

	  

	// and load the index.html of the app.

	mainWindow.setMenu(null)

	mainWindow.loadURL('http://localhost:8097')

	  

	// Open the DevTools.

	// mainWindow.webContents.openDevTools()

	}

	  

	// This method will be called when Electron has finished

	// initialization and is ready to create browser windows.

	// Some APIs can only be used after this event occurs.

	app.whenReady().then(() => {

	createWindow()

	  

	app.on('activate', function () {

	// On macOS it's common to re-create a window in the app when the

	// dock icon is clicked and there are no other windows open.

	if (BrowserWindow.getAllWindows().length === 0) createWindow()

	})

	})

	  

	// Quit when all windows are closed, except on macOS. There, it's common

	// for applications and their menu bar to stay active until the user quits

	// explicitly with Cmd + Q.

	app.on('window-all-closed', function () {

	if (process.platform !== 'darwin') app.quit()

	})

	  

	// In this file you can include the rest of your app's specific main process

	// code. You can also put them in separate files and require them here.

ahora posicionados en la carpeta \electron-quick-start> corremos el siguiente comando

npm install

Después creamos el paquete-ejecutable con el siguiente comando

electron-packager . -platform=win32 -arch=x64 ConversorXMLPDF

y nos genera los archivos necesarios
image

Creamos una carpeta en C: llamada aplicación o como ustedes quieran llamarle y copiamos el contenido, la carpeta del proyecto del codeigniter y los archivos ejecutable de PHP con los que trabajan, pueden copiar los del xampp y con el que debugean a través de netbeans
quedaría de la siguiente forma

image

ConvertidorXMLPDF seria el proyecto en codeigniter, php8 son los binarios necesarios para ejecutar código php, este lo pueden extraer de xampp y lo demas son los archivos de electronJS

Ahora en el archivo de configuración de código igniter en config/app.php en la base URL la dejamos asi

public $baseURL = '[http://localhost:8097/](http://localhost:8097/)';

El archivo Ejecutar.bat es el que va iniciar todo el codeigniter y dentro de el va el siguiente codigo

@echo off

php8\php.exe convertidorXMLPDF/spark serve --port 8097

El archivo Ejecutar.bat se ejecuta automáticamente al abrir el ejecutable

Y listo ahora solo queda hacer el instalador pero lo dejamos para otro manual.

JCPOS2022 CRUD Empresas Guardar Logo Certificado y Archivo Key

Bien ahora para seguir avanzando haremos las altas bajas y cambios del catalogo de empresas ya que actualmente solo tenemos para meter datos de una empresa.

Aprovechando meteremos varios campos extras como el logo, contraseña (Por si se tiene que ingresar por empresa), archivo .cer y .key y contraseña del certificado, por si en un futuro se mete la facturación electronica.

COMO REGRESAR ARCHIVOS DEL CÓDIGO FUENTE A UNA VERSIÓN ANTERIOR

En algunas ocasiones hacemos cambios nuevos en el fuente y el resultado no es satisfactorio, como es el caso de agregarle la función de guardar las imágenes directamente en la base de datos, en nuestro caso el resultado fue que funciono mas lento, ya que no queda de otra que volver a la versión anterior.

Esto no sera problema en nuestro caso ya que manejamos la tecnología GIT, y en nuestro caso con Netbeans sera mucho mas fácil volver a la versión anterior.

Primero listamos los archivos que modificamos que serian los siguientes.

  1. controladores/usuarios.controlador.php
  2. vistas/usuarios.php
  3. vistas/cabezote.php
  4. vistas/menu.php
  5. ajax/usuarios.ajax.php
  6. modelos/usuarios.modelo.php

Buscamos el commit donde no tenia los cambios que no deseamos y le damos click y luego revert y así con todos los archivos que hicimos cambios.

Por ultimo eliminamos el campo archivoFoto de la tabla usuarios con este comando

ALTER TABLE `usuarios` DROP `archivoFoto`;

Y bien seria todo el cambio por hoy les dejo el fuente para que lo puedan descargar y el demo, saludos y espero que les sea de utilidad

Acceso a un sistema con PHP, MySQL

 

php-logo

Utilizando las funciones de MySQL AES_ENCRYPT

   1: 

   2:  

   3: INGRESO AL SISTEMA 

   4: <?php

   5: /*******************************************************************************************************************

   6: *                             DESCRIPCION: ESTE ARCHIVO TIENE LA FUNCION DE CONECTAR CON LA BASE DE DATOS.             *

   7: *                             PROGRAMADOR: JULIO CESAR LEYVA RODRIGUEZ.                                               *

   8: *                             FECHA:          01/07/2012                                                               *

   9: ********************************************************************************************************************/

  10:  

  11:  

  12:  

  13: function conectar_mysql($direccion,$usuario,$password,$basededatos)

  14:     {

  15:     global $enlace;

  16:     if(!($enlace=mysql_connect($direccion,$usuario,$password)))

  17:         {

  18:         echo " alert('error de conexion')";

  19:         exit();

  20:         }

  21:     if(!(mysql_select_db($basededatos,$enlace)))

  22:         {

  23:         echo " alert('error al conectar con la base de datos')";

  24:         exit();

  25:         }

  26:     return $enlace;

  27:     }

  28:     

  29: function desconectar()

  30:     {

  31:     mysql_close($enlace);

  32:     }

  33:  

  34:     

  35:     

  36:     /*FUNCION QUE TE PERMITIRA VALIDAR SI UN CAMPO TE TEXTO ESTA VACIO

  37: 

  38:     Esta función se puede usar en un condición "if" */

  39:  

  40:      

  41:  

  42:      function validar_campo($campo)

  43:  

  44:         {

  45:  

  46:         if($campo=="")

  47:  

  48:            return(true);

  49:  

  50:           

  51:  

  52:        else

  53:  

  54:            return(false);

  55:  

  56:        }

  57:     function buscar($data)

  58:     {

  59:         

  60:     $total = mysql_num_rows(mysql_query($data));

  61:     if($total==0)

  62:         return(false);

  63:     else

  64:         return(true);

  65:     }

  66:     

  67:     ?>

  68:     

  69:     <form id "acceso" name "acceso" method="post" action="index.php">

  70:     

  71:     <table  border='0' align="Center">

  72:         

  73:         

  74:         

  75:             

  76:                 <img align="Center" src="http://1.bp.blogspot.com/_JrrrT5TM9lQ/SV8pjlllv0I/AAAAAAAAACQ/OpyoqSeY_SY/s320/escudo.jpg" 

  77:                     border="0" width="200" height="200">

  78:             

  79:         

  80:     

  81:     

  82:     <table align="center">

  83:         

  84:         

  85:             <td align = "center">

  86:         

  87:             USUARIO

  88:             

  89:             

  90:         

  91:         

  92:             

  93:             

  94:             <input name="usuario" type="text"/>

  95:             

  96:         

  97:         

  98:         

  99:         

 100:             <td align = "center">

 101:         

 102:             PASSWORD

 103:             

 104:             

 105:         

 106:         

 107:             

 108:             

 109:             <input name="pass" type="password"/>

 110:             

 111:         

 112:         

 113:         

 114:             <td align="center">

 115:              <input type="submit" name="Submit" value="Accesar">

 116:             

 117:         

 118:     

 119:     

 120:     

 121: <?php

 122: $usuario=@$_POST['usuario'];

 123: $password=@$_POST['pass'];

 124: $llave="millave";

 125: if(validar_campo($usuario)==false && validar_campo($password)==false)

 126:     {

 127:     $direccion1="localhost";

 128:     $usuario1="root";

 129:     $password1="";

 130:     $basededatos1="bd_itlm";

 131:     conectar_mysql($direccion1,$usuario1,$password1,$basededatos1);

 132:  

 133:     

 134:      $busqueda = "SELECT * FROM usuarios WHERE usuario='$usuario' AND 

 135:                                             clave=AES_ENCRYPT('$password','$llave')";

 136:     

 137:     if(buscar($busqueda)==true)

 138:         {

 139:         Echo " alert('ENCONTRADO')";

 140:         }

 141:     else

 142:         {

 143:         Echo " alert('NO ENCONTRADO')";

 144:         }

 145:     }

 146: ?>

 147:     

 148: 

ENVIAR UN CORREO CON PHP

php-logo
Un pequeño script que hice para una sola ocasión, se los dejo para que lo modifiquen y lo usen de acuerdo a sus necesidades.

   1: <?php
   2: //FUNCION QUE ENVIA UN CORREO ELECTRONICO
   3:  function enviar_correo($correo_e,$nombre,$asunto,$edificio,$dia,$mes,$anio,$hora,$minuto)
   4:     {
   5:     $headers = "MIME-Version: 1.0n";
   6:     $headers .= "Content-type: text/html; charset=utf-8n";
   7:     $headers .= "From: no-reply n";
   8:     $headers .= "X-Mailer: PHP/" . phpversion();
   9:     
  10:     $mensaje="Estimado $nombre se ha registrado su prestamo para el $dia de $mes del $anio a las $hora : $minuto";
  11:     mail($correo_e,$asunto,$mensaje,$headers);
  12:     }
  13:  ?>

DESCARGAR CODIGO FUENTE

Script para conectar PHP con Mysql

php-logo
Les dejo un código que hice hace unos meses, lo hice para hacer eso de la conexión en una sola línea y no andar perdiendo tiempo
Son dos funciones hasta ahora, una para conectar y otra para desconectar,he pensado hacer el de liberar resultados entre otros pero aun no le veo ventaja.
A veces es necesario hacer esto para ahorrar tiempo, cuando utilizas muchas veces la misma conexión.

   1: <?php
   2: /*******************************************************************************************************************
   3: *                             DESCRIPCION: ESTE ARCHIVO TIENE LA FUNCION DE CONECTAR CON LA BASE DE DATOS.             *
   4: *                             PROGRAMADOR: JULIO CESAR LEYVA RODRIGUEZ.                                               *
   5: *                             FECHA:          01/07/2012                                                               *
   6: ********************************************************************************************************************/
   7:  
   8: function conectar_mysql($direccion,$usuario,$password,$basededatos)
   9:     {
  10:     global $enlace;
  11:     if(!($enlace=mysql_connect($direccion,$usuario,$password)))
  12:         {
  13:         echo " alert('error de conexion')";
  14:         exit();
  15:         }
  16:     if(!(mysql_select_db($basededatos,$enlace)))
  17:         {
  18:         echo " alert('error al conectar con la base de datos')";
  19:         exit();
  20:         }
  21:     return $enlace;
  22:     }
  23:     
  24: function desconectar()
  25:     {
  26:     mysql_close($enlace);
  27:     }
  28: ?>

Ya en el momento de invocarla seria

   1: <?php
   2:  
   3: include "conexionmysql.php";
   4:  
   5: //ESTOS DATOS LOS PUEDES TENER EN OTRO ARCHIVO PHP TE AHORRARIA TIEMPO
   6: $direccion="mysql12.000webhost.com";
   7: $usuario="a5270459_tec";
   8: $pass="Tec101290";
   9: $bd="a5270459_tec";
  10:  
  11: conectar_mysql("$direccion","$usuario","$pass","$bd");
  12:  
  13: ?>

O también lo puedes hacer directamente sin variables

   1: <?php
   2:  
   3: include "conexionmysql.php";
   4:  
   5:  
   6: conectar_mysql("localhost","tuUsuraio","tuPassword","TuBaseDeDatos");
   7:  
   8: ?>

A si este ultimo no les sale traten sin las comillas x) no recuerdo en este momento si llevan x)

Página 3 de 3

Creado con WordPress & Tema de Anders Norén