Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.53 KB | None | 0 0
  1. <?php
  2. /**
  3. * Database class
  4. * https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class
  5. *
  6. */
  7.  
  8. class Database
  9. {
  10. # @object, The PDO object
  11. protected $pdo;
  12.  
  13. # @object, PDO statement object
  14. protected $sQuery;
  15.  
  16. # @array, The database settings
  17. protected $ini;
  18.  
  19. # @bool , Connected to the database
  20. protected $connected = false;
  21.  
  22. # @object, Object for logging exceptions
  23. protected $log;
  24.  
  25. # @array, The parameters of the SQL query
  26. protected $parameters;
  27.  
  28. # Create an instance
  29. private
  30.  
  31. /**
  32. * Default Constructor
  33. *
  34. * 1. Instantiate Log class.
  35. * 2. Creates the parameter array.
  36. */
  37. public function __construct()
  38. {
  39.  
  40. }
  41.  
  42. /**
  43. * Get the PDO connection
  44. *
  45. */
  46. public function getPDO()
  47. {
  48. if ($this->pdo instanceof PDO)
  49. return $this->pdo;
  50. }
  51.  
  52. /**
  53. * This method makes connection to the database.
  54. *
  55. * 1. Reads the database settings from a ini file.
  56. * 2. Puts the ini content into the settings array.
  57. * 3. Tries to connect to the database.
  58. * 4. If connection failed, exception is displayed and a log file gets created.
  59. */
  60. protected function Connect($host, $user, $password, $dbname)
  61. {
  62.  
  63. $dsn = 'mysql:dbname=' . $dbname . ';host=' . $host . '';
  64.  
  65. try {
  66. # Read settings from INI file, set UTF8
  67. $this->pdo = new PDO($dsn, $user, $password, array(
  68. PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
  69. ));
  70.  
  71. # We can now log any exceptions on Fatal error.
  72. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  73.  
  74. # Disable emulation of prepared statements, use REAL prepared statements instead.
  75. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  76.  
  77. # Connection succeeded, set the boolean to true.
  78. $this->connected = true;
  79. }
  80. catch (PDOException $e) {
  81. # Write into log
  82. // echo $this->ExceptionLog($e->getMessage());
  83. dbg( $this->ExceptionLog($e->getMessage()) );
  84. die();
  85. }
  86. }
  87.  
  88.  
  89. /*
  90. * You can use this little method if you want to close the PDO connection
  91. *
  92. */
  93. public function CloseConnection()
  94. {
  95. # Set the PDO object to null to close the connection
  96. # http://www.php.net/manual/en/pdo.connections.php
  97. $this->pdo = null;
  98. }
  99.  
  100.  
  101. /*
  102. * Gets db.ini data
  103. *
  104. */
  105. protected function get_db_ini()
  106. {
  107. if ( empty($this->ini) ) $this->load_db_ini();
  108. }
  109.  
  110.  
  111. /*
  112. * Load db.ini file contents
  113. *
  114. */
  115. protected function load_db_ini()
  116. {
  117. $this->ini = parse_ini_file('/etc/optimizeit/db.ini', true);
  118. }
  119.  
  120.  
  121. /*
  122. * Gets section from db.ini resultarray
  123. *
  124. */
  125. protected function get_db_ini_section($section)
  126. {
  127. return isset( $this->ini[$section] ) ? $this->ini[$section] : Array();
  128. }
  129.  
  130.  
  131. /**
  132. * Every method which needs to execute a SQL query uses this method.
  133. *
  134. * 1. If not connected, connect to the database.
  135. * 2. Prepare Query.
  136. * 3. Parameterize Query.
  137. * 4. Execute Query.
  138. * 5. On exception : Write Exception into the log + SQL query.
  139. * 6. Reset the Parameters.
  140. */
  141. protected function Init($query, $parameters = "")
  142. {
  143. # Connect to database
  144. if (!$this->connected) {
  145. $this->Connect();
  146. }
  147. try {
  148. # Prepare query
  149. $this->sQuery = $this->pdo->prepare($query);
  150.  
  151. # Add parameters to the parameter array
  152. $this->bindMore($parameters);
  153.  
  154. # Bind parameters
  155. if (!empty($this->parameters)) {
  156. foreach ($this->parameters as $param => $value) {
  157. if(is_int($value[1])) {
  158. $type = PDO::PARAM_INT;
  159. } else if(is_bool($value[1])) {
  160. $type = PDO::PARAM_BOOL;
  161. } else if(is_null($value[1])) {
  162. $type = PDO::PARAM_NULL;
  163. } else {
  164. $type = PDO::PARAM_STR;
  165. }
  166. // Add type when binding the values to the column
  167. $this->sQuery->bindValue($value[0], $value[1], $type);
  168. }
  169. }
  170.  
  171. # Execute SQL
  172. $this->sQuery->execute();
  173. }
  174. catch (PDOException $e) {
  175. # Write into log and display Exception
  176. // echo $this->ExceptionLog($e->getMessage(), $query);
  177. dbg( $this->ExceptionLog($e->getMessage(), $query) );
  178. die();
  179. }
  180.  
  181. # Reset the parameters
  182. $this->parameters = array();
  183. }
  184.  
  185.  
  186. /**
  187. * @void
  188. *
  189. * Add the parameter to the parameter array
  190. * @param string $para
  191. * @param string $value
  192. * Updated 11.07.2018: https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class/issues/83
  193. */
  194. public function bind($para, $value)
  195. {
  196. if (is_int($para)) {
  197. $this->parameters[sizeof($this->parameters)] = [++$para , $value];
  198. } else {
  199. $this->parameters[sizeof($this->parameters)] = [":" . $para , $value];
  200. }
  201. }
  202.  
  203. /**
  204. * @void
  205. *
  206. * Add more parameters to the parameter array
  207. * @param array $parray
  208. */
  209. public function bindMore($parray)
  210. {
  211. if (empty($this->parameters) && is_array($parray)) {
  212. $columns = array_keys($parray);
  213. foreach ($columns as $i => &$column) {
  214. $this->bind($column, $parray[$column]);
  215. }
  216. }
  217. }
  218.  
  219.  
  220. /**
  221. * If the SQL query contains a SELECT or SHOW statement it returns an array containing all of the result set row
  222. * If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows
  223. *
  224. * @param string $query
  225. * @param array $params
  226. * @param int $fetchmode
  227. * @return mixed
  228. */
  229. public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
  230. {
  231. $query = trim(str_replace("r", " ", $query));
  232.  
  233. $this->Init($query, $params);
  234.  
  235. $rawStatement = explode(" ", preg_replace("/s+|t+|n+/", " ", $query));
  236.  
  237. # Which SQL statement is used
  238. $statement = strtolower($rawStatement[0]);
  239.  
  240. if ($statement === 'select' || $statement === 'show') {
  241. return $this->sQuery->fetchAll($fetchmode);
  242. } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
  243. return $this->sQuery->rowCount();
  244. } else {
  245. return NULL;
  246. }
  247. }
  248.  
  249.  
  250. /**
  251. * Returns the last inserted id.
  252. * @return string
  253. */
  254. public function lastInsertId()
  255. {
  256. return $this->pdo->lastInsertId();
  257. }
  258.  
  259.  
  260. /**
  261. * Starts the transaction
  262. * @return boolean, true on success or false on failure
  263. */
  264. public function beginTransaction()
  265. {
  266. return $this->pdo->beginTransaction();
  267. }
  268.  
  269.  
  270. /**
  271. * Execute Transaction
  272. * @return boolean, true on success or false on failure
  273. */
  274. public function executeTransaction()
  275. {
  276. return $this->pdo->commit();
  277. }
  278.  
  279.  
  280. /**
  281. * Rollback of Transaction
  282. * @return boolean, true on success or false on failure
  283. */
  284. public function rollBack()
  285. {
  286. return $this->pdo->rollBack();
  287. }
  288.  
  289.  
  290. /**
  291. * Returns an array which represents a column from the result set
  292. *
  293. * @param string $query
  294. * @param array $params
  295. * @return array
  296. */
  297. public function column($query, $params = null)
  298. {
  299. $this->Init($query, $params);
  300. $Columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);
  301.  
  302. $column = null;
  303.  
  304. foreach ($Columns as $cells) {
  305. $column[] = $cells[0];
  306. }
  307.  
  308. return $column;
  309. }
  310.  
  311.  
  312. /**
  313. * Returns an array which represents a row from the result set
  314. *
  315. * @param string $query
  316. * @param array $params
  317. * @param int $fetchmode
  318. * @return array
  319. */
  320. public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
  321. {
  322. $this->Init($query, $params);
  323. $result = $this->sQuery->fetch($fetchmode);
  324. $this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
  325. return $result;
  326. }
  327.  
  328.  
  329. /**
  330. * Returns the value of one single field/column
  331. *
  332. * @param string $query
  333. * @param array $params
  334. * @return string
  335. */
  336. public function single($query, $params = null)
  337. {
  338. $this->Init($query, $params);
  339. $result = $this->sQuery->fetchColumn();
  340. $this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued
  341. return $result;
  342. }
  343.  
  344.  
  345. /**
  346. * Writes the log and returns the exception
  347. *
  348. * @param string $message
  349. * @param string $sql
  350. * @return string
  351. */
  352. protected function ExceptionLog($message, $sql = "")
  353. {
  354. $exception = "Unhandled Exception. <br /> n";
  355. $exception .= $message;
  356. $exception .= "<br /> n You can find the error back in the log.";
  357.  
  358. if (!empty($sql)) {
  359. # Add the Raw SQL to the Log
  360. $message .= "rnRaw SQL : " . $sql;
  361. }
  362. # Write into log
  363. // $this->log->write($message);
  364.  
  365. return $exception;
  366. }
  367.  
  368.  
  369. /**
  370. * Generate a string for columns selection
  371. * @param Array $app_name An array of app name/s or preferable - comma separated sting
  372. * @throws Array An array of app_id, app_name, lhm_threshold, enable_evm, evm_type, evm_rate for each app.
  373. */
  374. private function select_columns(Array $colums_array)
  375. {
  376. return implode(",", $columns_array);
  377. }
  378.  
  379. }
  380. ?>
  381.  
  382. <?php
  383. /**
  384. * Backoffice Database Connection class
  385. *
  386. */
  387. require("Database.class.php");
  388.  
  389. class Backoffice_db extends Database
  390. {
  391. # @string, Database Host
  392. private $bo_host;
  393.  
  394. # @string, Database Username
  395. protected $user = 'root';
  396.  
  397. # @string, Database Password
  398. protected $password = 'thisismyrealpassword';
  399.  
  400. # @string, Database Name
  401. private $bo_dbname = 'backoffice';
  402.  
  403.  
  404. /**
  405. * Default Constructor
  406. *
  407. * 1. Instantiate Log class.
  408. * 2. Creates the parameter array.
  409. * 3. Get backoffice variables from ini
  410. * 4. Connect to database.
  411. *
  412. */
  413. public function __construct()
  414. {
  415. $this->parameters = array(); // Init params for queries.
  416. if ( empty($this->ini) ) $this->get_db_ini(); // Make sure INI is fetched.
  417.  
  418. $this->get_bo_host(); // Set global variables for the backoffice.
  419. $this->Connect($this->bo_host, $this->user, $this->password, $this->bo_dbname); // Connect with global vars.
  420. }
  421.  
  422.  
  423. /**
  424. * Get backoffice HOST for connection
  425. *
  426. * 1. Get backoffice credentials.
  427. * 2. Set backoffice credentials.
  428. *
  429. */
  430. protected function get_bo_host()
  431. {
  432. $backoffice_credentials = $this->get_db_config($this->dbname);
  433. $this->bo_host = $backoffice_credentials['host'];
  434. }
  435.  
  436.  
  437. /**
  438. * Get db configurations via given $dbname
  439. *
  440. * 1. Return 'main' array section (backoffice credentials)
  441. *
  442. */
  443. protected function get_db_config($dbname)
  444. {
  445.  
  446. try
  447. {
  448. $settings = $this->get_db_ini_section(md5($this->bo_dbname));
  449.  
  450. if ( empty($settings) )
  451. throw new Exception('Cannot Find the customers name `' . $this->bo_dbname . '` in .ini file.');
  452. }
  453. catch (Exception $e)
  454. {
  455. // echo $this->ExceptionLog($e->getMessage());
  456. // dbg( $this->ExceptionLog($e->getMessage()) );
  457. err( $this->ExceptionLog($e->getMessage()) );
  458. die($ex->getMessage());
  459. }
  460.  
  461. return $settings;
  462. }
  463.  
  464.  
  465.  
  466. }
  467.  
  468. <?php
  469. /**
  470. * Customer Database Connection class
  471. *
  472. */
  473. require("Backoffice_db.class.php");
  474.  
  475. class Customer_db extends Backoffice_db
  476. {
  477.  
  478. # @string, Database Host
  479. private $host;
  480.  
  481. # @string, Database Name
  482. private $dbname;
  483.  
  484. # The Single Instance
  485. private static $instance;
  486.  
  487.  
  488. /*
  489. * Get an instance of the Database
  490. * @return Instance
  491. */
  492. public static function getInstance() {
  493.  
  494. if ( !self::$instance ) { // If no instance then make one
  495. self::$instance = new self();
  496. }
  497.  
  498. return self::$instance; // Return the Database obj
  499. // return self::$instance->getPDO();// Return the PDO connectoion instance from dabase obj
  500. }
  501.  
  502.  
  503. /**
  504. * Default Constructor
  505. * 1. Sets given dbnmae
  506. * 2. Connects to the backoffice
  507. * 3. Get customer data from backoffice db
  508. * 4. Disconnects from backoffice db
  509. * 5. Connect to customers database if active account
  510. */
  511. public function __construct($dbname)
  512. {
  513. self::$instance = $this;
  514.  
  515. $this->dbname = $dbname;
  516.  
  517. $bo_conn = new Backoffice_db();
  518.  
  519. list($this->host, $this->dbname, $status) = $this->get_customer_conn_info($bo_conn);
  520.  
  521. $bo_conn->CloseConnection(); // Disconnect from backoffice and connect to customer
  522.  
  523. try
  524. {
  525. if ( ($status === 'Deleted') || ($status === 'Inactive') )
  526. throw new Exception('Customer ('. $dbname .') account is "Deleted" or "Inactive".');
  527.  
  528. $this->Connect($this->host, $this->user, $this->password, $this->dbname);
  529. }
  530. catch(Exception $e)
  531. {
  532. err($this->ExceptionLog($e->getMessage()));
  533. die($e->getMessage());
  534. }
  535.  
  536. }
  537.  
  538.  
  539. /**
  540. * Get user HOST, DBNAME & STATUS from backoffice=>customers table
  541. *
  542. * 1. Run a query on backoffice to fetch users host and db name
  543. * 2. return 2 separate vairbles of host and db name
  544. *
  545. */
  546. protected function get_customer_conn_info($bo_conn){
  547.  
  548. $customer_data = $bo_conn->row("SELECT db_host, db_name, assessment_status FROM customers WHERE customer_name = :customer_name", array("customer_name" => $this->dbname));
  549. return array($customer_data['db_host'], $customer_data['db_name'], $customer_data['assessment_status']);
  550. }
  551.  
  552. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement