DB.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. Lib::loadClass('Config');
  3. Lib::loadClass('DataSourceException');
  4. class DB {
  5. public static function getDataSource($db = null) {
  6. static $_instanceList;
  7. if (!is_array($_instanceList)) {
  8. $_instanceList = array();
  9. }
  10. if (null === $db) {
  11. $configName = 'default_db';
  12. } else if (is_numeric($db) && $db > 0) {
  13. $configName = "zasob_{$db}";
  14. } else if ($db == 'import_db') {
  15. $configName = "import_db";
  16. } else if ($db == 'test_db') {
  17. $configName = "test_db";
  18. } else if ($db == 'billing_db') {
  19. $configName = "billing_db";
  20. } else {// TODO: check by name from zasoby
  21. throw new Exception("Unknown data source name!");
  22. }
  23. if (array_key_exists($configName, $_instanceList)) {
  24. return $_instanceList[$configName];
  25. }
  26. $_instanceList[$configName] = null;
  27. $conf = Config::getConfFile($configName);
  28. if (!$conf) throw new Exception("Config for data source '{$configName}' not found!");
  29. $type = V::get('type', 'mysql', $conf);
  30. $host = V::get('host', '', $conf);
  31. $port = V::get('port', '', $conf);
  32. $user = V::get('user', '', $conf);
  33. $pass = V::get('pass', '', $conf);
  34. $zasob_id = V::get('zasob_id', '', $conf);
  35. $database = V::get('database', '', $conf);
  36. if ($port && $host) $host .= ":{$port}";
  37. $names = 'utf8';
  38. $db_class = 'Core_DataSource_' . ucfirst($type);
  39. Lib::loadClass($db_class);
  40. if (!class_exists($db_class)) throw new Exception("Data source class for type '{$type}' not found!");
  41. $params = array();
  42. $tdsver = V::get('tdsver', '', $conf);
  43. if (!empty($tdsver)) $params['tdsver'] = $tdsver;
  44. if (!empty($zasob_id)) $params['zasob_id'] = $zasob_id;
  45. $_instanceList[$configName] = new $db_class($host, $user, $pass, $database, $names, $params);
  46. return $_instanceList[$configName];
  47. }
  48. /**
  49. * Get database object.
  50. *
  51. * @param string $db Zasob ID or database name (require config file @see Config::getZasobConf($db))
  52. *
  53. * @returns object Database
  54. */
  55. public static function getDB($db = null) {
  56. static $_instance;
  57. if (!is_array($_instance)) {
  58. $_instance = array();
  59. }
  60. $dbConfName = 'default_db';
  61. if (is_numeric($db) && $db > 0) {
  62. $dbConfName = "zasob_{$db}";
  63. } else if ($db == 'import_db') {
  64. $dbConfName = "import_db";
  65. } else if ($db == 'test_db') {
  66. $dbConfName = "test_db";
  67. } else if ($db == 'billing_db') {
  68. $dbConfName = "billing_db";
  69. }
  70. if (!array_key_exists($dbConfName, $_instance)) {
  71. $_instance[$dbConfName] = null;
  72. Lib::loadClass('Config');
  73. $conf = Config::getConfFile($dbConfName);
  74. if ($conf) {
  75. $type = V::get('type', 'mysql', $conf);
  76. $host = V::get('host', '', $conf);
  77. $port = V::get('port', '', $conf);
  78. $user = V::get('user', '', $conf);
  79. $pass = V::get('pass', '', $conf);
  80. $zasob_id = V::get('zasob_id', '', $conf);
  81. $database = V::get('database', '', $conf);
  82. if ($port && $host) {
  83. $host .= ":{$port}";
  84. }
  85. $names = 'utf8';
  86. $db_class = 'Core_Database_' . ucfirst($type);
  87. Lib::loadClass($db_class);
  88. if (class_exists($db_class)) {
  89. $params = array();
  90. $tdsver = V::get('tdsver', '', $conf);
  91. if (!empty($tdsver)) {
  92. $params['tdsver'] = $tdsver;
  93. }
  94. if(!empty($zasob_id)) {
  95. $params['zasob_id'] = $zasob_id;
  96. }
  97. $_instance[$dbConfName] = new $db_class($host, $user, $pass, $database, $names, $params);
  98. }
  99. } else {
  100. trigger_error("Config file for db {$dbConfName} not exists!", E_USER_WARNING);
  101. }
  102. }
  103. return $_instance[$dbConfName];
  104. }
  105. public static function connect() {
  106. static $conn;
  107. if (!is_resource($conn)) {
  108. $db = self::getDB();
  109. if (!$db) {
  110. die('Config file for main DB not exists!');
  111. }
  112. $conn = $db->getConnection();
  113. }
  114. return $conn;
  115. }
  116. public static function transaction_start() {
  117. DB::query(" START TRANSACTION; ");
  118. }
  119. public static function transaction_commit() {
  120. DB::query(" COMMIT; ");
  121. }
  122. public static function transaction_rollback() {
  123. DB::query(" ROLLBACK; ");
  124. }
  125. public static function query($sql, $die_on_error = true) {
  126. $conn = self::connect();
  127. $res = mysql_query($sql, $conn);
  128. if (!$res) {
  129. if ($die_on_error) {
  130. trigger_error("query error: #".mysql_errno($conn).": ".mysql_error($conn)."\n $sql", E_USER_ERROR);
  131. die("ERROR DB: QUERY ERROR");
  132. } else {
  133. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';print_r("query error: #".mysql_errno($conn).": ".mysql_error($conn)."\n $sql");echo'</pre>';
  134. $null = null;
  135. return $null;
  136. }
  137. } else {
  138. return $res;
  139. }
  140. }
  141. public static function fetch($res) {
  142. $ret = null;
  143. if ($res) $ret = mysql_fetch_object($res);
  144. return $ret;
  145. }
  146. public static function fetch_row($res) {
  147. $ret = null;
  148. if ($res) $ret = mysql_fetch_row($res);
  149. return $ret;
  150. }
  151. public static function fetch_array($res) {
  152. $ret = null;
  153. if ($res) $ret = mysql_fetch_array($res);
  154. return $ret;
  155. }
  156. public static function fetch_assoc($res) {
  157. $ret = null;
  158. if ($res) $ret = mysql_fetch_assoc($res);
  159. return $ret;
  160. }
  161. public static function _($str) {
  162. //PHP >= 4.3.0; dodaje lewe ukoᄊniki (backslash) do nast↑pujᄆcych znak￳w: \x00, \n, \r, \, ', " and \x1a
  163. return mysql_real_escape_string($str, self::connect());
  164. }
  165. public static function error() {
  166. $conn = self::connect();
  167. return "#".mysql_errno($conn).": ".mysql_error($conn);
  168. }
  169. // Pobiera liczb↑ wierszy przetworzonych w ostatnim zapytaniu INSERT, UPDATE, REPLACE lub DELETE skojarzonym z identyfikator_poᄈᄆczenia.
  170. public static function affected_rows() {
  171. return mysql_affected_rows(self::connect());
  172. }
  173. // Zwraca ID wygenerowane dla pola z wᄈasnoᄊciᄆ AUTO_INCREMENT lub 0 jesli error
  174. public static function insert_id() {
  175. return mysql_insert_id(self::connect());
  176. }
  177. // Zwraca liczb↑ wierszy w wyniku. T↑ funkcj↑ stosuje si↑ tylko do operacji SELECT.
  178. public static function num_rows($res) {
  179. return mysql_num_rows($res);
  180. }
  181. public static function get_by_id($table, $id) {
  182. $null = null;
  183. $sql = "select p.*
  184. from `{$table}` as p
  185. where p.`ID`='{$id}'
  186. ";
  187. $res = DB::query($sql);
  188. if ($r = DB::fetch($res)) {
  189. return $r;
  190. }
  191. return $null;
  192. }
  193. /**
  194. * @returns int
  195. * 1 - changed but without add hist
  196. * 2 - changed and add hist
  197. * 0 - nothing to change
  198. * -1 - error ID not set
  199. * -2 - error id not exists in DB
  200. *
  201. * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
  202. */
  203. public static function UPDATE_OBJ($table, &$sql_obj) {
  204. if (!isset($sql_obj->ID) || $sql_obj->ID <= 0) {
  205. return -1;
  206. }
  207. $id = $sql_obj->ID;
  208. // check id record $id exists
  209. if (($curr_obj = self::get_by_id($table, $sql_obj->ID)) == null) {
  210. return -2;
  211. }
  212. // check if enything changed
  213. $changed = false;
  214. $fields_to_change = get_object_vars($sql_obj);
  215. foreach ($fields_to_change as $k => $v) {
  216. if ($k == 'ID') continue;
  217. if ($v == $curr_obj->$k) {
  218. unset($sql_obj->$k);
  219. } else {
  220. $changed = true;
  221. }
  222. }
  223. if ($changed == false) {
  224. return 0;// record not changed
  225. }
  226. $sql_arr = array();
  227. // TODO: add admin columns if exists in table - search in session
  228. $admin_col = array();
  229. $admin_col[] = 'A_RECORD_CREATE_DATE';
  230. $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
  231. // ...
  232. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  233. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  234. foreach (get_object_vars($sql_obj) as $k => $v) {
  235. $sql_arr [] = "`".$k."`=".(($v == 'NOW()')? $v : "'".self::_($v)."'");//"'".self::_($v)."'";
  236. }
  237. $sql = "update `".$table."` set ".implode(",", $sql_arr)." where `ID`='".$id."' limit 1; ";
  238. self::query( $sql );
  239. $ret = self::affected_rows();
  240. if ($ret) {
  241. $sql_obj->ID_USERS2 = $id;
  242. unset($sql_obj->ID);
  243. $new_id = self::ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  244. if ($new_id) {
  245. $ret += 1;
  246. }
  247. }
  248. return $ret;
  249. }
  250. public static function ADD_NEW_OBJ($table, &$sql_obj) {
  251. $sql_arr = array();
  252. // TODO: add admin columns if exists in table - search in session
  253. $admin_col = array();
  254. $admin_col[] = 'ID';
  255. $admin_col[] = 'A_RECORD_CREATE_DATE';
  256. $admin_col[] = 'A_RECORD_CREATE_AUTHOR';
  257. $admin_col[] = 'A_RECORD_UPDATE_DATE';
  258. $admin_col[] = 'A_RECORD_UPDATE_AUTHOR';
  259. // ...
  260. $sql_arr["`ID`"] = "NULL";// add default value for ID, NULL in all inserts
  261. if (substr($table, 0, -5) == '_HIST') {
  262. $sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
  263. $sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
  264. } else {
  265. $sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d-H:i');
  266. $sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
  267. }
  268. foreach (get_object_vars($sql_obj) as $k => $v) {
  269. $sql_arr ["`".$k."`"] = ($v == 'NOW()')? $v : "'".self::_($v)."'";
  270. }
  271. $sql = "insert into `".$table."` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
  272. self::query($sql);
  273. $ret_id = self::insert_id();
  274. if (substr($table, -5) == '_HIST') {
  275. return $ret_id;
  276. }
  277. if ($ret_id) {
  278. $sql_obj->ID_USERS2 = $ret_id;
  279. unset($sql_obj->ID);
  280. $new_id_hist = self::ADD_NEW_OBJ($table . '_HIST', $sql_obj);
  281. // error jesli nie udalo sie dodac rekordu do tabeli _HIST
  282. }
  283. return $ret_id;
  284. }
  285. }