Database.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. ###
  3. # @name Database Module
  4. # @copyright 2015 by Tobias Reich
  5. ###
  6. if (!defined('LYCHEE')) exit('Error: Direct access is not allowed!');
  7. final class Database extends Module {
  8. private $connection = null;
  9. private static $instance = null;
  10. private static $versions = array(
  11. '020700', #2.7.0
  12. '030000', #3.0.0
  13. '030001', #3.0.1
  14. '030003' #3.0.3
  15. );
  16. public static function get() {
  17. if (!self::$instance) {
  18. $credentials = Config::get();
  19. self::$instance = new self(
  20. $credentials['host'],
  21. $credentials['user'],
  22. $credentials['password'],
  23. $credentials['name'],
  24. $credentials['prefix']
  25. );
  26. }
  27. return self::$instance->connection;
  28. }
  29. private function __construct($host, $user, $password, $name = 'lychee', $dbTablePrefix) {
  30. # Check dependencies
  31. Module::dependencies(isset($host, $user, $password, $name));
  32. # Define the table prefix
  33. defineTablePrefix($dbTablePrefix);
  34. # Open a new connection to the MySQL server
  35. $connection = self::connect($host, $user, $password);
  36. # Check if the connection was successful
  37. if ($connection===false) exit('Error: ' . $connection->connect_error);
  38. if (!self::setCharset($connection)) exit('Error: Could not set database charset!');
  39. # Create database
  40. if (!self::createDatabase($connection, $name)) exit('Error: Could not create database!');
  41. # Create tables
  42. if (!self::createTables($connection)) exit('Error: Could not create tables!');
  43. # Update database
  44. if (!self::update($connection, $name)) exit('Error: Could not update database and tables!');
  45. $this->connection = $connection;
  46. }
  47. private function __clone() {
  48. # Magic method clone is empty to prevent duplication of connection
  49. }
  50. public static function connect($host = 'localhost', $user, $password) {
  51. # Open a new connection to the MySQL server
  52. $connection = new mysqli($host, $user, $password);
  53. # Check if the connection was successful
  54. if ($connection->connect_errno) return false;
  55. return $connection;
  56. }
  57. private static function setCharset($connection) {
  58. # Avoid sql injection on older MySQL versions by using GBK
  59. if ($connection->server_version<50500) @$connection->set_charset('GBK');
  60. else @$connection->set_charset('utf8');
  61. # Set unicode
  62. $connection->query('SET NAMES utf8;');
  63. return true;
  64. }
  65. public static function createDatabase($connection, $name = 'lychee') {
  66. # Check dependencies
  67. Module::dependencies(isset($connection, $name));
  68. # Check if database exists
  69. if ($connection->select_db($name)) return true;
  70. # Create database
  71. $query = self::prepare($connection, 'CREATE DATABASE IF NOT EXISTS ?', array($name));
  72. $result = $connection->query($query);
  73. if (!$connection->select_db($name)) return false;
  74. return true;
  75. }
  76. private static function createTables($connection) {
  77. # Check dependencies
  78. Module::dependencies(isset($connection));
  79. # Check if tables exist
  80. $query = self::prepare($connection, 'SELECT * FROM ?, ?, ?, ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS, LYCHEE_TABLE_ALBUMS, LYCHEE_TABLE_SETTINGS, LYCHEE_TABLE_LOG));
  81. if ($connection->query($query)) return true;
  82. # Create log
  83. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_LOG));
  84. if (!$connection->query($exist)) {
  85. # Read file
  86. $file = __DIR__ . '/../database/log_table.sql';
  87. $query = @file_get_contents($file);
  88. if (!isset($query)||$query===false) return false;
  89. # Create table
  90. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_LOG));
  91. if (!$connection->query($query)) return false;
  92. }
  93. # Create settings
  94. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_SETTINGS));
  95. if (!$connection->query($exist)) {
  96. # Read file
  97. $file = __DIR__ . '/../database/settings_table.sql';
  98. $query = @file_get_contents($file);
  99. if (!isset($query)||$query===false) {
  100. Log::error(__METHOD__, __LINE__, 'Could not load query for lychee_settings');
  101. return false;
  102. }
  103. # Create table
  104. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_SETTINGS));
  105. if (!$connection->query($query)) {
  106. Log::error(__METHOD__, __LINE__, $connection->error);
  107. return false;
  108. }
  109. # Read file
  110. $file = __DIR__ . '/../database/settings_content.sql';
  111. $query = @file_get_contents($file);
  112. if (!isset($query)||$query===false) {
  113. Log::error(__METHOD__, __LINE__, 'Could not load content-query for lychee_settings');
  114. return false;
  115. }
  116. # Add content
  117. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_SETTINGS));
  118. if (!$connection->query($query)) {
  119. Log::error(__METHOD__, __LINE__, $connection->error);
  120. return false;
  121. }
  122. # Generate identifier
  123. $identifier = md5(microtime(true));
  124. $query = self::prepare($connection, "UPDATE `?` SET `value` = '?' WHERE `key` = 'identifier' LIMIT 1", array(LYCHEE_TABLE_SETTINGS, $identifier));
  125. if (!$connection->query($query)) {
  126. Log::error(__METHOD__, __LINE__, $connection->error);
  127. return false;
  128. }
  129. }
  130. # Create albums
  131. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_ALBUMS));
  132. if (!$connection->query($exist)) {
  133. # Read file
  134. $file = __DIR__ . '/../database/albums_table.sql';
  135. $query = @file_get_contents($file);
  136. if (!isset($query)||$query===false) {
  137. Log::error(__METHOD__, __LINE__, 'Could not load query for lychee_albums');
  138. return false;
  139. }
  140. # Create table
  141. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_ALBUMS));
  142. if (!$connection->query($query)) {
  143. Log::error(__METHOD__, __LINE__, $connection->error);
  144. return false;
  145. }
  146. }
  147. # Create photos
  148. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS));
  149. if (!$connection->query($exist)) {
  150. # Read file
  151. $file = __DIR__ . '/../database/photos_table.sql';
  152. $query = @file_get_contents($file);
  153. if (!isset($query)||$query===false) {
  154. Log::error(__METHOD__, __LINE__, 'Could not load query for lychee_photos');
  155. return false;
  156. }
  157. # Create table
  158. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_PHOTOS));
  159. if (!$connection->query($query)) {
  160. Log::error(__METHOD__, __LINE__, $connection->error);
  161. return false;
  162. }
  163. }
  164. return true;
  165. }
  166. private static function update($connection, $dbName) {
  167. # Check dependencies
  168. Module::dependencies(isset($connection));
  169. # Get current version
  170. $query = self::prepare($connection, "SELECT * FROM ? WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS));
  171. $results = $connection->query($query);
  172. $current = $results->fetch_object()->value;
  173. # For each update
  174. foreach (self::$versions as $version) {
  175. # Only update when newer version available
  176. if ($version<=$current) continue;
  177. # Load update
  178. include(__DIR__ . '/../database/update_' . $version . '.php');
  179. }
  180. return true;
  181. }
  182. public static function setVersion($connection, $version) {
  183. $query = self::prepare($connection, "UPDATE ? SET value = '?' WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS, $version));
  184. $result = $connection->query($query);
  185. if (!$result) {
  186. Log::error(__METHOD__, __LINE__, 'Could not update database (' . $connection->error . ')');
  187. return false;
  188. }
  189. }
  190. public static function prepare($connection, $query, $data) {
  191. # Check dependencies
  192. Module::dependencies(isset($connection, $query, $data));
  193. # Count the number of placeholders and compare it with the number of arguments
  194. # If it doesn't match, calculate the difference and skip this number of placeholders before starting the replacement
  195. # This avoids problems with placeholders in user-input
  196. # $skip = Number of placeholders which need to be skipped
  197. $skip = 0;
  198. $temp = '';
  199. $num = array(
  200. 'placeholder' => substr_count($query, '?'),
  201. 'data' => count($data)
  202. );
  203. if (($num['data']-$num['placeholder'])<0) Log::notice(__METHOD__, __LINE__, 'Could not completely prepare query. Query has more placeholders than values.');
  204. foreach ($data as $value) {
  205. # Escape
  206. $value = mysqli_real_escape_string($connection, $value);
  207. # Recalculate number of placeholders
  208. $num['placeholder'] = substr_count($query, '?');
  209. # Calculate number of skips
  210. if ($num['placeholder']>$num['data']) $skip = $num['placeholder'] - $num['data'];
  211. if ($skip>0) {
  212. # Need to skip $skip placeholders, because the user input contained placeholders
  213. # Calculate a substring which does not contain the user placeholders
  214. # 1 or -1 is the length of the placeholder (placeholder = ?)
  215. $pos = -1;
  216. for ($i=$skip; $i>0; $i--) $pos = strpos($query, '?', $pos + 1);
  217. $pos++;
  218. $temp = substr($query, 0, $pos); # First part of $query
  219. $query = substr($query, $pos); # Last part of $query
  220. }
  221. # Replace
  222. $query = preg_replace('/\?/', $value, $query, 1);
  223. if ($skip>0) {
  224. # Reassemble the parts of $query
  225. $query = $temp . $query;
  226. }
  227. # Reset skip
  228. $skip = 0;
  229. # Decrease number of data elements
  230. $num['data']--;
  231. }
  232. return $query;
  233. }
  234. }
  235. ?>