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