From 2b2348847abb93542a9333b0c0d130612c44c51b Mon Sep 17 00:00:00 2001 From: BlackScorpion Date: Sat, 29 Jul 2017 21:45:22 -0300 Subject: [PATCH] Initial --- Admin.php | 118 +++++++++++ Ajax.php | 221 +++++++++++++++++++ Html/admin.html | 66 ++++++ Html/cover.html | 115 ++++++++++ Html/login.html | 47 ++++ Html/page_edit.html | 74 +++++++ Html/page_new.html | 74 +++++++ Html/perfil.html | 83 ++++++++ Html/rascunho.html | 16 ++ Html/template.html | 134 ++++++++++++ Model/Article.php | 435 ++++++++++++++++++++++++++++++++++++++ Model/Base.php | 418 ++++++++++++++++++++++++++++++++++++ Model/Reports/Report.php | 87 ++++++++ Model/Reports/Report1.php | 140 ++++++++++++ Model/Reports/Report2.php | 125 +++++++++++ Model/Reports/Report3.php | 116 ++++++++++ Model/Xlog.php | 84 ++++++++ Page.php | 400 +++++++++++++++++++++++++++++++++++ Xlog.php | 122 +++++++++++ composer.json | 24 +++ 20 files changed, 2899 insertions(+) create mode 100644 Admin.php create mode 100644 Ajax.php create mode 100644 Html/admin.html create mode 100644 Html/cover.html create mode 100644 Html/login.html create mode 100644 Html/page_edit.html create mode 100644 Html/page_new.html create mode 100644 Html/perfil.html create mode 100644 Html/rascunho.html create mode 100644 Html/template.html create mode 100644 Model/Article.php create mode 100644 Model/Base.php create mode 100644 Model/Reports/Report.php create mode 100644 Model/Reports/Report1.php create mode 100644 Model/Reports/Report2.php create mode 100644 Model/Reports/Report3.php create mode 100644 Model/Xlog.php create mode 100644 Page.php create mode 100644 Xlog.php create mode 100644 composer.json diff --git a/Admin.php b/Admin.php new file mode 100644 index 0000000..49281b1 --- /dev/null +++ b/Admin.php @@ -0,0 +1,118 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog; + +use Resource\Main; +use Lib; + +/** + * Admin Class + * + * @category Controller + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Admin extends Main +{ + public $scripts = []; + public $styles = []; + + public $patchHtml = __DIR__.'/Html/'; + + public $header = false; + public $footer = false; + + function __construct() + { + /* + * Your code here... + * + */ + } + + + function index() + { + //return $this->view(); + $data['breadcumb'] = 'Home'; + $data['titulo'] = 'Relatórios'; + $data['content'] = ''; + $this->sendPage('admin', $data); + } + + + function pagination($r, $param) + { + $par0 = isset($param[0]) ? $param[0] : null; + $par1 = isset($param[1]) ? $param[1] : null; + $par2 = isset($param[2]) ? $param[2] : null; + $par3 = isset($param[3]) ? $param[3] : null; + + switch ($par0) { + case '1': + $this->report1($par1, $par2); + break; + case '2': + $this->report2($par1, $par2); + break; + case '3': + $this->report3($par1, $par2); + break; + + default: + return $this->index(); + break; + } + } + + function report1($page = 1, $length = 10) + { + $model = new Model\Reports\Report1; + $data = $model->view($page, $length); + + $data['baseUrl'] = 'http://dbrasil.tk/admin/1/'; + $data['breadcumb'] = 'RelatóriosHome'; + + $this->sendPage('admin', $data); + } + + function report2($page = 1, $length = 10) + { + $model = new Model\Reports\Report2; + $data = $model->view($page, $length); + + $data['baseUrl'] = 'http://dbrasil.tk/admin/2/'; + $data['breadcumb'] = 'RelatóriosHome'; + + $this->sendPage('admin', $data); + } + + function report3($page = 1, $length = 10) + { + $model = new Model\Reports\Report3; + $data = $model->view($page, $length); + + $data['baseUrl'] = 'http://dbrasil.tk/admin/3/'; + $data['breadcumb'] = 'RelatóriosHome'; + + $this->sendPage('admin', $data); + } +} diff --git a/Ajax.php b/Ajax.php new file mode 100644 index 0000000..b2251d9 --- /dev/null +++ b/Ajax.php @@ -0,0 +1,221 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog; + +use Resource\Main; +use Lib; + +/** + * Ajax Class + * + * @category Controller + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Ajax extends Main +{ + + public $patchHtml = __DIR__.'/Html/'; + private $articlePatch = 'media/article/'; + private $articleId = 0; + + + /** + * Hook test + * @return string Data in POST + */ + function put() + { + \Lib\App::e($_POST); + } + + /** + * Savar article + * @return array|string return array with "status": "ok' OR "error" + */ + function save() + { + $dt = ''; + if (isset($_POST['dt'])) { + $dt = base64_decode($_POST['dt']); + $dt = utf8_encode($dt); + $dt = json_decode($dt); + } + + if (isset($dt->content)) { + $media = isset($dt->media) ? $dt->media : '{}'; + $category = isset($dt->category) ? $dt->category : 1; + $link = isset($dt->link) ? $dt->link : ''; + $tags = isset($dt->tags) ? $dt->tags : ''; + $status = isset($dt->status) ? $dt->status : 'R'; + + $title = isset($dt->title) ? $dt->title : 'Sem Título'; + $destaque = isset($dt->destaque) ? $dt->destaque : 'Nenhum destaque ...'; + + $uID = isset($dt->info->user) ? $dt->info->user : 0; + $aID = isset($dt->info->article) ? $dt->info->article : 0; + + $article = new Model\Article($aID); + + $article->set('author', $uID); + $article->set('category', $category); + $article->set('pubdate', date('Y-m-d H:i:s')); + $article->set('editdate', date('Y-m-d H:i:s')); + + $article->set('link', $link); + $article->set('tags', $tags); + $article->set('status', $status); + $article->set('media', json_encode($media)); + + $article->set('title', $title); + $article->set('content', str_replace(["--", "..."], ["—", "…"], $dt->content)); + $article->set('resume', $destaque); + + //Gravando... + $article->save(); + + //Send to client + $this->send(['status'=>'ok', 'id'=>$article->get('id'), 'link'=>$article->get('link')]); + } + $this->sendError(); + } + + + /** + * Check if "link" is "in use" + * @return void Send data to javascript (Json) + */ + function checkLink() + { + if (!isset($_POST['link'])) { + $this->sendError(); + } + + $link = strtolower(str_replace([" ",'"',"'",';','.',','], ["-",""], preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim($_POST['link']))))); + + $base = new Model\Base; + $status = $base->checkLink($link, $_POST['aID']) === false ? 'ok' : 'error'; + + $this->send(['status'=>$status,'link'=>$link]); + } + + /** + * Delete a article image (and thumbnail) + * @param string $r URL requested + * @param array $param article ID + * @return void void... + */ + function delete($r, $param) + { + $this->setUp($param); + + if (isset($_POST['file'])) { + $file = _WWW.$this->articlePatch.basename(rawurldecode($_POST['file'])); + $mini = _WWW.$this->articlePatch.'mini_'.basename(rawurldecode($_POST['file'])); + + if (file_exists($file)) { + unlink($file); + } + if (file_exists($mini)) { + unlink($mini); + } + } + } + + /** + * Upload image + * @param string $r URL requested + * @param array $param article ID + * @return void Send data to client + */ + function upload($r, $param) + { + $this->setUp($param); + + if (isset($_FILES['files']['error'][0]) + && $_FILES['files']['error'][0] == UPLOAD_ERR_OK) { + $name = basename($_FILES["files"]["name"][0]); + + $ext = explode('.', $name); + $ext = '.'.end($ext); + + $name = md5($name); + + $a['files'][0] = [ + 'name' => $name.$ext, + 'size' => $_FILES['files']['size'][0], + 'type' => $_FILES['files']['type'][0], + 'url' => _URL.$this->articlePatch.$name.$ext]; + + //Create a directory (if not exists) + Lib\Cli\Main::checkAndOrCreateDir(_WWW.$this->articlePatch, true); + + //Save uploaded file + move_uploaded_file($_FILES["files"]["tmp_name"][0], _WWW.$this->articlePatch.$name.$ext); + + //Resize image + $canvas = new Lib\Canvas(_WWW.$this->articlePatch.$name.$ext); + $canvas->set_quality(80) + ->resize('540') + ->save(_WWW.$this->articlePatch.$name.$ext); + //Thumbnail + $canvas->set_rgb('#000') + ->set_quality(70) + //->resize('265', '150', 'fill') + ->resize('120', '68', 'fill') + ->save(_WWW.$this->articlePatch.'mini_'.$name.$ext); + + //Send to javascript + $this->send($a); + } + + header('HTTP/1.1 403 Forbidden'); + exit(); + } + + +// ------------------------- Privates + + private function setUp($param) + { + if (!isset($param['id'])) { + $this->sendError(); + } + + $this->articleId = 0 + $param['id']; + $this->articlePatch = $this->articlePatch.$this->articleId.'/'; + } + + + /** + * Send encoded json data + * @return void Send data and stop PHP execution. + */ + static function send($data) + { + @ob_end_clean(); + ob_start('ob_gzhandler'); + header('Vary: Accept-Language, Accept-Encoding'); + header('Content-Type: application/json'); + exit(json_encode($data)); + } + + static function sendError($data = false) + { + self::send(array_merge(['status'=>'error'], $data)); + } +} diff --git a/Html/admin.html b/Html/admin.html new file mode 100644 index 0000000..a0ad03a --- /dev/null +++ b/Html/admin.html @@ -0,0 +1,66 @@ + + + + + + + + Admin - <x:titulo/> + + + + + +
+ + + +
+ + + \ No newline at end of file diff --git a/Html/cover.html b/Html/cover.html new file mode 100644 index 0000000..449cfc0 --- /dev/null +++ b/Html/cover.html @@ -0,0 +1,115 @@ + + + + + + + + + <x:blogName/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + +
+
+ + + +
+ + + + +
+
+
+ + +
+
+
+ + + + +
+ + +
+ + + + + + + + diff --git a/Html/login.html b/Html/login.html new file mode 100644 index 0000000..48e8ce2 --- /dev/null +++ b/Html/login.html @@ -0,0 +1,47 @@ + + + + + + + + + <x:blogName/> + + + + + + + + + + + + +
+ + + +
+ + + + \ No newline at end of file diff --git a/Html/page_edit.html b/Html/page_edit.html new file mode 100644 index 0000000..5336747 --- /dev/null +++ b/Html/page_edit.html @@ -0,0 +1,74 @@ + + + + + + + + + <x:articleTitle/> - <x:blogName/> + + + + + + + + + + + + +
+ + + + + + + + + +
+ + + \ No newline at end of file diff --git a/Html/page_new.html b/Html/page_new.html new file mode 100644 index 0000000..3fa7937 --- /dev/null +++ b/Html/page_new.html @@ -0,0 +1,74 @@ + + + + + + + + + <x:articleTitle/> - <x:blogName/> + + + + + + + + + + + + +
+ + + + + + + + + +
+ + + \ No newline at end of file diff --git a/Html/perfil.html b/Html/perfil.html new file mode 100644 index 0000000..c0a9853 --- /dev/null +++ b/Html/perfil.html @@ -0,0 +1,83 @@ + + + + + + + + + <x:blogName/> + + + + + + + + + + + +
+ + + + + +
+ + + \ No newline at end of file diff --git a/Html/rascunho.html b/Html/rascunho.html new file mode 100644 index 0000000..644a266 --- /dev/null +++ b/Html/rascunho.html @@ -0,0 +1,16 @@ + + + + + + + +
\ No newline at end of file diff --git a/Html/template.html b/Html/template.html new file mode 100644 index 0000000..cdd318b --- /dev/null +++ b/Html/template.html @@ -0,0 +1,134 @@ + + + + + + + + + <x:articleTitle/> - <x:blogName/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+ + + +
+ +
+
+
+ + +
+
+
+
+
+ + +
+ + + + + + + + + + diff --git a/Model/Article.php b/Model/Article.php new file mode 100644 index 0000000..fe9cb1f --- /dev/null +++ b/Model/Article.php @@ -0,0 +1,435 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model; + +use Lib; +use Lib\Db; + +/** + * Result Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Article +{ + private $table = 'article, articlecontent'; + private $where = 'article.id = articlecontent.article'; + private $patch = 'media/article/'; + + private $id = false; + private $category = 1; + private $status = 1; + private $author = 1; + private $rateup = 0; + private $ratedown = 0; + private $access = 0; + private $pubdate = ''; + private $editdate = ''; + private $link = 'titulo-da-publicaçao'; + private $tags = ''; + private $title = 'Titulo da Publicação'; + private $media = '"{}"'; + private $resume = 'Digite um texto para destaque e descrição resumida da publicação'; + private $content = 'Conteúdo da publicação...'; + + function __construct($data = null) + { + if ($data === null) { + return; + } + + if ($data === 0) { + $this->requestNew(); + } + + if (is_array($data)) { + $this->load($data); + } + if (is_numeric($data)) { + $this->mountById($data); + } + + if (is_string($data)) { + $this->mountByLink($data); + } + } + + /** + * Mount from DataBase - search by ID + * @param integer $id id in database + * @return bool|object $this object or false + */ + function mountById($id) + { + $db = new Db(); + + if ($this->where != false || $this->where != '') { + $where = ' AND '.$this->where; + } + + $res = $db->query('SELECT * FROM '.$this->table.' WHERE id = :id '.$where, [':id'=>0 + $id]); + + if (isset($res[0])) { + $this->load($res[0]->getAll()); + + //Access counter + $db->query('UPDATE article + SET access = access + 1 + WHERE id = '.$this->id); + return $this; + } + return false; + } + + + /** + * Mount from DataBase - search by LINK + * @param integer $link link in database + * @return bool|object $this object or false + */ + function mountByLink($link) + { + $db = new Db(); + + if ($this->where != false || $this->where != '') { + $where = ' and '.$this->where; + } + $res = $db->query('SELECT * FROM '.$this->table.' WHERE link = :link '.$where, [':link'=>$link]); + + if (isset($res[0])) { + $this->load($res[0]->getAll()); + + //Access counter + $db->query('UPDATE article + SET access = access + 1 + WHERE id = '.$this->id); + return $this; + } + + return false; + } + + + /** + * Get Row in DB + * + * @return bool|integer New ID or false + */ + function requestNew() + { + $db = new Db; + + //Search from first register with [article.status] 5 and [article.editdate] <= datetime - 24 hours. + $result = $db->query('SELECT MIN(id)id, (SELECT MAX(id+1) FROM article)nid + FROM article + WHERE status = 6 + OR (status = 5 AND editdate <= STR_TO_DATE(\''.date('Y-m-d H:i:s', time()-86400).'\', \'%Y-%m-%d %H:%i:%s\'))'); + + if (isset($result[0])) { + $this->editdate = date('Y-m-d H:i:s'); + $this->pubdate = $this->editdate; + + + //Criando novo registro + if ($result[0]->get('id') == null) { + $this->id = $result[0]->get('nid'); + + $db->query('INSERT INTO articlecontent + SET article = '.$this->id.', + content = "", + editdate = "'.$this->editdate.'"'); + + $db->query('INSERT INTO article + SET id = '.$this->id.', + status = 5, + editdate = \''.$this->editdate.'\''); + + //Atualizando o registro + } else { + $this->id = $result[0]->get('id'); + + $db->query('UPDATE article + SET status = 5, + pubdate = \''.$this->pubdate.'\', + editdate = \''.$this->editdate.'\', + rateup = 0, + ratedown = 0, + access = 0, + link = "", + tags = "", + title = "", + media = "{}", + resume = "" + + WHERE id = '.$this->id.''); + + $db->query('UPDATE articlecontent + SET content = "", + editdate = \''.$this->editdate.'\' + WHERE article = '.$this->id.''); + } + + //Make dir clean (delete all files) + $this->clearDir(); + return $this; + } + + return false; + } + + /** + * Get All data + * @return array array of fields name X data + */ + function getAll() + { + foreach ($this as $k => $v) { + if ($k == 'table' || $k == 'where') { + continue; + } + $data[$k] = $v; + } + return $data; + } + + /** + * Get one item + * @param string $item Item + * @return bool|string requaired item ou false + */ + function get($item) + { + if (isset($this->$item)) { + return $this->$item; + } + return false; + } + + /** + * Set one item + * @param string $item Item name + * @param string $value Value + * + * @return bool|object $this object or false + */ + function set($item, $value) + { + if (isset($this->$item)) { + $this->$item = $value; + return $this; + } + return false; + } + + + /** + * SAVE a new or UPDATE this + * @return bool status of success + */ + function save() + { + if ($this->id != false || $this->id != 0) { + return $this->update(); + } else { + return $this->insert(); + } + } + + /** + * DELETE this + * @return bool status of success + */ + function delete() + { + if ($this->id <= 0) { + return false; + } + + $db = new Db(); + $dlt = $db->query('DELETE FROM articlecontent WHERE article = :id', [':id'=>$this->id]); + $dlt = $db->query('DELETE FROM article WHERE id = :id', [':id'=>$this->id]); + + return $dlt; + } + + + // Privates --------------------------------------------- + + /** + * Delete all files in article directory + * @return void Clear directory + */ + function clearDir() + { + $dir = _WWW.$this->patch.$this->id.'/'; + foreach (scandir($dir) as $file) { + if ($file == '.' || $file == '..') { + continue; + } + unlink($dir.$file); + } + } + + + /** + * [load description] + * @param array $data [description] + * @return [type] [description] + */ + function load($data = []) + { + foreach ($this as $k => $v) { + if ($k == 'table' || $k == 'where') { + continue; + } + if (isset($data[$k])) { + $this->$k = $data[$k]; + } + } + } + + /** + * [update description] + * @return [type] [description] + */ + private function update() + { + $db = new Db(); + + //Insert into article table + $row = $db->query('UPDATE article + SET category = :category, + author = :author, + pubdate = :pubdate, + editdate = :editdate, + tags = :tags, + status = :status, + title = :title, + media = :media, + resume = :resume + WHERE id = :id', + + [':id'=>$this->id, + ':category' => $this->category, + ':author' => $this->author, + ':pubdate' => $this->pubdate, + ':editdate' => $this->editdate, + ':tags' => $this->tags, + ':status' => $this->status, + ':title' => $this->title, + ':media' => $this->media, + ':resume' => $this->resume + ]); + //check update + if (!$row) { + return false; + } + + //Insert into content table + $row = $db->query('UPDATE articlecontent + SET editdate = :editdate, + content = :content + WHERE article = :article', + + [':article' => $this->id, + ':editdate' => $this->editdate, + ':content' => $this->content]); + return $row; + + + $cols = ''; + $vals = []; + foreach ($this as $k => $v) { + if ($k == 'table' || $k == 'where') { + continue; + }echo '
'.$k.': '.$v; + if ($k !== 'id') { + $cols .= $k.' = :'.$k.','; + } + $vals[':'.$k] = $v; + } + + $cols = substr($cols, 0, -1); //tirando a ultima vírgula + + $where = ' WHERE id = :id '; + if ($this->where != null) { + $where .= ' and '.$this->where; + } + + $db = new Db(); + return $db->query('UPDATE '.$this->table.' SET '.$cols.$where, $vals); + } + + /** + * [insert description] + * @return [type] [description] + */ + private function insert() + { + $db = new Db(); + + //Pegando um ID válido + $id = $db->query('SELECT MAX(id)id FROM article'); + $this->id = $id[0]->get('id')+1; + + //Insert into content table + $row = $db->query('INSERT INTO articlecontent + SET article = :article, + editdate = :editdate, + content = :content', + [':article' => $this->id, + ':editdate' => $this->editdate, + ':content' => $this->content]); + + //check insert + if (!$row) { + //TODO: insert a ROWBACK if not inserted. + + return false; + } + + //Insert into article table + $row = $db->query('INSERT INTO article + SET id = :id, + category = :category, + author = :author, + pubdate = :pubdate, + editdate = :editdate, + link = :link, + tags = :tags, + status = :status, + title = :title, + media = :media, + resume = :resume ', + [':id'=>$this->id, + ':category' => $this->category, + ':author' => $this->author, + ':pubdate' => $this->pubdate, + ':editdate' => $this->editdate, + ':link' => $this->link, + ':tags' => $this->tags, + ':status' => $this->status, + ':title' => $this->title, + ':media' => $this->media, + ':resume' => $this->resume + ]); + + return $row; + } +} diff --git a/Model/Base.php b/Model/Base.php new file mode 100644 index 0000000..ab81d01 --- /dev/null +++ b/Model/Base.php @@ -0,0 +1,418 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model; + +use Lib; +use Lib\Db; + +/** + * Article Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Base +{ + private $db = false; + private $articleTable = 'article'; + private $contentTable = 'articlecontent'; + private $categoryTable = 'category'; + private $userTable = 'usuario'; + + private $data = ['id'=>false, + 'category' => false, + 'author' =>false, + 'pubdate' => false, + 'editdate' => false, + 'link' => false, + 'tags' => false, + 'status' => false, + 'title' => false, + 'media' => false, + 'mediacaption' => false, + 'resume' => false, + 'content' => false + ]; + + private $result = null; + + + function __construct($id = null) + { + $this->db = new Db(); + } + + + function getByLink($link) + { + $result = $this->db->query('SELECT * + FROM '.$this->articleTable.', '.$this->contentTable.' + WHERE link LIKE :link + AND article = id + LIMIT 1', [':link'=>"%$link%"]); + if (isset($result[0])) { + return new Article($result[0]->getAll()); + } + return false; + } + + /** + * Check link and if ID is diferent + * @param [type] $link [description] + * @param [type] $id [description] + * @return [type] [description] + */ + function checkLink($link, $id) + { + $result = $this->db->query('SELECT link + FROM '.$this->articleTable.' + WHERE link = :link + AND id != :id', + + [':link'=>$link, + ':id'=>0+$id]); + if (isset($result[0])) { + return $result[0]->get('link'); + } + + $this->db->query('UPDATE '.$this->articleTable.' + SET link = :link + WHERE id = :id', + + [':link'=>$link, + ':id'=>0+$id]); + return false; + } + + + /** + * Get categories + * @return array category data + */ + function getCategories() + { + $result = $this->db->query('SELECT * FROM category'); + + $data = []; + if (isset($result[0])) { + foreach ($result as $v) { + $data[$v->get('id')] = $v->get('name'); + } + } + return $data; + } + + /** + * Get Category by id + * @param integer $id Id for category + * @return bool|array Array of the name and description or false + */ + function getCategory($id) + { + $result = $this->db->query('SELECT * FROM category WHERE id = :id', [':id'=>(0+$id)]); + if (isset($result[0])) { + return ['name'=>$result[0]->get('name'), + 'description'=>$result[0]->get('description')]; + } + return false; + } + + + /** + * Get status + * @return array status data + */ + function getStatus() + { + $result = $this->db->query('SELECT * FROM status'); + + $data = []; + if (isset($result[0])) { + foreach ($result as $v) { + $data[$v->get('id')] = $v->get('name'); + } + } + return $data; + } + + + /** + * Create tables and insert user bases + * @return void void + */ + function create() + { + //Tablela ARTICLE + $this->db->query("CREATE TABLE `article` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `category` int(11) NOT NULL DEFAULT '1', + `status` int(11) NOT NULL, + `author` int(11) NOT NULL DEFAULT '1', + `rateup` int(11) NOT NULL DEFAULT '0', + `ratedown` int(11) NOT NULL DEFAULT '0', + `access` int(11) NOT NULL DEFAULT '0', + `pubdate` datetime DEFAULT NULL, + `editdate` datetime DEFAULT NULL, + `link` varchar(300) DEFAULT NULL, + `tags` varchar(300) DEFAULT NULL, + `title` varchar(300) DEFAULT NULL, + `media` text, + `resume` text, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + + //Tablela ARTICLECONTENT + $this->db->query("CREATE TABLE `articlecontent` ( + `article` int(10) unsigned NOT NULL, + `editdate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, + `content` longtext NOT NULL, + KEY `article` (`article`), + CONSTRAINT `articlecontent_ibfk_1` FOREIGN KEY (`article`) REFERENCES `article` (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + + //Tablela CATEGORY + $this->db->query("CREATE TABLE `category` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(200) NOT NULL, + `description` varchar(500) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=latin1"); + + //Tablela STATUS + $this->db->query("CREATE TABLE `status` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(200) NOT NULL, + `description` varchar(500) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=latin1"); + + //Tablela STATUS - INSERT + $this->db->query("INSERT INTO `status` (`id`, `name`, `description`) VALUES + (1, 'Publicar imediatamente', 'Artigo publicado imediatamente depois de criado/editado.'), + (2, 'Salvar como Rascunho', 'Mantém como um rascunho para futura edição (estacionado)'), + (3, 'Deletar ou Desabilitar', 'Sinaliza que o artigo está deletado, porém, se mantém salvo para futura auditoria. '), + (4, 'Acesso Restrito - logado', 'Permite acesso somente a leitores logados.'), + (5, 'Editando...', 'O registro fica reservado para edição por 24 horas.'), + (6, 'Livre para reúso', 'Registro usado anteriormente, porém, livre para reúso.')"); + + //Tablela USUARIO + $this->db->query("CREATE TABLE `usuario` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `login` varchar(255) DEFAULT NULL, + `senha` varchar(300) DEFAULT NULL, + `nome` varchar(255) DEFAULT NULL, + `token` varchar(200) DEFAULT NULL, + `vida` int(11) unsigned DEFAULT NULL, + `nivel` varchar(45) DEFAULT NULL COMMENT '[A]dmin, [E]ditor, [G]uest', + `status` char(1) DEFAULT NULL COMMENT '[A]ctive, [D]isable', + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + + //Tablela USUARIO - INSERT + $this->db->query("INSERT INTO `usuario` (`id`, `login`, `senha`, `nome`, `token`, `vida`, `nivel`, `status`) VALUES + (1, 'admin', 'admin#123', 'Administrator', 'DrFol:LeinC%[4CBVcT$hWGK~çjj', 908, 'E', 'A'), + (3, 'jessica', 'jessica#123', 'Jessica Mendes', '=+$Wr%yLEbxe7P11iWm1=d)Y@O%47Vow(2r{mv*u', 908, 'A', 'A'), + (5, 'guest', 'guest#123', 'Guest', 'IK:QernGB9azWQuh-A6BD', 0, 'G', 'A'), + (6, 'test', 'test#123', 'Disabled User', '![vw*$3lP_z!#IVfe.#n8NiTKBE8db->query("CREATE TABLE `usuariopar` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `usuario` int(11) NOT NULL, + `parametro` varchar(100) NOT NULL, + `valor` varchar(1000) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Lista de parâmetros extras para cada usuário (opcional e varia entre usuários)'"); + + //Tabela ACCESS + $this->db->query("CREATE TABLE `access` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `data` datetime NOT NULL, + `ip` varchar(100) NOT NULL, + `uri` varchar(300) NOT NULL, + `method` varchar(20) NOT NULL, + `agent` varchar(500) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8"); + } + + +// ------ oldies ¬ + + public function setTable($table) + { + $this->table = $table; + return $this; + } + + public function getResult() + { + return $this->result[0]; + } + + + public function setId($id) + { + return $this->data['id'] = 0 + $id; + } + + + public function getId() + { + return $this->data['id']; + } + + + public function getData() + { + return $this->data; + } + + + public function get($node) + { + return isset($this->data[$node]) ? $this->data[$node] : false; + } + + + + /** + * Private util function + * + * @param array $result Array of the Row object + * + * @return array result data + */ + private function comList($result) + { + foreach ($result as $res) { + $data[$res->get('id')]['title'] = $res->get('title'); + $data[$res->get('id')]['resume'] = $res->get('resume'); + $data[$res->get('id')]['author'] = $res->get('author'); + $data[$res->get('id')]['autor'] = $res->get('autor'); + $data[$res->get('id')]['category'] = $res->get('category'); + $data[$res->get('id')]['categoria'] = $res->get('categoria'); + $data[$res->get('id')]['link'] = $res->get('link'); + $data[$res->get('id')]['pubdate'] = $res->get('pubdate'); + //$data[$res->get('id')]['image'] = ['type'=>'picture', 'src'=>'/media/blog.png']; + + $media = json_decode($res->get('media')); + + foreach ($media as $img) { + if (isset($img->type) && $img->type == 'image') { + $data[$res->get('id')]['image'] = '/media/article/'.$res->get('id').'/mini_'.basename($img->src); + break; + } + + if (isset($img->type) && $img->type == 'video') { + $data[$res->get('id')]['image'] = '/media/v.png'; + } + } + } + + return $data; + } + + public function searchIn($field, $text) + { + //Check if is field of $this->data + if (!isset($this->data[$field])) { + return false; + } + + $result = $this->db->query('SELECT * + FROM '.$this->articleTable.', '.$this->contentTable.' + WHERE '.$field.' LIKE :tx + AND article = id', [':tx'=>"%$text%"]); + if (isset($result[0])) { + if (count($result) > 1) { + return $this->comList($result); + } else { + return $this->refresh($result[0]->getAll()); + } + } + return false; + } + + /** + * List ao article in this category + * + * @param integer $cat category id + * + * @return array|bool data result or false + */ + public function listByCategory($cat = null) + { + $result = $this->db->query('SELECT id, title, resume, category, author, link + FROM '.$this->articleTable.' + WHERE category = :cat', [':cat'=>$cat]); + if (isset($result[0])) { + return $this->comList($result); + } + return false; + } + + + /** + * [listNews description] + * @return [type] [description] + */ + public function listNews($noID = 0, $limit = 5, $category = 0, $search = '') + { + $category = 0 + $category; + $category = $category != 0 ? ' AND category='.$category : ''; + + $src = trim($search); + $search = $src != '' ? ' AND (title LIKE :src OR resume LIKE :src) ' : ' AND author != :src'; + + $result = $this->db->query('SELECT article.id as id, article.title as title, resume, category, category.name as categoria, usuario.nome as autor, author, article.link as link, pubdate, media + FROM '.$this->articleTable.','.$this->categoryTable.','.$this->userTable.' + WHERE article.id != :id + AND article.category = category.id + AND article.author = usuario.id + AND article.status = 1 + '.$category.' + '.$search.' + ORDER BY pubdate DESC + LIMIT '.$limit, + + [':id'=> 0 + $noID, ':src'=>"%$src%"]); + + if (isset($result[0])) { + return $this->comList($result); + } + return false; + } + + /** + * Refresh data + * + * @param array $res new data + * + * @return void none + */ + private function refresh($res) + { + foreach ($this->data as $k => $v) { + $this->data[$k] = isset($res[$k]) ? $res[$k] : false; + } + return $this->data; + } +} diff --git a/Model/Reports/Report.php b/Model/Reports/Report.php new file mode 100644 index 0000000..313b49e --- /dev/null +++ b/Model/Reports/Report.php @@ -0,0 +1,87 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model\Reports; + +use Lib; +use Lib\Db; + +/** + * Admin Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Report +{ + public $db = null; + + function __construct() + { + $this->db = new Db(); + } + + + final function calculate($page = 1, $length = 10, $query, $data) + { + $tmp = $this->db->query($query, $data); + + if (!$tmp) { + return false; + } + + //Calculando ... + $total = count($tmp); + $sm = $total/$length; + $int = intval($sm); + $pages = $int < $sm ? $int + 1 : $int; + + //Limitando se requerir uma página maior ou menor que o limite. + if ($page > $pages) { + $page = $pages; + } + if ($page < 1) { + $page = 1; + } + + //registro inicial da página + $init = ($page -1) * $length; + + return ['total'=>$total, + 'page'=>$page, + 'pages'=>$pages, + 'init'=>$init, + 'length'=>$length]; + } + + final function execute($data, $query, $dbdata = []) + { + $db = $this->db->query($query, $dbdata); + + if (!$db) { + return false; + } + + $rows = []; + foreach ($db as $row) { + $rows[] = $row->getAll(); + } + + $data['rows'] = $rows; + return $data; + } +} diff --git a/Model/Reports/Report1.php b/Model/Reports/Report1.php new file mode 100644 index 0000000..0931e3b --- /dev/null +++ b/Model/Reports/Report1.php @@ -0,0 +1,140 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model\Reports; + +use Lib; +use Lib\Db; + +/** + * Admin Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Report1 extends Report +{ + + function view($page = 1, $length = 10, $year = false, $month = false, $day = false) + { + $db = $this->getData($page, $length, $year, $month, $day); + + $data['titulo'] = 'Acesso diário agrupado pela URL de acesso'; + + if (!$db) { + $data['content'] = '

Nenhum resultado.

'; + return $this->sendPage('admin', $data); + } + + //mONTANDO ... + $o = ''; + + //Montando o resumo + $s = $db['total'] > 1 ? 's':'';//Plural ?? + + $sel = ''; + + $o .= "

Exibindo $sel de $db[total] registro$s por página.

"; + + //Montando paginação + $o .= '

Página '; + for ($i = 1; $i <= $db['pages']; $i++) { + $o .= ''; + } + $o .= '

'; + + //Montando a TABELA + $registros = 0; + $o .= ''; + + foreach ($db['rows'][0] as $key => $value) { + $o .= ""; + } + + $o .= ''; + + + foreach ($db['rows'] as $key => $row) { + $registros ++; + $o .= ''; + + foreach ($row as $k => $value) { + if ($k == 'data') { + $o .= ''; + } else { + $o .= ""; + } + } + $o .= ''; + } + + $o .= '
$key
'.date('d/m/Y', strtotime($value)).'$value
'; + + $data['content'] = $o; + + return $data; + } + + /** + * Quantidade de acesso ao HOME e ARTIGOS por dia do mês + * @return [type] [description] + */ + function getdata($page = 1, $length = 10, $ano = false, $mes = false, $dia = false) + { + + $dt = []; + $where = ''; + + if ($ano !== false) { + $where .= ' AND YEAR(data) = :ano '; + $dt[':ano'] = $ano; + } + + if ($mes !== false) { + $where .= ' AND MONTH(data) = :mes '; + $dt[':mes'] = $mes; + } + + if ($dia !== false) { + $where .= ' AND DAY(data) = :dia '; + $dt[':dia'] = $dia; + } + + //Calculando a página + $data = $this->calculate($page, $length, + 'SELECT id + FROM access + WHERE (uri LIKE "/a/%" + OR uri = "/") + '.$where.' + GROUP BY uri, MONTH(data), DAY(data)', $dt); + + return $this->execute($data, + 'SELECT data, COUNT(id)qt, uri AS Link + FROM access + WHERE (uri LIKE "/a/%" + OR uri = "/") + '.$where.' + GROUP BY uri, MONTH(data), DAY(data) + ORDER BY DAY(data), uri + LIMIT '.$data['init'].', '.$data['length'], $dt); + } +} diff --git a/Model/Reports/Report2.php b/Model/Reports/Report2.php new file mode 100644 index 0000000..88475c2 --- /dev/null +++ b/Model/Reports/Report2.php @@ -0,0 +1,125 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model\Reports; + +use Lib; +use Lib\Db; + +/** + * Admin Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Report2 extends Report +{ + function view($page = 1, $length = 10) + { + $db = $this->getData($page, $length); + + $data['titulo'] = 'Artigos mais acessados'; + + if (!$db) { + $data['content'] = '

Nenhum resultado.

'; + return $this->sendPage('admin', $data); + } + + //mONTANDO ... + $o = ''; + + //Montando o resumo + $s = $db['total'] > 1 ? 's':'';//Plural ?? + + $sel = ''; + + $o .= "

Exibindo $sel de $db[total] registro$s por página.

"; + + //Montando paginação + $o .= '

Página '; + for ($i = 1; $i <= $db['pages']; $i++) { + $o .= ''; + } + $o .= '

'; + + //Montando a TABELA + $registros = 0; + $o .= ''; + + foreach ($db['rows'][0] as $key => $value) { + $o .= ""; + } + + $o .= ''; + + + foreach ($db['rows'] as $key => $row) { + $registros ++; + $o .= ''; + + foreach ($row as $k => $value) { + if ($k == 'data') { + $o .= ''; + } else { + $o .= ""; + } + } + $o .= ''; + } + + $o .= '
$key
'.date('d/m/Y', strtotime($value)).'$value
'; + + $data['content'] = $o; + + return $data; + } + + + /** + * Quantidade de acesso ao HOME e ARTIGOS por dia do mês + * @return [type] [description] + */ + function getData($page = 1, $length = 10) + { + //Calculando a página + $data = $this->calculate($page, $length, + 'SELECT access.id + FROM access, article, usuario, category + WHERE uri LIKE "/a/%" + AND access.uri = CONCAT("/a/", article.link) + AND article.author = usuario.id + AND article.category = category.id + GROUP BY uri', []); + + return $this->execute($data, 'SELECT COUNT(access.id)Qt, article.title AS Titulo, usuario.nome AS Autor, category.name AS Categoria + FROM access, article, usuario, category + + WHERE uri LIKE "/a/%" + AND access.uri = CONCAT("/a/", article.link) + AND article.author = usuario.id + AND article.category = category.id + + GROUP BY uri + ORDER BY Qt DESC + + LIMIT '.$data['init'].','.$data['length']); + } +} diff --git a/Model/Reports/Report3.php b/Model/Reports/Report3.php new file mode 100644 index 0000000..647f0ae --- /dev/null +++ b/Model/Reports/Report3.php @@ -0,0 +1,116 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model\Reports; + +use Lib; +use Lib\Db; + +/** + * Admin Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Report3 extends Report +{ + function view($page = 1, $length = 10) + { + $db = $this->getData($page, $length); + + $data['titulo'] = 'Acesso de Robots (agrupado por Agent)'; + + if (!$db) { + $data['content'] = '

Nenhum resultado.

'; + return $this->sendPage('admin', $data); + } + + //mONTANDO ... + $o = ''; + + //Montando o resumo + $s = $db['total'] > 1 ? 's':'';//Plural ?? + + $sel = ''; + + $o .= "

Exibindo $sel de $db[total] registro$s por página.

"; + + //Montando paginação + $o .= '

Página '; + for ($i = 1; $i <= $db['pages']; $i++) { + $o .= ''; + } + $o .= '

'; + + //Montando a TABELA + $registros = 0; + $o .= ''; + + foreach ($db['rows'][0] as $key => $value) { + $o .= ""; + } + + $o .= ''; + + + foreach ($db['rows'] as $key => $row) { + $registros ++; + $o .= ''; + + foreach ($row as $k => $value) { + if ($k == 'data') { + $o .= ''; + } else { + $o .= ""; + } + } + $o .= ''; + } + + $o .= '
$key
'.date('d/m/Y', strtotime($value)).'$value
'; + + $data['content'] = $o; + + return $data; + } + + + /** + * Quantidade de acesso ao HOME e ARTIGOS por dia do mês + * @return [type] [description] + */ + function getData($page = 1, $length = 10) + { + //Calculando a página + $data = $this->calculate($page, $length, + 'SELECT id + From access + WHERE agent LIKE "%bot%" + GROUP BY agent', []); + + return $this->execute($data, 'SELECT COUNT(id)Qt, ip, uri, method, agent + From access + WHERE agent LIKE "%bot%" + GROUP BY agent + ORDER BY Qt DESC + LIMIT '.$data['init'].','.$data['length']); + } +} diff --git a/Model/Xlog.php b/Model/Xlog.php new file mode 100644 index 0000000..6a89690 --- /dev/null +++ b/Model/Xlog.php @@ -0,0 +1,84 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog\Model; + +use Lib; +use Lib\Db; + +/** + * Xlog Class + * + * @category Model + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Xlog +{ + private $db = false; + private $accessTable = 'access'; + private $result = null; + + function __construct() + { + $this->db = new Db(); + } + + + function setAccessData($data) + { + $set = ' SET '; + foreach ($data as $k => $v) { + $data[':'.$k] = $v; + $set .= " $k = :$k,"; + } + + //tirando a última vírgula... + $set = substr($set, 0, -1); + + //Escrevendo os dados no banco de dados + $this->db->query('INSERT INTO '.$this->accessTable.' '.$set, $data); + } + + function decodeAgent() + { + + $result = $this->db->query('SHOW TABLE STATUS FROM devbr_site'); + \Lib\App::e($result); + + + $result = $this->db->query('SELECT id,agent FROM '.$this->accessTable.' WHERE id > 6693'); + + if (isset($result[0])) { + $totalId = count($result); + + echo "\nEncontrados $totalId registros."; + + foreach ($result as $key => $value) { + $dec = json_encode(get_browser($value->get('agent'))); + + $this->db->query('UPDATE '.$this->accessTable.' SET decdata=:dec WHERE id=:id', + [':dec'=>$dec, + ':id'=>$value->get('id')] + ); + + echo "\nId: ".$value->get('id')." de $totalId"; + } + } + + exit("\n\nFinished!\n\n"); + } +} diff --git a/Page.php b/Page.php new file mode 100644 index 0000000..26861bf --- /dev/null +++ b/Page.php @@ -0,0 +1,400 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog; + +use Resource\Main; +use Lib; + +/** + * Page Class + * + * @category Controller + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Page extends Main +{ + + public $scripts = ['1']; + public $styles = []; + + public $patchHtml = __DIR__.'/Html/'; + + public $blogName = 'DBrasil'; + public $blogDescription = 'O jeito brasileiro de ver o mundo.'; + public $blogLink = _URL; + public $blogArticleLink = _URL.'a/'; + public $blogMedia = _URL.'media/cover/destaque.jpg'; + + public $header = false; + public $footer = false; + + + function index($rqst, $param) + { + //Data to template + $data = [ 'blogName' => $this->blogName, + 'blogDescription' => $this->blogDescription, + 'blogLink' => $this->blogLink, + 'blogMedia' => $this->blogMedia + ]; + //USER + $user = Lib\User::this(); + $base = new Model\Base(); + + $category = isset($_GET['category']) ? 0 + $_GET['category'] : 0; + $search = isset($_GET['search']) ? $_GET['search'] : ''; + + $data['destaques'] = ''; + foreach ($base->listNews(0, 20, $category, $search) as $id => $row) { + $data['destaques'] .= '
'. + (isset($row['image']) ? '' : ''). + ''.strtoupper($row['categoria'].': '.$row['autor']).' - '.date('d/m H:i', strtotime($row['pubdate'])).''. + '

'.$row['title'].'

'. + ''.$row['resume'].'
'; + } + + if ($data['destaques'] == '') { + $data['destaques'] = '

Nenhuma publicação encontrada.

'; + } + + //Categories + $data['categories']['data'][0] = 'Tudo...'; + foreach ($base->getCategories() as $key => $value) { + $data['categories']['data'][$key] = $value; + } + $data['categories']['default'] = $category; + + $data['search'] = $search; + + $this->sendPage('cover', $data); + } + + + /** + * View article page + * + * @param string $rqst [description] + * @param array $param [description] + * + * @return void [description] + */ + function view($rqst, $param) + { + if ($param['id'] === '0') { + Lib\App::go($this->blogLink); + } + + $base = new Model\Base(); + $article = new Model\Article($param['id']); + + if ($article->get('id') === false || $article->get('status') != 1) { + Lib\App::go($this->blogLink); + } + + //Geting the first image in field "media" in database + $media = json_decode($article->get('media')); + $articleMedia = (isset($media[0]->src)) ? $media[0]->src : $this->blogMedia; + + //USER + $user = Lib\User::this(); + $user->getById($article->get('author')); + + //Data to template + $data = [ 'blogName' => $this->blogName, + 'blogDescription' => $article->get('resume').' - '.$this->blogDescription, + 'blogLink' => $this->blogLink, + 'blogMedia' => $this->blogMedia, + + 'authorName' => $user->get('name'), + 'authorFoto' => _URL.'media/user/'.$user->get('id').'/1.jpg', + 'authorLink' => _URL.'perfil', //'user/'.$user->get('login'), + 'authorPubData' => date("d/m/Y à\s H:i", strtotime($article->get('pubdate'))), + + 'articleTitle' => $article->get('title'), + 'articleResume' => $article->get('resume'), + 'articleContent' => $article->get('content'), + 'articleMedia' => $articleMedia, + 'articleLink' => $this->blogArticleLink.$article->get('link'), + 'articleViews' => number_format($article->get('access'), 0, ',', '.'), + 'articleTags' => $article->get('tags'), + 'articleCategory' => $base->getCategory($article->get('category'))['name'], + 'articleDateTime' => date('c', strtotime($article->get('pubdate'))), + 'articleEditLink' => $this->blogLink.'e/'.$article->get('link') + ]; + + //Categories + $data['categories']['data'][0] = 'Tudo...'; + foreach ($base->getCategories() as $key => $value) { + $data['categories']['data'][$key] = $value; + } + + //Lib\App::e($data); + $this->sendPage('template', $data, ['aID'=>$article->get('id'), + 'uID'=>$user->get('id')]); + } + + + function edit($rqst, $param) + { + //Impedindo que se acesse sem LOGIN... + Lib\App::go('login'); + + //Checando se a rota está correta + if (!isset($param['id'])) { + Lib\App::go($this->blogLink); + } + + //USER + $user = Lib\User::this(); + + //$user->getMe(); + $user->getById(7); + $aID = $param['id'] == 'new' + || (is_numeric($param['id']) + && $param['id'] == 0) + ? 0 + : $param['id']; + + $page = $aID == 0 ? 'new' : 'edit'; + + $article = new Model\Article($aID); + $base = new Model\Base; + + $aID = $article->get('id') + 0; + + //Se não existir, cria um novo artigo. + $data['blogName'] = $this->blogName; + $data['authorName'] = $user->get('name'); + $data['authorFoto'] = _URL.'media/user/'.$user->get('id').'/1.jpg'; + $data['authorLink'] = _URL.'perfil'; //'user/'.$user->get('login'); + $data['authorPubData'] = date("d/m/Y à\s H:i", strtotime($article->get('pubdate'))); + $data['articleTitle'] = $article->get('title'); + $data['articleResume'] = $article->get('resume'); + $data['articleContent'] = $article->get('content'); + $data['articleLink'] = $article->get('link'); + $data['articleViewLink'] = $this->blogArticleLink.$article->get('link'); + + //Select CATEGORIES + $data['categoria']['data'] = $base->getCategories(); + $data['categoria']['default'] = $article->get('category'); + + //Select STATUS + $data['status']['data'] = $base->getStatus(); + $data['status']['default'] = $article->get('status'); + + //Tags + $data['articleTags'] = $article->get('tags'); + + //$this->styles = ['source/font-awesome.min']; + $this->scripts = ['2']; + + //Send page to user + $this->sendPage('page_'.$page, $data, ['aType'=>$page, 'aID'=>$aID, 'uID'=>$user->get('id'), 'pageLink'=>$article->get('link')]); + } + + + function login() + { + //exit('
'.print_r($_SERVER, true));
+        //$this->styles = ['source/skell', 'source/login', 'source/login_doc'];
+        $this->scripts = ['3'];
+
+        $key = str_replace(
+            array("\r","\n","-----BEGIN PUBLIC KEY-----","-----END PUBLIC KEY-----"), '',
+                            file_get_contents(_CONFIG.'Key/public.key'));
+
+        $this->sendPage('login', [], ['KEY'=>$key]);
+    }
+
+
+    function perfil()
+    {
+        //exit('
'.print_r($_SERVER, true));
+        //$this->styles = ['source/skell', 'source/login', 'source/login_doc'];
+        $this->scripts = ['3'];
+
+        $this->sendPage('perfil');
+    }
+
+
+
+    //TEMP - de le te me
+    
+    function tmp()
+    {
+        //$xlog = new Model\Xlog;
+
+        //$xlog->decodeAgent();
+
+        //Fazendo login
+        //Lib\User::this()->login('admin', 'admin#123');
+        //Lib\User::this()->setCriptoCookie();
+
+        //Lib\User::this()->unsetCriptoCookie();
+        $user = new Lib\User();
+
+        $user->login('jessica', 'jessica#123');
+
+        //$user->unsetCriptoCookie();
+        //
+        //
+        Lib\App::p($user->get(), true);
+        Lib\App::p(Lib\User::this()->get(), true);
+        Lib\App::p($_SERVER['REMOTE_ADDR'], true);
+        Lib\App::p($_SERVER['HTTP_USER_AGENT'], true);
+        Lib\App::p($_SERVER['HTTP_ACCEPT_LANGUAGE'], true);
+
+        echo "
OS: ".$this->operating_system_detection(); + + echo '
'; + + $jsonBrowser = json_encode(get_browser()); + + echo '
Tamanho do arquivo: '.strlen($jsonBrowser).'
'; + Lib\App::p(json_decode($jsonBrowser), true); + + + //Fazendo login + //Lib\User::this()->login('jessica', 'jessica#123'); + //Lib\User::this()->setCriptoCookie(); + + //Lib\App::p(Lib\User::this()->get(), true); + + echo "
Finished!"; + } + + + + /* return Operating System */ + function operating_system_detection() + { + if (isset( $_SERVER )) { + $agent = $_SERVER['HTTP_USER_AGENT'] ; + } else { + global $HTTP_SERVER_VARS ; + if (isset( $HTTP_SERVER_VARS )) { + $agent = $HTTP_SERVER_VARS['HTTP_USER_AGENT'] ; + } else { + global $HTTP_USER_AGENT ; + $agent = $HTTP_USER_AGENT ; + } + } + $ros[] = array('Windows XP', 'Windows XP'); + $ros[] = array('Windows NT 5.1|Windows NT5.1)', 'Windows XP'); + $ros[] = array('Windows 2000', 'Windows 2000'); + $ros[] = array('Windows NT 5.0', 'Windows 2000'); + $ros[] = array('Windows NT 4.0|WinNT4.0', 'Windows NT'); + $ros[] = array('Windows NT 5.2', 'Windows Server 2003'); + $ros[] = array('Windows NT 6.0', 'Windows Vista'); + $ros[] = array('Windows NT 7.0', 'Windows 7'); + $ros[] = array('Windows NT 10.0', 'Windows 10'); + $ros[] = array('Windows CE', 'Windows CE'); + $ros[] = array('(media center pc).([0-9]{1,2}\.[0-9]{1,2})', 'Windows Media Center'); + $ros[] = array('(win)([0-9]{1,2}\.[0-9x]{1,2})', 'Windows'); + $ros[] = array('(win)([0-9]{2})', 'Windows'); + $ros[] = array('(windows)([0-9x]{2})', 'Windows'); + // Doesn't seem like these are necessary...not totally sure though.. + //$ros[] = array('(winnt)([0-9]{1,2}\.[0-9]{1,2}){0,1}', 'Windows NT'); + //$ros[] = array('(windows nt)(([0-9]{1,2}\.[0-9]{1,2}){0,1})', 'Windows NT'); // fix by bg + $ros[] = array('Windows ME', 'Windows ME'); + $ros[] = array('Win 9x 4.90', 'Windows ME'); + $ros[] = array('Windows 98|Win98', 'Windows 98'); + $ros[] = array('Windows 95', 'Windows 95'); + $ros[] = array('(windows)([0-9]{1,2}\.[0-9]{1,2})', 'Windows'); + $ros[] = array('win32', 'Windows'); + $ros[] = array('(java)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})', 'Java'); + $ros[] = array('(Solaris)([0-9]{1,2}\.[0-9x]{1,2}){0,1}', 'Solaris'); + $ros[] = array('dos x86', 'DOS'); + $ros[] = array('unix', 'Unix'); + $ros[] = array('Mac OS X', 'Mac OS X'); + $ros[] = array('Mac_PowerPC', 'Macintosh PowerPC'); + $ros[] = array('(mac|Macintosh)', 'Mac OS'); + $ros[] = array('(sunos)([0-9]{1,2}\.[0-9]{1,2}){0,1}', 'SunOS'); + $ros[] = array('(beos)([0-9]{1,2}\.[0-9]{1,2}){0,1}', 'BeOS'); + $ros[] = array('(risc os)([0-9]{1,2}\.[0-9]{1,2})', 'RISC OS'); + $ros[] = array('os/2', 'OS/2'); + $ros[] = array('freebsd', 'FreeBSD'); + $ros[] = array('openbsd', 'OpenBSD'); + $ros[] = array('netbsd', 'NetBSD'); + $ros[] = array('irix', 'IRIX'); + $ros[] = array('plan9', 'Plan9'); + $ros[] = array('osf', 'OSF'); + $ros[] = array('aix', 'AIX'); + $ros[] = array('GNU Hurd', 'GNU Hurd'); + $ros[] = array('(fedora)', 'Linux - Fedora'); + $ros[] = array('(kubuntu)', 'Linux - Kubuntu'); + $ros[] = array('(ubuntu)', 'Linux - Ubuntu'); + $ros[] = array('(debian)', 'Linux - Debian'); + $ros[] = array('(CentOS)', 'Linux - CentOS'); + $ros[] = array('(Mandriva).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)', 'Linux - Mandriva'); + $ros[] = array('(SUSE).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)', 'Linux - SUSE'); + $ros[] = array('(Dropline)', 'Linux - Slackware (Dropline GNOME)'); + $ros[] = array('(ASPLinux)', 'Linux - ASPLinux'); + $ros[] = array('(Red Hat)', 'Linux - Red Hat'); + // Loads of Linux machines will be detected as unix. + // Actually, all of the linux machines I've checked have the 'X11' in the User Agent. + //$ros[] = array('X11', 'Unix'); + $ros[] = array('(linux)', 'Linux'); + $ros[] = array('(amigaos)([0-9]{1,2}\.[0-9]{1,2})', 'AmigaOS'); + $ros[] = array('amiga-aweb', 'AmigaOS'); + $ros[] = array('amiga', 'Amiga'); + $ros[] = array('AvantGo', 'PalmOS'); + //$ros[] = array('(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1}-([0-9]{1,2}) i([0-9]{1})86){1}', 'Linux'); + //$ros[] = array('(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1} i([0-9]{1}86)){1}', 'Linux'); + //$ros[] = array('(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1})', 'Linux'); + $ros[] = array('[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3})', 'Linux'); + $ros[] = array('(webtv)/([0-9]{1,2}\.[0-9]{1,2})', 'WebTV'); + $ros[] = array('Dreamcast', 'Dreamcast OS'); + $ros[] = array('GetRight', 'Windows'); + $ros[] = array('go!zilla', 'Windows'); + $ros[] = array('gozilla', 'Windows'); + $ros[] = array('gulliver', 'Windows'); + $ros[] = array('ia archiver', 'Windows'); + $ros[] = array('NetPositive', 'Windows'); + $ros[] = array('mass downloader', 'Windows'); + $ros[] = array('microsoft', 'Windows'); + $ros[] = array('offline explorer', 'Windows'); + $ros[] = array('teleport', 'Windows'); + $ros[] = array('web downloader', 'Windows'); + $ros[] = array('webcapture', 'Windows'); + $ros[] = array('webcollage', 'Windows'); + $ros[] = array('webcopier', 'Windows'); + $ros[] = array('webstripper', 'Windows'); + $ros[] = array('webzip', 'Windows'); + $ros[] = array('wget', 'Windows'); + $ros[] = array('Java', 'Unknown'); + $ros[] = array('flashget', 'Windows'); + // delete next line if the script show not the right OS + //$ros[] = array('(PHP)/([0-9]{1,2}.[0-9]{1,2})', 'PHP'); + $ros[] = array('MS FrontPage', 'Windows'); + $ros[] = array('(msproxy)/([0-9]{1,2}.[0-9]{1,2})', 'Windows'); + $ros[] = array('(msie)([0-9]{1,2}.[0-9]{1,2})', 'Windows'); + $ros[] = array('libwww-perl', 'Unix'); + $ros[] = array('UP.Browser', 'Windows CE'); + $ros[] = array('NetAnts', 'Windows'); + $file = count ( $ros ); + $os = ''; + for ($n=0; $n<$file; $n++) { + if (preg_match('/'.$ros[$n][0].'/i', $agent, $name)) { + $os = @$ros[$n][1].' '.@$name[2]; + break; + } + } + return trim ( $os ); + } +} diff --git a/Xlog.php b/Xlog.php new file mode 100644 index 0000000..4f291b5 --- /dev/null +++ b/Xlog.php @@ -0,0 +1,122 @@ + + * @copyright 2016 Bill Rocha + * @license MIT + * @version GIT: 0.0.1 + * @link http://paulorocha.tk/devbr + */ + +namespace Blog; + +use Resource\Main; +use Lib\Aes; +use Lib\User; +use Blog\Ajax; + +/** + * Xlog Class + * + * @category Controller + * @package Library + * @author Bill Rocha + * @license MIT + * @link http://paulorocha.tk/devbr + */ +class Xlog extends Main +{ + + function __construct() + { + #code here... + } + + function key() + { + $key = str_replace( + array("\r","\n","-----BEGIN PUBLIC KEY-----","-----END PUBLIC KEY-----"), '', + file_get_contents(_CONFIG.'Key/public.key')); + Ajax::send(['key'=>$key]); + } + + + //Pega os dados do usuário por ajax encriptado com RSA + //Retorna o0s dados encriptados por AES com o Token como Sincrono Key + function signUp() + { + if (isset($_POST['data']) + && trim($_POST['data']) !== '') { + //Decodificando RSA + $private = file_get_contents(_CONFIG.'Key/private.key'); + $key = json_decode($_POST['data']); + $key = base64_decode($key->enc); + + if (!openssl_private_decrypt($key, + $key, + openssl_pkey_get_private($private) + )) { + Ajax::send(['error'=>'Confira seu Login ou Senha!']); //exit($key); + } + + $key = json_decode($key); + + //inicializando o usuário => User Singleton Object + $user = User::this(); + $user->login($key->login, $key->passw); + + + //Verificando se o login foi bem sucedido + if ($user->get('login')) { + //Gravando o novo Token no BD + $user->saveToken($key->token); + $userdata = json_encode(['name'=>$user->get('name'), + 'id'=>$user->get('id'), + 'level'=>$user->get('level')]); + + $resumo = (new Model\Xlog)->resumo($user->get('id')); + + //Encriptando o token + Aes::size(256); + $key = Aes::enc(json_encode( + ['user'=>$userdata, + 'token'=>$key->token, + 'resumo'=>$resumo]), + $key->token); + + //Retorna os dados do usuário + Ajax::send(['error'=>false, 'key'=>$key]); + } + } + //Em casos contrários, retorna erro. + Ajax::send(['error'=>'Confira seu Login ou Senha!']); + } + + + function logout() + { + //Procede o LOGOUT + User::this()->logout($this->params[0]); + Ajax::send(['error'=>false,'logout'=>'Você está desconectado!']); + } + + + /** + * Escrevendo dados de acesso no banco de dados + * @return void Não retorna + */ + function access() + { + $data['agent'] = $_SERVER['HTTP_USER_AGENT']; + $data['ip'] = $_SERVER['REMOTE_ADDR']; + $data['method'] = $_SERVER['REQUEST_METHOD']; + $data['uri'] = $_SERVER['REQUEST_URI']; + $data['data'] = date('Y-m-d H:i:s'); + + (new Model\Xlog)->setAccessData($data); + } +} diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..74e1b55 --- /dev/null +++ b/composer.json @@ -0,0 +1,24 @@ +{ + "name": "devbr/pack-blog", + "description": "Blog implementation package", + "keywords": ["blog", "pack", "wscore"], + "license": "MIT", + "type": "devbr-pack", + "homepage": "http://dbrasil.tk/devbr/", + "authors": [{ + "name": "Bill Rocha", + "email": "prbr@ymail.com" + }], + "config": { + "preferred-install": "dist" + }, + "require": { + "php": ">=5.6", + "devbr/install-plugin":"*" + }, + "autoload": { + "psr-4": { + "Blog\\": "" + } + } +}