Database.php 9.0 KB

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