Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

424 lines
9.7 KiB

  1. <?php
  2. require_once("dbm.php");
  3. # if PDO is avaible for mysql, use the new database abstraction
  4. # TODO: PDO is disabled for release 3.3. We need to investigate why
  5. # the update from 3.2 fails with pdo
  6. /*
  7. if(class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
  8. require_once("library/dddbl2/dddbl.php");
  9. require_once("include/dba_pdo.php");
  10. }
  11. */
  12. require_once('include/datetime.php');
  13. /**
  14. * @class MySQL database class
  15. *
  16. * For debugging, insert 'dbg(1);' anywhere in the program flow.
  17. * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
  18. * When logging, all binary info is converted to text and html entities are escaped so that
  19. * the debugging stream is safe to view within both terminals and web pages.
  20. *
  21. */
  22. if(! class_exists('dba')) {
  23. class dba {
  24. private $debug = 0;
  25. private $db;
  26. private $result;
  27. public $mysqli = true;
  28. public $connected = false;
  29. public $error = false;
  30. function __construct($server,$user,$pass,$db,$install = false) {
  31. global $a;
  32. $stamp1 = microtime(true);
  33. $server = trim($server);
  34. $user = trim($user);
  35. $pass = trim($pass);
  36. $db = trim($db);
  37. if (!(strlen($server) && strlen($user))){
  38. $this->connected = false;
  39. $this->db = null;
  40. return;
  41. }
  42. if($install) {
  43. if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
  44. if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
  45. $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
  46. $this->connected = false;
  47. $this->db = null;
  48. return;
  49. }
  50. }
  51. }
  52. if(class_exists('mysqli')) {
  53. $this->db = @new mysqli($server,$user,$pass,$db);
  54. if(! mysqli_connect_errno()) {
  55. $this->connected = true;
  56. }
  57. if (isset($a->config["system"]["db_charset"]))
  58. $this->db->set_charset($a->config["system"]["db_charset"]);
  59. }
  60. else {
  61. $this->mysqli = false;
  62. $this->db = mysql_connect($server,$user,$pass);
  63. if($this->db && mysql_select_db($db,$this->db)) {
  64. $this->connected = true;
  65. }
  66. if (isset($a->config["system"]["db_charset"]))
  67. mysql_set_charset($a->config["system"]["db_charset"], $this->db);
  68. }
  69. if(! $this->connected) {
  70. $this->db = null;
  71. if(! $install)
  72. system_unavailable();
  73. }
  74. $a->save_timestamp($stamp1, "network");
  75. }
  76. public function getdb() {
  77. return $this->db;
  78. }
  79. /**
  80. * @brief Returns the MySQL server version string
  81. *
  82. * This function discriminate between the deprecated mysql API and the current
  83. * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
  84. *
  85. * @return string
  86. */
  87. public function server_info() {
  88. if ($this->mysqli) {
  89. $return = $this->db->server_info;
  90. } else {
  91. $return = mysql_get_server_info($this->db);
  92. }
  93. return $return;
  94. }
  95. public function q($sql, $onlyquery = false) {
  96. global $a;
  97. if((! $this->db) || (! $this->connected))
  98. return false;
  99. $this->error = '';
  100. // Check the connection (This can reconnect the connection - if configured)
  101. if ($this->mysqli)
  102. $connected = $this->db->ping();
  103. else
  104. $connected = mysql_ping($this->db);
  105. $connstr = ($connected ? "Connected": "Disonnected");
  106. $stamp1 = microtime(true);
  107. if($this->mysqli)
  108. $result = @$this->db->query($sql);
  109. else
  110. $result = @mysql_query($sql,$this->db);
  111. $stamp2 = microtime(true);
  112. $duration = (float)($stamp2-$stamp1);
  113. $a->save_timestamp($stamp1, "database");
  114. if (strtolower(substr($sql, 0, 6)) != "select")
  115. $a->save_timestamp($stamp1, "database_write");
  116. if(x($a->config,'system') && x($a->config['system'],'db_log')) {
  117. if (($duration > $a->config["system"]["db_loglimit"])) {
  118. $duration = round($duration, 3);
  119. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  120. @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
  121. basename($backtrace[1]["file"])."\t".
  122. $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
  123. substr($sql, 0, 2000)."\n", FILE_APPEND);
  124. }
  125. }
  126. if($this->mysqli) {
  127. if($this->db->errno) {
  128. $this->error = $this->db->error;
  129. $this->errorno = $this->db->errno;
  130. }
  131. } elseif(mysql_errno($this->db)) {
  132. $this->error = mysql_error($this->db);
  133. $this->errorno = mysql_errno($this->db);
  134. }
  135. if(strlen($this->error)) {
  136. logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
  137. }
  138. if($this->debug) {
  139. $mesg = '';
  140. if($result === false)
  141. $mesg = 'false';
  142. elseif($result === true)
  143. $mesg = 'true';
  144. else {
  145. if($this->mysqli)
  146. $mesg = $result->num_rows . ' results' . EOL;
  147. else
  148. $mesg = mysql_num_rows($result) . ' results' . EOL;
  149. }
  150. $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
  151. . (($this->error) ? ' error: ' . $this->error : '')
  152. . EOL;
  153. logger('dba: ' . $str );
  154. }
  155. /**
  156. * If dbfail.out exists, we will write any failed calls directly to it,
  157. * regardless of any logging that may or may nor be in effect.
  158. * These usually indicate SQL syntax errors that need to be resolved.
  159. */
  160. if($result === false) {
  161. logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
  162. if(file_exists('dbfail.out'))
  163. file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
  164. }
  165. if(($result === true) || ($result === false))
  166. return $result;
  167. if ($onlyquery) {
  168. $this->result = $result;
  169. return true;
  170. }
  171. $r = array();
  172. if($this->mysqli) {
  173. if($result->num_rows) {
  174. while($x = $result->fetch_array(MYSQLI_ASSOC))
  175. $r[] = $x;
  176. $result->free_result();
  177. }
  178. }
  179. else {
  180. if(mysql_num_rows($result)) {
  181. while($x = mysql_fetch_array($result, MYSQL_ASSOC))
  182. $r[] = $x;
  183. mysql_free_result($result);
  184. }
  185. }
  186. //$a->save_timestamp($stamp1, "database");
  187. if($this->debug)
  188. logger('dba: ' . printable(print_r($r, true)));
  189. return($r);
  190. }
  191. public function qfetch() {
  192. $x = false;
  193. if ($this->result)
  194. if($this->mysqli) {
  195. if($this->result->num_rows)
  196. $x = $this->result->fetch_array(MYSQLI_ASSOC);
  197. } else {
  198. if(mysql_num_rows($this->result))
  199. $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
  200. }
  201. return($x);
  202. }
  203. public function qclose() {
  204. if ($this->result)
  205. if($this->mysqli) {
  206. $this->result->free_result();
  207. } else {
  208. mysql_free_result($this->result);
  209. }
  210. }
  211. public function dbg($dbg) {
  212. $this->debug = $dbg;
  213. }
  214. public function escape($str) {
  215. if($this->db && $this->connected) {
  216. if($this->mysqli)
  217. return @$this->db->real_escape_string($str);
  218. else
  219. return @mysql_real_escape_string($str,$this->db);
  220. }
  221. }
  222. function connected() {
  223. if ($this->mysqli)
  224. $connected = $this->db->ping();
  225. else
  226. $connected = mysql_ping($this->db);
  227. return $connected;
  228. }
  229. function __destruct() {
  230. if ($this->db)
  231. if($this->mysqli)
  232. $this->db->close();
  233. else
  234. mysql_close($this->db);
  235. }
  236. }}
  237. if(! function_exists('printable')) {
  238. function printable($s) {
  239. $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
  240. $s = str_replace("\x00",'.',$s);
  241. if(x($_SERVER,'SERVER_NAME'))
  242. $s = escape_tags($s);
  243. return $s;
  244. }}
  245. // Procedural functions
  246. if(! function_exists('dbg')) {
  247. function dbg($state) {
  248. global $db;
  249. if($db)
  250. $db->dbg($state);
  251. }}
  252. if(! function_exists('dbesc')) {
  253. function dbesc($str) {
  254. global $db;
  255. if($db && $db->connected)
  256. return($db->escape($str));
  257. else
  258. return(str_replace("'","\\'",$str));
  259. }}
  260. // Function: q($sql,$args);
  261. // Description: execute SQL query with printf style args.
  262. // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
  263. // 'user', 1);
  264. if(! function_exists('q')) {
  265. function q($sql) {
  266. global $db;
  267. $args = func_get_args();
  268. unset($args[0]);
  269. if($db && $db->connected) {
  270. $stmt = @vsprintf($sql,$args); // Disabled warnings
  271. //logger("dba: q: $stmt", LOGGER_ALL);
  272. if($stmt === false)
  273. logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
  274. return $db->q($stmt);
  275. }
  276. /**
  277. *
  278. * This will happen occasionally trying to store the
  279. * session data after abnormal program termination
  280. *
  281. */
  282. logger('dba: no database: ' . print_r($args,true));
  283. return false;
  284. }}
  285. /**
  286. * @brief Performs a query with "dirty reads"
  287. *
  288. * By doing dirty reads (reading uncommitted data) no locks are performed
  289. * This function can be used to fetch data that doesn't need to be reliable.
  290. *
  291. * @param $args Query parameters (1 to N parameters of different types)
  292. * @return array Query array
  293. */
  294. function qu($sql) {
  295. global $db;
  296. $args = func_get_args();
  297. unset($args[0]);
  298. if($db && $db->connected) {
  299. $stmt = @vsprintf($sql,$args); // Disabled warnings
  300. if($stmt === false)
  301. logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
  302. $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
  303. $retval = $db->q($stmt);
  304. $db->q("COMMIT;");
  305. return $retval;
  306. }
  307. /**
  308. *
  309. * This will happen occasionally trying to store the
  310. * session data after abnormal program termination
  311. *
  312. */
  313. logger('dba: no database: ' . print_r($args,true));
  314. return false;
  315. }
  316. /**
  317. *
  318. * Raw db query, no arguments
  319. *
  320. */
  321. if(! function_exists('dbq')) {
  322. function dbq($sql) {
  323. global $db;
  324. if($db && $db->connected)
  325. $ret = $db->q($sql);
  326. else
  327. $ret = false;
  328. return $ret;
  329. }}
  330. // Caller is responsible for ensuring that any integer arguments to
  331. // dbesc_array are actually integers and not malformed strings containing
  332. // SQL injection vectors. All integer array elements should be specifically
  333. // cast to int to avoid trouble.
  334. if(! function_exists('dbesc_array_cb')) {
  335. function dbesc_array_cb(&$item, $key) {
  336. if(is_string($item))
  337. $item = dbesc($item);
  338. }}
  339. if(! function_exists('dbesc_array')) {
  340. function dbesc_array(&$arr) {
  341. if(is_array($arr) && count($arr)) {
  342. array_walk($arr,'dbesc_array_cb');
  343. }
  344. }}
  345. function dba_timer() {
  346. return microtime(true);
  347. }