Database.php 11 KB

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