File: /var/www/vhosts/onlinedev.com/httpdocs/admin/framework.php
<?php
session_start();
require_once('config.php');
/* Start Framework */
class Db
{
protected $link;
protected $resource;
public function __construct($h, $u, $p, $d)
{
$this->connect($h, $u, $p, $d);
}
public function connect($host, $user, $pass, $db)
{
$this->link = mysql_connect($host, $user, $pass);
if (!$this->link)
{
throw new Exception('Could not connect to database, error: '.mysql_error());
}
if (!mysql_select_db($db, $this->link))
{
throw new Exception('Could not select database, error: '.mysql_error());
}
}
public function query($sql)
{
$this->resource = mysql_query($sql);
if (!$this->resource)
{
throw new Exception('Query error, error: '.mysql_error($this->link).', query='.$sql);
}
if (preg_match('/^SELECT/i', $sql)) return mysql_num_rows($this->resource);
else if (preg_match('/^INSERT/i', $sql)) return mysql_insert_id($this->link);
else return mysql_affected_rows($this->link);
}
public function getValue()
{
$row = array();
if ($this->resource)
{
$row = mysql_fetch_array($this->resource);
}
return $row[0];
}
public function getRow()
{
$row = array();
if ($this->resource)
{
$row = mysql_fetch_array($this->resource);
}
return $row;
}
public function getArray()
{
$rows = array();
if ($this->resource)
{
while ($row = mysql_fetch_array($this->resource)) {
$rows[] = $row;
}
}
return $rows;
}
public static function escape($str)
{
return mysql_escape_string($str);
}
}
class DBFactory
{
/**
* @return DB
*/
public function &getInstance()
{
static $instance;
if (!$instance)
{
$instance = new Db(HOST, USER, PASS, DBNAME);
}
return $instance;
}
}
class Model
{
protected $tableId = 'id';
protected $tableName;
protected $tableFields;
protected $pagination;
public function get($id)
{
$field = $this->tableId;
$this->$field = $id;
$this->findFirst();
}
public function findFirst()
{
$sql = $this->buildQuery();
$db = DBFactory::getInstance();
$db->query($sql);
$row = $db->getRow();
if (!empty($row))
{
foreach ($this->tableFields as $field)
{
$this->$field = ($row[$field]);
}
return true;
}
else
{
return false;
}
}
public function getArray($start=0, $count=0, $orderby=null, $getobjects = false)
{
$sql = $this->buildQuery($start, $count, $orderby);
$db = DBFactory::getInstance();
$db->query($sql);
if ($getobjects)
{
$ret = array();
$className = get_class($this);
foreach ($db->getArray() as $k => $row)
{
$ret[$k] = new $className;
foreach ($this->tableFields as $field)
{
if ($row[$field])
$ret[$k]->$field = $row[$field];
}
}
return $ret;
}
else
{
return $db->getArray();
}
}
public function count()
{
$sql = $this->buildCountQuery();
$db = DBFactory::getInstance();
$db->query($sql);
return $db->getValue();
}
public function reset()
{
foreach ($this->tableFields as $field)
{
$this->$field = null;
}
}
public function save()
{
$IDfield = $this->tableId;
if ($this->$IDfield && $this->id_exists($this->$IDfield))
{
return $this->update();
}
else
{
return $this->insert();
}
}
public function insert()
{
$sql = ' INSERT INTO '.$this->tableName.'(';
$ok = false;
foreach ($this->tableFields as $field)
{
if (isset($this->$field) && !is_null($this->$field) && strlen($this->$field))
{
$ok = true;
$sql .= ''. $field.',';
}
}
if(!$ok) return false;
$sql = preg_replace('/,$/', ')', $sql);
$sql .= ' VALUES (';
foreach ($this->tableFields as $field)
{
if (isset($this->$field) && !is_null($this->$field) && strlen($this->$field))
{
$sql .= '"'.Db::escape($this->$field).'",';
}
}
$sql = preg_replace('/,$/', ')', $sql);
return DBFactory::getInstance()->query($sql);
}
public function update()
{
$IDField = $this->tableId;
$sql = 'UPDATE '.$this->tableName.' SET ';
foreach ($this->tableFields as $field)
{
if (isset($this->$field) && !is_null($this->$field) && strlen($this->$field) && $field != $IDField)
{
$sql .= $field.'="'.Db::escape($this->$field).'",';
}
}
$sql = preg_replace('/,$/', ' ', $sql);
$sql .= 'WHERE '.$IDField.' = "'.Db::escape($this->$IDField).'" ';
return DBFactory::getInstance()->query($sql);
}
public function id_exists($id)
{
if ($id)
{
$sql = 'SELECT id FROM '.$this->tableName.' WHERE id='.$id;
$db = DBFactory::getInstance();
$db->query($sql);
if ($db->getValue()) return true;
else return false;
}
else
{
return false;
}
}
protected function buildQuery($start=0, $count=0, $orderby=null)
{
$sql = 'SELECT * FROM '.$this->tableName.' WHERE 1=1 ';
foreach ($this->tableFields as $k => $field)
{
if (!is_null($this->$field))
$sql .= 'AND ' . $field. ' = "'.Db::escape($this->$field).'" ';
}
if ($orderby)
{
$sql .= ' ORDER BY '.$orderby.' ';
}
if ($start && $count)
{
$sql .= 'LIMIT '.$start.', '.$count;
}
else if ($count)
{
$sql .= 'LIMIT '.$count;
}
return $sql;
}
protected function buildCountQuery()
{
$sql = 'SELECT COUNT(*) AS total FROM '.$this->tableName.' WHERE 1=1 ';
foreach ($this->tableFields as $k => $field)
{
if (!is_null($this->$field))
$sql .= 'AND ' . $field. ' = "'.Db::escape($this->$field).'" ';
}
return $sql;
}
public function delete($id = null)
{
if (!$id)
{
$field = $this->tableId;
$id = $this->$field;
}
if (!$id)
{
return false;
}
$sql = 'DELETE FROM ' . $this->tableName . ' WHERE id = %s' ;
$sql = sprintf($sql, intval($id)) ;
DBFactory::getInstance()->query($sql);
}
public function paginate($link, $perpage, $orderby=null, $getobjects = false)
{
$this->pagination = new Pagination();
$this->pagination->setLink($link);
$this->pagination->setPage(isset($_GET['page']) ? (int) $_GET['page'] : 1);
$this->pagination->setSize($perpage);
$this->pagination->setTotalRecords($this->count());
return $this->getArray(($this->pagination->page - 1) * $this->pagination->size, $this->pagination->size, $orderby, $getobjects);
}
public function getPagination()
{
return $this->pagination->create_links();
}
}
class Controller
{
protected $mastertemplate = false;
protected $mastervars = array();
public $users = array();
public function getUrl($module, $action, $params=array())
{
return App::getUrl($module, $action, $params);
}
public function getBaseUrl($absolute = true)
{
return App::getBaseUrl($absolute);
}
public function getBasePath()
{
return App::getBasePath();
}
public function redirect($module, $action, $params)
{
$url = $this->getUrl($module, $action , $params);
$this->_redirect($url);
}
public function loadTemplate($template)
{
if ($template && is_file($this->getBasePath() . DIRECTORY_SEPARATOR . App::templatedir . DIRECTORY_SEPARATOR . $template.'.phtml'))
{
foreach (get_object_vars($this) as $var => $value)
{
$$var = $value;
}
ob_start();
include($this->getBasePath() . DIRECTORY_SEPARATOR . App::templatedir . DIRECTORY_SEPARATOR . $template.'.phtml');
$content = ob_get_clean();
return $content;
}
else
{
throw new Exception('Error: template file ' . $template . ' does not exist');
}
}
public function loadMasterTemplate($template)
{
$this->mastertemplate = $template;
}
public function setMasterVar($var, $val)
{
$this->mastervars[$var] = $val;
}
public function getRequest($var, $default=null)
{
return App::getRequest($var, $default);
}
public function _redirect($url, $die=true, $onlyJScript=false)
{
App::_redirect($url, $die, $onlyJScript);
}
public function doAction($action)
{
if ( ! $this->userHasAccess()) throw new Exception('Access restricted!');
$content = call_user_method($action, $this);
if ($this->mastertemplate && is_file(App::templatedir . DIRECTORY_SEPARATOR . $this->mastertemplate . '.phtml'))
{
foreach ($this->mastervars as $var => $val)
{
$$var = $val;
}
ob_start();
include(App::templatedir . DIRECTORY_SEPARATOR . $this->mastertemplate . '.phtml');
$result = ob_get_clean();
return $result;
}
else if ($this->mastertemplate)
{
throw new Exception('Error: master template file '.$this->mastertemplate .' not found');
}
else
{
return $content;
}
}
public function userHasAccess () {
return in_array($_SERVER['REMOTE_USER'], $this->users);
}
}
class Pagination
{
/**
* Current Page
*
* @var integer
*/
var $page;
/**
* Size of the records per page
*
* @var integer
*/
var $size;
/**
* Total records
*
* @var integer
*/
var $total_records;
/**
* Link used to build navigation
*
* @var string
*/
var $link;
/**
* Class Constructor
*
* @param integer $page
* @param integer $size
* @param integer $total_records
*/
function Pagination($page = null, $size = null, $total_records = null)
{
$this->page = $page;
$this->size = $size;
$this->total_records = $total_records;
}
/**
* Set's the current page
*
* @param unknown_type $page
*/
function setPage($page)
{
$this->page = 0+$page;
}
/**
* Set's the records per page
*
* @param integer $size
*/
function setSize($size)
{
$this->size = 0+$size;
}
/**
* Set's total records
*
* @param integer $total
*/
function setTotalRecords($total)
{
$this->total_records = 0+$total;
}
/**
* Sets the link url for navigation pages
*
* @param string $url
*/
function setLink($url)
{
$this->link = $url;
}
/**
* Returns the LIMIT sql statement
*
* @return string
*/
function getLimitSql()
{
$sql = "LIMIT " . $this->getLimit();
return $sql;
}
/**
* Get the LIMIT statment
*
* @return string
*/
function getLimit()
{
if ($this->total_records == 0)
{
$lastpage = 0;
}
else
{
$lastpage = ceil($this->total_records/$this->size);
}
$page = $this->page;
if ($this->page < 1)
{
$page = 1;
}
else if ($this->page > $lastpage && $lastpage > 0)
{
$page = $lastpage;
}
else
{
$page = $this->page;
}
$sql = ($page - 1) * $this->size . "," . $this->size;
return $sql;
}
/**
* Creates page navigation links
*
* @return string
*/
function create_links()
{
$totalItems = $this->total_records;
$perPage = $this->size;
$currentPage = $this->page;
$link = $this->link;
$totalPages = floor($totalItems / $perPage);
$totalPages += ($totalItems % $perPage != 0) ? 1 : 0;
if ($totalPages < 1 || $totalPages == 1){
return null;
}
$output = null;
//$output = '<span id="total_page">Page (' . $currentPage . '/' . $totalPages . ')</span> ';
$loopStart = 1;
$loopEnd = $totalPages;
if ($totalPages > 5)
{
if ($currentPage <= 3)
{
$loopStart = 1;
$loopEnd = 5;
}
else if ($currentPage >= $totalPages - 2)
{
$loopStart = $totalPages - 4;
$loopEnd = $totalPages;
}
else
{
$loopStart = $currentPage - 2;
$loopEnd = $currentPage + 2;
}
}
if ($loopStart != 1){
$output .= sprintf('<li class="disabledpage"><a href="' . $link . '">«</a></li>', '1');
}
if ($currentPage > 1){
$output .= sprintf('<li class="nextpage"><a href="' . $link . '">Précédent</a></li>', $currentPage - 1);
}
for ($i = $loopStart; $i <= $loopEnd; $i++)
{
if ($i == $currentPage){
$output .= '<li class="currentpage">' . $i . '</li> ';
} else {
$output .= sprintf('<li><a href="' . $link . '">', $i) . $i . '</a></li> ';
}
}
if ($currentPage < $totalPages){
$output .= sprintf('<li class="nextpage"><a href="' . $link . '">Suivant</a></li>', $currentPage + 1);
}
if ($loopEnd != $totalPages){
$output .= sprintf('<li class="nextpage"><a href="' . $link . '">»</a></li>', $totalPages);
}
return '<div class="pagination"><ul>' . $output . '</ul></div>';
}
}
final class App
{
const defaultmodule = 'news';
const defaultaction = 'index';
const templatedir = 'templates';
const use_urlrewrite = false;
public static function init()
{
$controller_class_name = ucfirst(strtolower(App::getRequest('module', self::defaultmodule ))) . 'Controller';
if (class_exists($controller_class_name))
{
$controller = new $controller_class_name;
$method_name = strtolower(App::getRequest('action', self::defaultaction )) . 'Action' ;
if (method_exists($controller, $method_name))
{
try {
$result = call_user_method('doAction', $controller, $method_name);
echo $result;
} catch (Exception $ex) {
echo 'Error, unhandled exception: '. $ex->getMessage();
}
}
}
}
public static function getRequest($var, $default_value = null)
{
return isset($_REQUEST[$var]) ? $_REQUEST[$var] : $default_value;
}
public static function getUrl($module, $action, $params=array())
{
if (self::use_urlrewrite)
{
$url = self::getBaseUrl() . $module . '/' . $action ;
foreach ($params as $k=> $param)
{
$url .= $k.'/'.$param;
}
}
else
{
$url = self::getBaseUrl() . '?module='.$module.'&action='.$action;
foreach ($params as $k => $param)
{
$url .= '&'.$k.'='.$param;
}
}
return $url;
}
public static function getBaseUrl()
{
$url = 'https://' . $_SERVER['HTTP_HOST'] . '/';
if (strpos($_SERVER['REQUEST_URI'], '/admin') !== false) $url .= 'admin/';
return $url;
}
public static function getBasePath()
{
$dirname = dirname($_SERVER['SCRIPT_FILENAME']);
return preg_match('/.*\/$/', $dirname) ? $dirname : $dirname . '';
}
public static function loadPartial($template)
{
ob_start();
include(self::getBasePath() . DIRECTORY_SEPARATOR . App::templatedir . DIRECTORY_SEPARATOR . $template.'.phtml');
$content = ob_get_clean();
return $content;
}
public static function _redirect($url, $die=true, $onlyJScript=false)
{
if (!headers_sent() && !$onlyJScript) {
ob_end_clean();
header("Location: ".$url);
}
if (!defined('C_SYSTEM_DEBUG'))
printf('<HTML><HEAD><META http-equiv="Refresh" content="0;url=%s"></HEAD><BODY onLoad="try {self.location.href=\'%s\' } catch(e) {}">
<A HREF="%s"> - </A></BODY></HTML>', $url, $url, $url);
if ($die) die();
}
public static function getMeta($options = array())
{
$metas = '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />'."\n";
$metas .= isset($options['title']) ? ' <title>'.$options['title'].'</title>' : ' <title>Agence référencement naturel Paris SEO Google</title>'; $metas .= "\n";
/*$metas .= isset($options['keywords']) ? ' <meta name="Keywords" content="'.$options['keywords'].'" />' : ' <meta name="Keywords" content="E-Commerce, site marchand, boutique en ligne, magento, prestashop, off-shore Roumanie, solutions IT, SSII franco-roumaine, entreprises IT, sous-traitance informatique" />'; $metas .= "\n";*/
$metas .= isset($options['description']) ? ' <meta name="Description" content="'.$options['description'].'" />' : ' <meta name="Description" content="Agence de référencement naturel Paris sur mesure. Meilleur expert solution SEO, Audit, optimisation netlinking, améliorez la visibilité de votre site sur google" />'; $metas .= "\n";
$metas .= ' <meta name="Language" content="fr" />'."\n";
$metas .= ' <meta name="robots" content ="all" />'."\n";
//$metas .= '<meta name="Keywords" content="E-Commerce, site marchand, boutique en ligne, magento, prestashop, off-shore Roumanie, solutions IT, SSII franco-roumaine, entreprises IT, sous-traitance informatique" />'."\n";
//$metas .= '<meta name="Description" content="Prestataire référencement naturel SEO sur mesure. Audit, optimisation, net linking, rédaction web : meilleure solution pour la visibilité de votre site sur Google" />'."\n";
return $metas;
}
}
/* End Framework */