Database.php 9.2 KB

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