Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
MVC Update (PDO)
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / M-BiTsy / M-BiTsy Support

2020-04-08 17:09:50
The way the TT code is set up is old fashioned so heres a mvc core i added to my pdo project
im in the process of making my way through all the files and quickly moving to controllers which will just leave separating the ui

thought id share if anyone wants to see how i do it, create 4 folders
core, controllers, views & models

.htaccess (route everything through index)
<IfModule mod_rewrite.c>
 Options -Multiviews
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule  ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>


init.php (this is functions in v3 the defines are different as well BASEPATH/BACKEND)
require_once (TTROOT."/core/Database.php");
require_once (TTROOT."/core/Controller.php");
require_once (TTROOT."/core/Router.php");


core/Controller   (loads models/views)
<?php
 /*
  * Base Controller
  * Loads the models and views
  */
 class Controller {
   // Load model
   public function model($model){
     // Require model file
     require_once TTROOT.'/models/' . $model . '.php';

     // Instatiate model
     return new $model();
   }

   // Load view
   public function view($view, $data = []){
     // Check for view file
     if(file_exists(TTROOT.'/views/' . $view . '.php')){
       require_once TTROOT.'/views/' . $view . '.php';
     } else {
       // View does not exist
       die('View does not exist');
     }
   }
 }


core/Database.php (2nd dbclass which will replce the static one)
<?php
 /*
  * PDO Database Class
  * Connect to database
  * Create prepared statements
  * Bind values
  * Return rows and results
  */
 class Database {
   private $host = DB_HOST;
   private $user = DB_USER;
   private $pass = DB_PASS;
   private $dbname = DB_NAME;

   private $dbh;
   private $stmt;
   private $error;

   public function __construct(){
     // Set DSN
     $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
     $options = array(
       PDO::ATTR_PERSISTENT => true,
       PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
     );

     // Create PDO instance
     try{
       $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
     } catch(PDOException $e){
       $this->error = $e->getMessage();
       echo $this->error;
     }
   }

   // Chained Prepared Statements
   public function run($sql, $bind = NULL){
       if (!$bind)
       {
           return $this->dbh->query($sql);
       }
       $stmt = $this->dbh->prepare($sql);
       $stmt->execute($bind);
       return $stmt;
   }
 }


core/Router.php   (use url to get contoller/method/parameter) clean urls
<?php
 /*
  * App Router Class
  * Creates URL & loads core controller
  * URL FORMAT - /controller/method/params
  */
 class Router {
   protected $currentController = 'index';
   protected $currentMethod = 'index';
   protected $params = [];

   public function __construct(){
     //print_r($this->getUrl());

     $url = $this->getUrl();

     // Look in controllers for first value
     if(file_exists(TTROOT.'/controllers/' . ucwords($url[0]). '.php')){
       // If exists, set as controller
       $this->currentController = ucwords($url[0]);
       // Unset 0 Index
       unset($url[0]);
     }

     // Require the controller
     require_once TTROOT.'/controllers/'. $this->currentController . '.php';

     // Instantiate controller class
     $this->currentController = new $this->currentController;

     // Check for second part of url
     if(isset($url[1])){
       // Check to see if method exists in controller
       if(method_exists($this->currentController, $url[1])){
         $this->currentMethod = $url[1];
         // Unset 1 index
         unset($url[1]);
       }
     }

     // Get params
     $this->params = $url ? array_values($url) : [];

     // Call a callback with array of params
     call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
   }

   public function getUrl(){
     if(isset($_GET['url'])){
       $url = rtrim($_GET['url'], '/');
       $url = filter_var($url, FILTER_SANITIZE_URL);
       $url = explode('/', $url);
       return $url;
     }
   }
 }


index.php  (notice we keep stdhead, dbconn & stdfoot) these 3 functions need replacing but for now we keep them as they are
<?php
require_once("backend/init.php");
dbconn(true);
loggedinonly ();
stdhead(T_("HOME"));

// Init Router Library
 $init = new Router;

stdfoot();


for how i started using it
this is my staff controller which is the old staff.php code placed in a class that extends the core/ controller
we then add model to constructor im still in process of updating the root files so ill post some more better examples with the ui & model separated
still need to finish models as well, thats why we keep old db so everything works as it should till we get to it
instead of staff.php  in url  use  staff
first we remove these from staff.php
require_once("backend/init.php");
dbconn();
stdhead();
stdfoot();


Then we make it a class controller

