DB.php 10 KB

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