Database.php 8.6 KB

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