controllers/Staff.php (Naming is important for autoload eg Torrentsupload.php)
<?php
 class Staff extends Controller {
   public function __construct(){
     $this->userModel = $this->model('User');
   }

   public function index(){
 $dt = get_date_time(gmtime() - 180);

 $res = DB::run("SELECT `users`.`id`, `users`.`username`, `users`.`class`, `users`.`last_access` FROM `users` INNER JOIN `groups` ON `users`.`class` = `groups`.`group_id` WHERE `users`.`enabled` =? AND `users`.`status` =? AND `groups`.`staff_page` =? ORDER BY `username`", ['yes', 'confirmed', 'yes']);
 $col = [];  //undefined var
 $table = []; //undefined var
 while ( $row = $res->fetch(PDO::FETCH_ASSOC) )
 {
     $table[$row["class"]] = ($table[$row["class"]]).
       "<td><img src='/images/button_o".($row["last_access"] > $dt ? "n" : "ff")."line.png' alt='' /> ".
       "<a href='account-details.php?id=".$row["id"]."'>" . (new Curuser)->class_colour($row["username"]) . "</a> ".
       "<a href='mailbox.php?compose&amp;id=".$row["id"]."'><img src='/images/button_pm.gif' border='0' alt='' /></a></td>";

      $col[$row['class']] = ($col[$row['class']] ?? 0) + 1;

     if ($col[$row["class"]] <= 4)
         $table[$row["class"]] = $table[$row["class"]] . "<td></td>";
     else
     {
         $table[$row["class"]] = $table[$row["class"]] . "</tr><tr>";
         $col[$row["class"]] = 2;
     }
 }

 $where = null;
 if ($CURUSER["edit_users"] == "no")
     $where = "AND `staff_public` = 'yes'";

 $res = DB::run("SELECT `group_id`, `level`, `staff_public` FROM `groups` WHERE `staff_page` = 'yes' $where ORDER BY `staff_sort`");

 if ($res->rowCount() == 0)
     show_error_msg(T_("ERROR"), T_("NO_STAFF_HERE"), 1);

 begin_frame(T_("STAFF"));
?>
 <div class="table-responsive"><table class="table">
 <?php while ($row = $res->fetch(PDO::FETCH_ASSOC)): if ( !isset($table[$row["group_id"]]) ) continue; ?>

 <tr>
     <td colspan="14" class="newtd"><center><b><?php echo T_($row["level"]); ?></b> <?php if ($row["staff_public"] == "no") echo("<font color='#ff0000'>[".T_("HIDDEN FROM PUBLIC")."]</font>"); ?><center></td>
 </tr>
 <tr>
     <?php echo $table[$row["group_id"]]; ?>
 </tr>

 <?php endwhile; ?>
 </table></div>
 <?php

 end_frame();
   }
 }
2020-04-17 17:52:38
I downloaded the master code. I copied the files. I inserted the SQL code. Updated the config.php to my setup. and started up the site.

And it simply works...and looks the same as default TT.

[USER=20288]@m-jay[/USER] compliments!! I am sure there are lots of things you wanna change and update, but amazing still. With so many changes in the background.
If It Ain't Dutch, It Ain't Much!!
2020-04-17 19:31:00
Thank you I've enjoyed playing with the script.
Got another theme for it somewhere got too many folders on my pc lol
There will be odd update over next few days
Going make most of this free time
2020-04-18 00:34:35
"m-jay, post: 68403, member: 20288":

Thank you I've enjoyed playing with the script.
Got another theme for it somewhere got too many folders on my pc lol
There will be odd update over next few days
Going make most of this free time


Excellent. Yes much free time too, must keep myself busy
2020-04-18 11:14:15
Thought id share the last 3 phases
Moving the theme was not necessary this was a personal choice it was just stdhead, stdfoot and links in header to css & js  & in the theme admincp
Depending how much work this is to someone else if its not worth it you dont need to

But ill go through what i plan to do so you can see the end product and the goal posts dont keep moving, in github anything from moving the theme onwards is optional and its about options now and these options are available through git at any time

[color=rgb(250, 197, 28)]THE BACKEND (This is finished ready to add to github)[/color]
A classes folder has been added (dbclass, cache, BEcode, mail)  all classes will be here)

The helpers folder


The functions have been taken from everywhere except admincp & announce and the functions have been split into little specific files
The cookie helper
<?php
// Obtain / Create Cookie Function
function logincookie($id, $password, $secret, $updatedb = 1, $expires = 0x7fffffff)
{
   // Retrieving Cookie Information
   $hash = $id . $secret . $password . getip() . $secret;
   // Cookie Information Encryption
   $hash = password_hash($hash, PASSWORD_BCRYPT);
   // Declaration And Sending Cookie
   setcookie("pass", $hash, $expires, "/");
   setcookie("uid", $id, $expires, "/");

   if ($updatedb) {
       $stmt = DB::run("UPDATE users SET last_login=? WHERE id=?", [get_date_time(), $id]);
   }

}
// Cookie Destruction function
function logoutcookie()
{
   // Declaration And Sending Cookie
   // As Set to NULL ==> Destruction
   setcookie("pass", null, time(), "/");
   setcookie("uid", null, time(), "/");
}


