Database.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. );
  45. # For each update
  46. foreach ($updates as $update) {
  47. if ($update<=$version) continue;
  48. # Load update
  49. include(__DIR__ . '/../database/update_' . $update . '.php');
  50. }
  51. return true;
  52. }
  53. static function createConfig($host = 'localhost', $user, $password, $name = 'lychee', $prefix = '') {
  54. # Check dependencies
  55. Module::dependencies(isset($host, $user, $password, $name));
  56. $database = new mysqli($host, $user, $password);
  57. if ($database->connect_errno) return 'Warning: Connection failed!';
  58. # Check if database exists
  59. if (!$database->select_db($name)) {
  60. # Database doesn't exist
  61. # Check if user can create the database
  62. $result = Database::createDatabase($database, $name);
  63. if ($result===false) return 'Warning: Creation failed!';
  64. }
  65. # Escape data
  66. $host = mysqli_real_escape_string($database, $host);
  67. $user = mysqli_real_escape_string($database, $user);
  68. $password = mysqli_real_escape_string($database, $password);
  69. $name = mysqli_real_escape_string($database, $name);
  70. $prefix = mysqli_real_escape_string($database, $prefix);
  71. # Save config.php
  72. $config = "<?php
  73. ###
  74. # @name Configuration
  75. # @author Tobias Reich
  76. # @copyright 2015 Tobias Reich
  77. ###
  78. if(!defined('LYCHEE')) exit('Error: Direct access is not allowed!');
  79. # Database configuration
  80. \$dbHost = '$host'; # Host of the database
  81. \$dbUser = '$user'; # Username of the database
  82. \$dbPassword = '$password'; # Password of the database
  83. \$dbName = '$name'; # Database name
  84. \$dbTablePrefix = '$prefix'; # Table prefix
  85. ?>";
  86. # Save file
  87. if (file_put_contents(LYCHEE_CONFIG_FILE, $config)===false) return 'Warning: Could not create file!';
  88. return true;
  89. }
  90. static function createDatabase($database, $name = 'lychee') {
  91. # Check dependencies
  92. Module::dependencies(isset($database, $name));
  93. # Create database
  94. $query = Database::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. static function createTables($database) {
  100. # Check dependencies
  101. Module::dependencies(isset($database));
  102. # Create log
  103. $exist = Database::prepare($database, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_LOG));
  104. if (!$database->query($exist)) {
  105. # Read file
  106. $file = __DIR__ . '/../database/log_table.sql';
  107. $query = @file_get_contents($file);
  108. if (!isset($query)||$query===false) return false;
  109. # Create table
  110. $query = Database::prepare($database, $query, array(LYCHEE_TABLE_LOG));
  111. if (!$database->query($query)) return false;
  112. }
  113. # Create settings
  114. $exist = Database::prepare($database, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_SETTINGS));
  115. if (!$database->query($exist)) {
  116. # Read file
  117. $file = __DIR__ . '/../database/settings_table.sql';
  118. $query = @file_get_contents($file);
  119. if (!isset($query)||$query===false) {
  120. Log::error($database, __METHOD__, __LINE__, 'Could not load query for lychee_settings');
  121. return false;
  122. }
  123. # Create table
  124. $query = Database::prepare($database, $query, array(LYCHEE_TABLE_SETTINGS));
  125. if (!$database->query($query)) {
  126. Log::error($database, __METHOD__, __LINE__, $database->error);
  127. return false;
  128. }
  129. # Read file
  130. $file = __DIR__ . '/../database/settings_content.sql';
  131. $query = @file_get_contents($file);
  132. if (!isset($query)||$query===false) {
  133. Log::error($database, __METHOD__, __LINE__, 'Could not load content-query for lychee_settings');
  134. return false;
  135. }
  136. # Add content
  137. $query = Database::prepare($database, $query, array(LYCHEE_TABLE_SETTINGS));
  138. if (!$database->query($query)) {
  139. Log::error($database, __METHOD__, __LINE__, $database->error);
  140. return false;
  141. }
  142. }
  143. # Create albums
  144. $exist = Database::prepare($database, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_ALBUMS));
  145. if (!$database->query($exist)) {
  146. # Read file
  147. $file = __DIR__ . '/../database/albums_table.sql';
  148. $query = @file_get_contents($file);
  149. if (!isset($query)||$query===false) {
  150. Log::error($database, __METHOD__, __LINE__, 'Could not load query for lychee_albums');
  151. return false;
  152. }
  153. # Create table
  154. $query = Database::prepare($database, $query, array(LYCHEE_TABLE_ALBUMS));
  155. if (!$database->query($query)) {
  156. Log::error($database, __METHOD__, __LINE__, $database->error);
  157. return false;
  158. }
  159. }
  160. # Create photos
  161. $exist = Database::prepare($database, 'SELECT * FROM ? LIMIT 0', array(LYCHEE_TABLE_PHOTOS));
  162. if (!$database->query($exist)) {
  163. # Read file
  164. $file = __DIR__ . '/../database/photos_table.sql';
  165. $query = @file_get_contents($file);
  166. if (!isset($query)||$query===false) {
  167. Log::error($database, __METHOD__, __LINE__, 'Could not load query for lychee_photos');
  168. return false;
  169. }
  170. # Create table
  171. $query = Database::prepare($database, $query, array(LYCHEE_TABLE_PHOTOS));
  172. if (!$database->query($query)) {
  173. Log::error($database, __METHOD__, __LINE__, $database->error);
  174. return false;
  175. }
  176. }
  177. return true;
  178. }
  179. static function setVersion($database, $version) {
  180. $query = Database::prepare($database, "UPDATE ? SET value = '?' WHERE `key` = 'version'", array(LYCHEE_TABLE_SETTINGS, $version));
  181. $result = $database->query($query);
  182. if (!$result) {
  183. Log::error($database, __METHOD__, __LINE__, 'Could not update database (' . $database->error . ')');
  184. return false;
  185. }
  186. }
  187. static function prepare($database, $query, $data) {
  188. # Check dependencies
  189. Module::dependencies(isset($database, $query, $data));
  190. # Count the number of placeholders and compare it with the number of arguments
  191. # If it doesn't match, calculate the difference and skip this number of placeholders before starting the replacement
  192. # This avoids problems with placeholders in user-input
  193. # $skip = Number of placeholders which need to be skipped
  194. $skip = 0;
  195. $num = array(
  196. 'placeholder' => substr_count($query, '?'),
  197. 'data' => count($data)
  198. );
  199. if (($num['data']-$num['placeholder'])<0) Log::notice($database, __METHOD__, __LINE__, 'Could not completely prepare query. Query has more placeholders than values.');
  200. foreach ($data as $value) {
  201. # Escape
  202. $value = mysqli_real_escape_string($database, $value);
  203. # Recalculate number of placeholders
  204. $num['placeholder'] = substr_count($query, '?');
  205. # Calculate number of skips
  206. if ($num['placeholder']>$num['data']) $skip = $num['placeholder'] - $num['data'];
  207. if ($skip>0) {
  208. # Need to skip $skip placeholders, because the user input contained placeholders
  209. # Calculate a substring which does not contain the user placeholders
  210. # 1 or -1 is the length of the placeholder (placeholder = ?)
  211. $pos = -1;
  212. for ($i=$skip; $i>0; $i--) $pos = strpos($query, '?', $pos + 1);
  213. $pos++;
  214. $temp = substr($query, 0, $pos); # First part of $query
  215. $query = substr($query, $pos); # Last part of $query
  216. }
  217. # Replace
  218. $query = preg_replace('/\?/', $value, $query, 1);
  219. if ($skip>0) {
  220. # Reassemble the parts of $query
  221. $query = $temp . $query;
  222. }
  223. # Reset skip
  224. $skip = 0;
  225. # Decrease number of data elements
  226. $num['data']--;
  227. }
  228. return $query;
  229. }
  230. }
  231. ?>