From fb96e02c84523ae08f20e095ae41ac2c3f365c3e Mon Sep 17 00:00:00 2001 From: Vignesh Date: Tue, 13 Jan 2015 23:56:53 +0530 Subject: [PATCH] created pdo.class.php and used in some lib files --- cms/actionbar.lib.php | 23 +++---- cms/authenticate.lib.php | 12 ++-- cms/breadcrumbs.lib.php | 5 +- cms/download.lib.php | 6 +- cms/iconmanagement.lib.php | 4 +- cms/modules/article.lib.php | 90 ++++++++++++++------------- cms/pdo.class.php | 119 ++++++++++++++++++++++++++++++++++++ index.php | 3 +- 8 files changed, 195 insertions(+), 67 deletions(-) create mode 100755 cms/pdo.class.php diff --git a/cms/actionbar.lib.php b/cms/actionbar.lib.php index 87a62da6..5fa8df5e 100755 --- a/cms/actionbar.lib.php +++ b/cms/actionbar.lib.php @@ -24,19 +24,19 @@ * @return $actionbar The list of permitted actions for the 'user' of 'page'. */ function getActionbarPage($userId, $pageId) { - + global $pdb; $action_query = "SELECT perm_id, perm_action, perm_text FROM `".MYSQL_DATABASE_PREFIX."permissionlist` WHERE page_module = 'page'"; - $action_result = mysql_query($action_query); + $action_result = $pdb->query($action_query); $allow_login_query = "SELECT `value` FROM `".MYSQL_DATABASE_PREFIX."global` WHERE `attribute` = 'allow_login'"; - $allow_login_result = mysql_query($allow_login_query); - $allow_login_result = mysql_fetch_array($allow_login_result); + $allow_login_result = $pdb->query($allow_login_query); + $allow_login_result = $allow_login_result[0]; $actionbarPage=array(); - while($action_row = mysql_fetch_assoc($action_result)) { + foreach($action_result as $action_row) { if(getPermissions($userId, $pageId, $action_row['perm_action'])) $actionbarPage[$action_row['perm_action']]=$action_row['perm_text']; } if($userId==0) { - if($allow_login_result[0]) { + if($allow_login_result['value']) { $actionbarPage["login"]="Login"; $actionbarPage["login&subaction=register"]="Register"; } @@ -75,19 +75,20 @@ function getActionbarPage($userId, $pageId) { * @return $actionbar The list of permitted module specific actions for the 'user' of 'page'. */ function getActionbarModule($userId, $pageId) { + global $pdb; $action_query = "SELECT perm_id, perm_action, perm_text FROM `".MYSQL_DATABASE_PREFIX."permissionlist` WHERE perm_action != 'create' AND page_module = '".getEffectivePageModule($pageId)."'"; - $action_result = mysql_query($action_query); + $action_result = $pdb->query($action_query); $allow_login_query = "SELECT `value` FROM `".MYSQL_DATABASE_PREFIX."global` WHERE `attribute` = 'allow_login'"; - $allow_login_result = mysql_query($allow_login_query); - $allow_login_result = mysql_fetch_array($allow_login_result); + $allow_login_result = $pdb->query($allow_login_query); + $allow_login_result = $allow_login_result[0]; $actionbarPage = array(); - while($action_row = mysql_fetch_assoc($action_result)) + foreach($action_result as $action_row) if(getPermissions($userId, $pageId, $action_row['perm_action'])) $actionbarPage[$action_row['perm_action']]=$action_row['perm_text']; $actionbar="
"; if(is_array($actionbarPage)>0) foreach($actionbarPage as $action=>$actionname) { - if((!$allow_login_result[0])&&($actionname=="View")&&!($userId)) + if((!$allow_login_result['value'])&&($actionname=="View")&&!($userId)) continue; $actionbar.="$actionname\n"; } diff --git a/cms/authenticate.lib.php b/cms/authenticate.lib.php index dfef8ce4..3da273d2 100755 --- a/cms/authenticate.lib.php +++ b/cms/authenticate.lib.php @@ -24,10 +24,11 @@ * */ function getSessionData($user_id) { + global $pdb; $user_id=escape($user_id); $query = "SELECT `user_name`,`user_email`,`user_lastlogin` FROM `" . MYSQL_DATABASE_PREFIX . "users` WHERE `user_id`='$user_id'"; - $data = mysql_query($query) or die(mysql_error()); - $temp = mysql_fetch_assoc($data); + $data = $pdb->query($query); + $temp = $data[0]; $user_name = $temp['user_name']; $user_email = $temp['user_email']; $lastlogin = $temp['user_lastlogin']; @@ -129,6 +130,7 @@ function firstTimeGetUserId() { * */ function getGroupIds($userId) { + global $pdb; $groups = array ( 0 ); @@ -137,9 +139,9 @@ function getGroupIds($userId) { else $groups[] = 1; $groupQuery = 'SELECT `group_id` FROM `' . MYSQL_DATABASE_PREFIX . 'usergroup` WHERE `user_id` = \'' . escape($userId)."'"; - $groupQueryResult = mysql_query($groupQuery) or die(mysql_error()); - while ($groupQueryResultRow = mysql_fetch_row($groupQueryResult)) - $groups[] = $groupQueryResultRow[0]; + $groupQueryResult = $pdb->query($groupQuery); + foreach($groupQueryResult as $groupQueryResultRow) + $groups[] = $groupQueryResultRow['group_id']; return $groups; } diff --git a/cms/breadcrumbs.lib.php b/cms/breadcrumbs.lib.php index c351613c..34e375fc 100755 --- a/cms/breadcrumbs.lib.php +++ b/cms/breadcrumbs.lib.php @@ -25,12 +25,13 @@ * @return HTML string representing the breadcrumbs to be displayed for the given page */ function breadcrumbs($pageIdArray) { + global $pdb; $sqlOutputArray = array(); $pageIdList = join($pageIdArray, ","); $query = 'SELECT `page_id`, `page_name`, `page_title` FROM `' . MYSQL_DATABASE_PREFIX . 'pages` WHERE `page_id` IN (' . $pageIdList . ')'; - $resultId = mysql_query($query); - while ($row = mysql_fetch_assoc($resultId)) + $rows=$pdb->query($query); + foreach ($rows as $row) $sqlOutputArray[$row['page_id']] = array($row['page_name'], $row['page_title']); global $urlRequestRoot; diff --git a/cms/download.lib.php b/cms/download.lib.php index c244e0c3..332d4db8 100755 --- a/cms/download.lib.php +++ b/cms/download.lib.php @@ -25,7 +25,7 @@ */ function download($pageId, $userId, $fileName,$action="") { - + global $pdb; /// If page not found display error if($pageId===false) { header("http/1.0 404 Not Found" ); @@ -75,8 +75,8 @@ function download($pageId, $userId, $fileName,$action="") { //return the file the particular page id. $query = "SELECT * FROM `" . MYSQL_DATABASE_PREFIX . "uploads` WHERE `upload_filename`= '". escape($fileName). "' AND `page_module` = '".escape($moduleType)."' AND `page_modulecomponentid` = '".escape($moduleComponentId)."'"; - $result = mysql_query($query) or die(mysql_error() . "upload L:85"); - $row = mysql_fetch_assoc($result); + $rows = $pdb->query($query); + $row = $rows[0]; $fileType = $row['upload_filetype']; /** diff --git a/cms/iconmanagement.lib.php b/cms/iconmanagement.lib.php index 57ea7291..4f1d5b60 100755 --- a/cms/iconmanagement.lib.php +++ b/cms/iconmanagement.lib.php @@ -22,7 +22,7 @@ * @return HTML of the FORM */ function handleIconManagement() { - + global $pdb; /* * Upload a new icon */ @@ -63,7 +63,7 @@ function handleIconManagement() { * Save the Icon in Database - The following entries are saved * icon URL - path relative to the website installation folder on the server */ - mysql_query("UPDATE `".MYSQL_DATABASE_PREFIX."pages` SET `page_image`='$iconURL' WHERE `page_id`='$target'"); + $pdb->query("UPDATE `".MYSQL_DATABASE_PREFIX."pages` SET `page_image`='$iconURL' WHERE `page_id`='$target'"); $pageDetails = getPageInfo($target); if($pageDetails['page_image'] != NULL) echo " "; diff --git a/cms/modules/article.lib.php b/cms/modules/article.lib.php index e4f993ad..890506eb 100755 --- a/cms/modules/article.lib.php +++ b/cms/modules/article.lib.php @@ -42,12 +42,14 @@ public static function getUploadableFileProperties(&$fileTypesArray,&$maxFileSiz } function isCommentsEnabled() { - $result = mysql_fetch_array(mysql_query("SELECT `allowComments` FROM `article_content` WHERE `page_modulecomponentid` = '{$this->moduleComponentId}'")); - return $result['allowComments']; + global $pdb; + $result = $pdb->query("SELECT `allowComments` FROM `article_content` WHERE `page_modulecomponentid` = '{$this->moduleComponentId}'"); + return $result[0]['allowComments']; } function setCommentEnable($val) { - mysql_query("UPDATE `article_content` SET `allowComments` ='$val' WHERE `page_modulecomponentid` = '{$this->moduleComponentId}'"); + global $pdb; + $result = $pdb->query("UPDATE `article_content` SET `allowComments` ='$val' WHERE `page_modulecomponentid` = '{$this->moduleComponentId}'"); } function renderComment($id,$user,$timestamp,$comment,$delete=0) { @@ -93,40 +95,41 @@ function commentBox() { public function actionView($text="") { + global $pdb; if (isset($_GET['draft']) && isset ($_POST['CKEditor1'])){ //$query = "UPDATE `article_draft` SET `draft_content` = '" . $_POST["CKEditor1"] . "' WHERE `page_modulecomponentid` =".$this->moduleComponentId; $query="SELECT MAX(draft_number) AS MAX FROM `article_draft` WHERE page_modulecomponentid ='$this->moduleComponentId'"; - $result = mysql_query($query); - if(!$result) { displayerror(mysql_error() . "article.lib L:44"); return; } - if(mysql_num_rows($result)) + $result = $pdb->query($query); + //if(!$result) { displayerror(mysql_error() . "article.lib L:44"); return; } + if(count($result)) { - $drow = mysql_fetch_assoc($result); + $drow = $result[0]; $draftId = $drow['MAX'] + 1; } else $draftId=1; $query = "INSERT INTO `article_draft` (`page_modulecomponentid`,`draft_number`,`draft_content`,`draft_lastsaved`,`user_id`) VALUES ('".$this->moduleComponentId."','".$draftId."','".$_POST['CKEditor1']."',now(),'".$this->userId."')"; - $result = mysql_query($query) or die(mysql_error()); - if(mysql_affected_rows() < 1) + $result = $pdb->query($query); + if($result < 1) displayerror("Unable to draft the article"); } if($this->isCommentsEnabled() && isset($_POST['btnSubmit'])) { - $id = mysql_fetch_array(mysql_query("SELECT MAX(`comment_id`) AS MAX FROM `article_comments`")); - $id = $id['MAX'] + 1; + $id = $pdb->query("SELECT MAX(`comment_id`) AS MAX FROM `article_comments`"); + $id = $id[0]['MAX'] + 1; $user = getUserName($this->userId); $comment = escape(safe_html($_POST['comment'])); - mysql_query("INSERT INTO `article_comments`(`comment_id`,`page_modulecomponentid`,`user`,`comment`) VALUES('$id','{$this->moduleComponentId}','$user','$comment')"); - if(mysql_affected_rows()) + $result = $pdb->query("INSERT INTO `article_comments`(`comment_id`,`page_modulecomponentid`,`user`,`comment`) VALUES('$id','{$this->moduleComponentId}','$user','$comment')"); + if($result) displayinfo("Post successful"); else displayerror("Error in posting comment"); } if($text==""){ $query = "SELECT article_content,article_lastupdated FROM article_content WHERE page_modulecomponentid='" . $this->moduleComponentId."'"; - $result = mysql_query($query); - if($row = mysql_fetch_assoc($result)) { + $result = $pdb->query($query); + if($row = $result[0]) { $text = $row['article_content']; $text = censor_words($text); global $PAGELASTUPDATED; @@ -148,12 +151,12 @@ public function actionView($text="") { if($this->isCommentsEnabled()) { - $comments = mysql_query("SELECT `comment_id`,`user`,`timestamp`,`comment` FROM `article_comments` WHERE `page_modulecomponentid` = '{$this->moduleComponentId}' ORDER BY `timestamp`"); - if(mysql_num_rows($comments)>0) + $comments = $pdb->query("SELECT `comment_id`,`user`,`timestamp`,`comment` FROM `article_comments` WHERE `page_modulecomponentid` = '{$this->moduleComponentId}' ORDER BY `timestamp`"); + if(count($comments)>0) $ret .= "
Comments"; - while($row = mysql_fetch_array($comments)) + foreach($comments as $row) $ret .= $this->renderComment($row['comment_id'],$row['user'],$row['timestamp'],censor_words($row['comment'])); - if(mysql_num_rows($comments)>0) + if(count($comments)>0) $ret .= "
"; $ret .= $this->commentBox(); } @@ -162,7 +165,7 @@ public function actionView($text="") { public function actionEdit() { - global $sourceFolder,$ICONS; + global $sourceFolder,$ICONS,$pdb; //require_once("$sourceFolder/diff.lib.php"); require_once($sourceFolder."/upload.lib.php"); @@ -170,7 +173,7 @@ public function actionEdit() { { $dno = escape($_GET['dno']); $query = "DELETE FROM `article_draft` WHERE `page_modulecomponentid`='". $this->moduleComponentId."' AND `draft_number`=".$dno; - $result = mysql_query($query) or die(mysql_error()); + $result = $pdb->query($query); } global $ICONS; @@ -192,8 +195,8 @@ public function actionEdit() { submitFileUploadForm($this->moduleComponentId,"article",$this->userId,UPLOAD_SIZE_LIMIT); if(isset($_GET['delComment']) && $this->userId == 1) { - mysql_query("DELETE FROM `article_comments` WHERE `comment_id` = '".escape($_GET['delComment'])."'"); - if(mysql_affected_rows()) + $result = $pdb->query("DELETE FROM `article_comments` WHERE `comment_id` = '".escape($_GET['delComment'])."'"); + if($result) displayinfo("Comment deleted!"); else displayerror("Error in deleting comment"); @@ -217,15 +220,15 @@ public function actionEdit() { /*Save the diff :-*/ $query = "SELECT article_content FROM article_content WHERE page_modulecomponentid='" . $this->moduleComponentId."'"; - $result = mysql_query($query); - $row = mysql_fetch_assoc($result); - $diff = mysql_escape_string($this->diff($_POST['CKEditor1'],$row['article_content'])); + $result = $pdb->query($query); + $row = $result[0]; + $diff = $this->diff($_POST['CKEditor1'],$row['article_content']); $query="SELECT MAX(article_revision) AS MAX FROM `article_contentbak` WHERE page_modulecomponentid ='" . $this->moduleComponentId."'"; - $result = mysql_query($query); - if(!$result) { displayerror(mysql_error() . "article.lib L:44"); return; } - if(mysql_num_rows($result)) + $result = $pdb->query($query); + //if(!$result) { displayerror(mysql_error() . "article.lib L:44"); return; } + if(count($result)) { - $row = mysql_fetch_assoc($result); + $row = $result[0]; $revId = $row['MAX'] + 1; } else $revId=1; @@ -233,14 +236,14 @@ public function actionEdit() { $query = "INSERT INTO `article_contentbak` (`page_modulecomponentid` ,`article_revision` ,`article_diff`,`user_id`) VALUES ('$this->moduleComponentId', '$revId','$diff','$this->userId')"; - $result = mysql_query($query); - if(!$result) { displayerror(mysql_error() . "article.lib L:44"); return; } + $result = $pdb->query($query); + //if(!$result) { displayerror(mysql_error() . "article.lib L:44"); return; } /*Save the diff end.*/ $query = "UPDATE `article_content` SET `article_content` = '" . escape($_POST["CKEditor1"]) . "' WHERE `page_modulecomponentid` ='$this->moduleComponentId' "; - $result = mysql_query($query); - if(mysql_affected_rows() < 0) + $result = $pdb->query($query); + if(count($result) <= 0) displayerror("Unable to update the article content"); else { @@ -254,8 +257,8 @@ public function actionEdit() { if(isset($_POST['editor'])){ $editor=escape($_POST['editor']); $query = "UPDATE `article_content` SET `default_editor` = '" . $editor . "' WHERE `page_modulecomponentid` ='$this->moduleComponentId' "; - $result = mysql_query($query); - if(mysql_affected_rows() < 0) + $result = $pdb->query($query); + if(count($result) < 0) displayerror("Unable to update the article Editor"); } return $this->actionView(); @@ -265,12 +268,12 @@ public function actionEdit() { $commentsedit = "
{$ICONS['Page Comments']['small']}Comments"; if($this->isCommentsEnabled()) { - $comments = mysql_query("SELECT `comment_id`,`user`,`timestamp`,`comment` FROM `article_comments` WHERE `page_modulecomponentid` = '{$this->moduleComponentId}' ORDER BY `timestamp`"); - if(mysql_num_rows($comments)==0) + $comments = $pdb->query("SELECT `comment_id`,`user`,`timestamp`,`comment` FROM `article_comments` WHERE `page_modulecomponentid` = '{$this->moduleComponentId}' ORDER BY `timestamp`"); + if(count($comments)==0) $commentsedit.= "No comments have been posted !"; - while($row = mysql_fetch_array($comments)) + foreach($comments as $row) { $commentsedit .= $this->renderComment($row['comment_id'],$row['user'],$row['timestamp'],$row['comment'],1); @@ -366,13 +369,14 @@ public function patch($article,$patch) { return $patch; } public function getRevision($revisionNo) { + global $pdb; $currentquery = "SELECT article_content FROM article_content WHERE page_modulecomponentid='" . $this->moduleComponentId."'"; - $currentresult = mysql_query($currentquery); - $currentrow = mysql_fetch_assoc($currentresult); + $currentresult = $pdb->query($currentquery); + $currentrow = $currentresult[0]; $revision = $currentrow['article_content']; $diffquery = "SELECT * FROM `article_contentbak` WHERE `page_modulecomponentid`='$this->moduleComponentId' AND article_revision >= '$revisionNo' ORDER BY article_revision DESC"; - $diffresult = mysql_query($diffquery); - while($diffrow = mysql_fetch_assoc($diffresult)) { + $diffresult = $pdb->query($diffquery); + foreach($diffresult as $diffrow) { $revision = $this->patch($revision,$diffrow['article_diff']); } return $revision; diff --git a/cms/pdo.class.php b/cms/pdo.class.php new file mode 100755 index 00000000..60cb0905 --- /dev/null +++ b/cms/pdo.class.php @@ -0,0 +1,119 @@ + + * @license http://www.gnu.org/licenses/gpl.html GNU GPL V3 + * @link https://github.com/delta/pragyan/ + * For more details, see README + * + *TODO + *1 Write docblock for class and functions + *2 Make connect a public function and pass database constants to constructor + */ + +if (!defined('__PRAGYAN_CMS')) { + header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden'); + echo "

403 Forbidden

You are not authorized to access the page.

"; + echo '
'.$_SERVER['SERVER_SIGNATURE']; + exit(1); +} + +class pdodb { + private $_pdo; // @object The PDO object + private $_stmt; // @object PDO statement object + private $_isconnected; // @bool connected to database + private $_params; // @array Paramaters of query + + // Constructor sets $isconnected, connects to db and creates params array + public function __construct() { + $this->_isconnected = false; + $this->_connect(); + $this->_params=array(); + } + + // connect tries to connect + private function _connect() { + if (MYSQL_SERVER=='localhost') { + $dsn='mysql:dbname='.MYSQL_DATABASE.';host=127.0.0.1'; + } else { + $dsn='mysql:dbname='.MYSQL_DATABASE.';host='.MYSQL_SERVER.''; + } + try { + $this->_pdo = new PDO($dsn, MYSQL_USERNAME, MYSQL_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); + $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + $this->_isconnected = true; + } catch(PDOException $e) { + displayerror($e->getMessage()); + die(); + } + } + + // init tries to connect, prepare, parameterize, execute and reset params + private function _init($query,$params = "") { + if (!$this->_isconnected) { + $this->_connect(); + } + try { + $this->_stmt=$this->_pdo->prepare($query); + $this->bindMore($params); + if (!empty($this->_params)) { + foreach ($this->_params as $param) { + $params=explode("\x7F", $param); + $this->_stmt->bindParam($params[0], $params[1]); + } + } + $this->_stmt->execute(); + } catch(PDOException $e) { + displayerror($e->getMessage()); + die(); + } + $this->_params=array(); + } + + // exposing _pdo + public function getpdo() { + return $this->_pdo; + } + + // bind adds parameter to params array + public function bind($para,$value) { + $this->_params[sizeof($this->_params)] = ":" . $para . "\x7F" . utf8_encode($value); + } + + // bind more + public function bindMore($parray) { + if (empty($this->_params) && is_array($parray)) { + $columns = array_keys($parray); + foreach ($columns as $i => &$column) { + $this->bind($column, $parray[$column]); + } + } + } + + // returns array for SELECT and SHOW, returns number of affected rows for DELETE, INSERT and UPDATE + public function query($query,$params=null,$fetchmode=PDO::FETCH_ASSOC) { + $query=trim($query); + $this->_init($query, $params); + $rawStatement=explode(" ", $query); + $statement=strtolower($rawStatement[0]); + if ($statement==='select'||$statement==='show') { + return $this->_stmt->fetchAll($fetchmode); + } elseif ($statement==='insert'||$statement==='update'||$statement==='delete') { + return $this->_stmt->rowCount(); + } else { + return null; + } + } + + // returns the last inserted id. + public function lastInsertId() { + return $this->_pdo->lastInsertId(); + } +} diff --git a/index.php b/index.php index 42cdc29f..b5b911f1 100755 --- a/index.php +++ b/index.php @@ -117,7 +117,8 @@ NOTE:If you're not using the official package of the Pragyan CMS or you're installing for the second time, then please make sure that the 'RewriteEngine' property is set to 'Off' in the .htaccess file present in the root folder of Pragyan for the above link to work correctly."; exit(); } - +require_once($sourceFolder."/pdo.class.php"); +$pdb = new pdodb(); ///Contains functions which are common to many tasks and very frequently used. require_once($sourceFolder."/common.lib.php");