All cookie functions in there, all torrent functions in torrents etc again this is personal choice it makes no difference and some will say its slower
but the difference in speed is the smallest of fractions, its to make life easier for myself and updating much easier in future.
there is a mods helper for any new functions for mods so mod functions will be separate,
The files have different names so can be added over time or in 6 months but its about preference but id recommend including modded functions separate from now

Been thinking of renaming functions so the helper is in the name but i have left it for now like
show_error_message = show_general_error_message in general_helper.php
this will probably be last thing i do

[color=rgb(250, 197, 28)]The Models & Views[/color]
This just leaves these 2 now every things moved, any old TT page should have its own controller then updating is just file for file
for mods we save the mod controller, mod helper & mod view & mod model so mods can be separated

while the controllers are there to see over time the plan is to remove from the controllers the frontend where possible into views & all queries will be called from the model
on github theres a example of the finished accountlogin

Again this isnt something that needs to be done the controllers work as they are but its something to be aware of if you want to stay close to the project
The approach behind this is to have a place for everything, make updating easier and moderniser structure a little bit
2020-04-18 12:35:20
updated github with final backend & moved a few more root files to controllers exceptions, adminmodtaks
That just leaves controllers these are fully functional so no rush were good to go
2020-04-18 13:31:45
Too early to add this to github but its what ive added to assist with breaking controllers down
This doesn't effect anything its just a starter template and a unit tester
to view go to SITEURL/atest & SITEURL/atest/one

I'll keep adding examples to it as I go
new models.zip
Download
2020-04-18 20:27:32
"m-jay, post: 68408, member: 20288":

Too early to add this to github but its what ive added to assist with breaking controllers down
This doesn't effect anything its just a starter template and a unit tester
to view go to SITEURL/atest & SITEURL/atest/one

I'll keep adding examples to it as I go


Thanks!!
Unknown User
2020-04-19 11:23:56
I had a look at some of this, after some observations I would recommend making all models require the database e.g __construct(Database $db) and set it to a property inside the given model, and then all the methods of a model can use that property to access the dB, the static calling should be avoided.
2020-04-19 11:45:08
there is 2 db classes both the same except ones a static the other is not this has been considered before, thats the long term plan m8 but its there now so ill go through them
the static dbclass.php (this was for putting everything together)
DB::run  (everything/everywhere works)

the new core Database.php (this does what you say)
its in constructor for models (called from class itself)

in functions or anywhere we can call it
$PDO = new Database
$PDO->run

And there is a new global in dbconn global $PDO = new Database;
global $PDO;
$PDO->run
Unknown User
2020-04-19 11:59:24
Do you have this setup on github? I think it would be good to change cookies to sessions but allow the user to have a remember me option
2020-04-19 14:50:17
Just splitting controllers up left but its fully functional and will have a release page in a day or two
[URL unfurl="true"]https://github.com/M-jay84/Torrent-Trader-MVC-PDO-OOP[/url]
2020-04-24 17:22:53
dont have much experience with sessions so would this be secure [USER=20311]@shadows[/USER] [USER=20335]@mostvotedplaya[/USER]
seems to work fine and the session user_key is encrytpted
remove this
    //Check The Cookie and get CURUSER details
   if (strlen($_COOKIE["pass"]) != 60 || !is_numeric($_COOKIE["uid"])) {
       logoutcookie();
       return;
   }


with this
    if (!is_numeric($_COOKIE['uid']) || (int) $_COOKIE['uid'] < 1 || !isset($_COOKIE['pass']) ) {
       logoutcookie();
       return;
   }
session_start()
   if(isset($_COOKIE['uid']) || isset($_COOKIE['pass'])) {

       $_SESSION['user_id'] = $_COOKIE['uid'];
       $_SESSION['user_key'] = $_COOKIE['pass'];
   }

echo $_SESSION['user_id'];
echo $_SESSION['user_key'];


to test in staff.php
replace
loggedinonly();


with
if (!(isset($_SESSION['user_key']) && $_SESSION['user_key'] != '')) {

header ("Location: /account/login");

}


we would add destroy session to logout, would it be safe to use session to call model
    public function getUserById($id){
     $row = $this->db->run("SELECT id, password, secret, status, enabled FROM users WHERE username =? ", [$id])->fetch();
     return $row;

$id = $_SESSION['user_id'];
$res = $this->userModel-> getUserById($id)

   }
Unknown User
2020-04-25 07:34:05
Ideally the logincookie needs to populate the session, and user login should check whether a session is active.
2020-04-25 07:54:49
That can be done I'm redoing account controller now with sessions
I have login, logout, recover etc all in one controller just pulling models and views out
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 3
  • Members: 0
  • Guests online: 3
  • Comments: 3
  • Messages: 1,728