Database.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. /**
  14. * @return object Returns a new or cached connection.
  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. /**
  30. * Exits on error.
  31. * @return boolean Returns true when successful.
  32. */
  33. private function __construct($host, $user, $password, $name = 'lychee', $dbTablePrefix) {
  34. // Check dependencies
  35. Validator::required(isset($host, $user, $password, $name), __METHOD__);
  36. // Define the table prefix
  37. defineTablePrefix($dbTablePrefix);
  38. // Open a new connection to the MySQL server
  39. $connection = self::connect($host, $user, $password);
  40. // Check if the connection was successful
  41. if ($connection===false) Response::error('' . $connection->connect_error);
  42. if (self::setCharset($connection)===false) Response::error('Could not set database charset!');
  43. // Create database
  44. if (self::createDatabase($connection, $name)===false) Response::error('Could not create database!');
  45. // Create tables
  46. if (self::createTables($connection)===false) Response::error('Could not create tables!');
  47. // Update database
  48. if (self::update($connection, $name)===false) Response::error('Could not update database and tables!');
  49. $this->connection = $connection;
  50. return true;
  51. }
  52. /**
  53. * @return object|false Returns the connection when successful.
  54. */
  55. public static function connect($host = 'localhost', $user, $password) {
  56. // Open a new connection to the MySQL server
  57. $connection = new Mysqli($host, $user, $password);
  58. // Check if the connection was successful
  59. if ($connection->connect_errno) return false;
  60. return $connection;
  61. }
  62. /**
  63. * @return boolean Returns true when successful.
  64. */
  65. private static function setCharset($connection) {
  66. // Check dependencies
  67. Validator::required(isset($connection), __METHOD__);
  68. // Avoid sql injection on older MySQL versions by using GBK
  69. if ($connection->server_version<50500) @$connection->set_charset('GBK');
  70. else @$connection->set_charset('utf8');
  71. // Set unicode
  72. $query = 'SET NAMES utf8';
  73. $result = self::execute($connection, $query, null, null);
  74. if ($result===false) return false;
  75. return true;
  76. }
  77. /**
  78. * @return boolean Returns true when successful.
  79. */
  80. public static function createDatabase($connection, $name = 'lychee') {
  81. // Check dependencies
  82. Validator::required(isset($connection), __METHOD__);
  83. // Check if database exists
  84. if ($connection->select_db($name)===true) return true;
  85. // Create database
  86. $query = self::prepare($connection, 'CREATE DATABASE IF NOT EXISTS ?', array($name));
  87. $result = self::execute($connection, $query, null, null);
  88. if ($result===false) return false;
  89. if ($connection->select_db($name)===false) return false;
  90. return true;
  91. }
  92. /**
  93. * @return boolean Returns true when successful.
  94. */
  95. private static function createTables($connection) {
  96. // Check dependencies
  97. Validator::required(isset($connection), __METHOD__);
  98. // Check if tables exist
  99. $query = self::prepare($connection, 'SELECT * FROM ?, ?, ?, ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS, LYCHEE_TABLE_ALBUMS, LYCHEE_TABLE_SETTINGS, LYCHEE_TABLE_LOG));
  100. $result = self::execute($connection, $query, null, null);
  101. if ($result!==false) return true;
  102. // Check if log table exists
  103. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_LOG));
  104. $result = self::execute($connection, $exist, null, null);
  105. if ($result===false) {
  106. // Read file
  107. $file = __DIR__ . '/../database/log_table.sql';
  108. $query = @file_get_contents($file);
  109. if ($query===false) return false;
  110. // Create table
  111. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_LOG));
  112. $result = self::execute($connection, $query, null, null);
  113. if ($result===false) return false;
  114. }
  115. // Check if settings table exists
  116. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_SETTINGS));
  117. $result = self::execute($connection, $exist, __METHOD__, __LINE__);
  118. if ($result===false) {
  119. // Read file
  120. $file = __DIR__ . '/../database/settings_table.sql';
  121. $query = @file_get_contents($file);
  122. if ($query===false) {
  123. Log::error($connection, __METHOD__, __LINE__, 'Could not load query for lychee_settings');
  124. return false;
  125. }
  126. // Create table
  127. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_SETTINGS));
  128. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  129. if ($result===false) return false;
  130. // Read file
  131. $file = __DIR__ . '/../database/settings_content.sql';
  132. $query = @file_get_contents($file);
  133. if ($query===false) {
  134. Log::error($connection, __METHOD__, __LINE__, 'Could not load content-query for lychee_settings');
  135. return false;
  136. }
  137. // Add content
  138. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_SETTINGS));
  139. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  140. if ($result===false) return false;
  141. // Generate identifier
  142. $identifier = md5(microtime(true));
  143. $query = self::prepare($connection, "UPDATE `?` SET `value` = '?' WHERE `key` = 'identifier' LIMIT 1", array(LYCHEE_TABLE_SETTINGS, $identifier));
  144. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  145. if ($result===false) return false;
  146. }
  147. // Check if albums table exists
  148. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_ALBUMS));
  149. $result = self::execute($connection, $exist, __METHOD__, __LINE__);
  150. if ($result===false) {
  151. // Read file
  152. $file = __DIR__ . '/../database/albums_table.sql';
  153. $query = @file_get_contents($file);
  154. if ($query===false) {
  155. Log::error($connection, __METHOD__, __LINE__, 'Could not load query for lychee_albums');
  156. return false;
  157. }
  158. // Create table
  159. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_ALBUMS));
  160. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  161. if ($result===false) return false;
  162. }
  163. // Check if photos table exists
  164. $exist = self::prepare($connection, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS));
  165. $result = self::execute($connection, $exist, __METHOD__, __LINE__);
  166. if ($result===false) {
  167. // Read file
  168. $file = __DIR__ . '/../database/photos_table.sql';
  169. $query = @file_get_contents($file);
  170. if ($query===false) {
  171. Log::error($connection, __METHOD__, __LINE__, 'Could not load query for lychee_photos');
  172. return false;
  173. }
  174. // Create table
  175. $query = self::prepare($connection, $query, array(LYCHEE_TABLE_PHOTOS));
  176. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  177. if ($result===false) return false;
  178. }
  179. return true;
  180. }
  181. /**
  182. * Exits when an update fails.
  183. * @return boolean Returns true when successful.
  184. */
  185. private static function update($connection, $dbName) {
  186. // Check dependencies
  187. Validator::required(isset($connection, $dbName), __METHOD__);
  188. // Get current version
  189. $query = self::prepare($connection, "SELECT * FROM ? WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS));
  190. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  191. if ($result===false) return false;
  192. // Extract current version
  193. $current = $result->fetch_object()->value;
  194. // For each update
  195. foreach (self::$versions as $version) {
  196. // Only update when newer version available
  197. if ($version<=$current) continue;
  198. // Load update
  199. include(__DIR__ . '/../database/update_' . $version . '.php');
  200. }
  201. return true;
  202. }
  203. /**
  204. * @return boolean Returns true when successful.
  205. */
  206. public static function setVersion($connection, $version) {
  207. // Check dependencies
  208. Validator::required(isset($connection), __METHOD__);
  209. $query = self::prepare($connection, "UPDATE ? SET value = '?' WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS, $version));
  210. $result = self::execute($connection, $query, __METHOD__, __LINE__);
  211. if ($result===false) return false;
  212. return true;
  213. }
  214. /**
  215. * @return string Returns a escaped query.
  216. */
  217. public static function prepare($connection, $query, array $data) {
  218. // Check dependencies
  219. Validator::required(isset($connection, $query), __METHOD__);
  220. // Count the number of placeholders and compare it with the number of arguments
  221. // If it doesn't match, calculate the difference and skip this number of placeholders before starting the replacement
  222. // This avoids problems with placeholders in user-input
  223. // $skip = Number of placeholders which need to be skipped
  224. $skip = 0;
  225. $temp = '';
  226. $num = array(
  227. 'placeholder' => substr_count($query, '?'),
  228. 'data' => count($data)
  229. );
  230. if (($num['data']-$num['placeholder'])<0) Log::notice($connection, __METHOD__, __LINE__, 'Could not completely prepare query. Query has more placeholders than values.');
  231. foreach ($data as $value) {
  232. // Escape
  233. $value = mysqli_real_escape_string($connection, $value);
  234. // Recalculate number of placeholders
  235. $num['placeholder'] = substr_count($query, '?');
  236. // Calculate number of skips
  237. if ($num['placeholder']>$num['data']) $skip = $num['placeholder'] - $num['data'];
  238. if ($skip>0) {
  239. // Need to skip $skip placeholders, because the user input contained placeholders
  240. // Calculate a substring which does not contain the user placeholders
  241. // 1 or -1 is the length of the placeholder (placeholder = ?)
  242. $pos = -1;
  243. for ($i=$skip; $i>0; $i--) $pos = strpos($query, '?', $pos + 1);
  244. $pos++;
  245. $temp = substr($query, 0, $pos); // First part of $query
  246. $query = substr($query, $pos); // Last part of $query
  247. }
  248. // Replace
  249. $query = preg_replace('/\?/', $value, $query, 1);
  250. if ($skip>0) {
  251. // Reassemble the parts of $query
  252. $query = $temp . $query;
  253. }
  254. // Reset skip
  255. $skip = 0;
  256. // Decrease number of data elements
  257. $num['data']--;
  258. }
  259. return $query;
  260. }
  261. /**
  262. * @return object|false Returns the results on success.
  263. */
  264. public static function execute($connection, $query, $function, $line) {
  265. // Check dependencies
  266. Validator::required(isset($connection, $query), __METHOD__);
  267. // Only activate logging when $function and $line is set
  268. $logging = ($function===null||$line===null ? false : true);
  269. // Execute query
  270. $result = $connection->query($query);
  271. // Check if execution failed
  272. if ($result===false) {
  273. if ($logging===true) Log::error($connection, $function, $line, $connection->error);
  274. return false;
  275. }
  276. return $result;
  277. }
  278. }
  279. ?>