mssql.class.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. <?php
  2. /* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2008 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2007 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2007 Simon Desee <simon@dedisoft.com>
  6. * Copyright (C) 2015 Cedric GROSS <c.gross@kreiz-it.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/core/db/mssql.class.php
  23. * \brief Fichier de la classe permettant de gerer une base MSSQL
  24. */
  25. require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
  26. /**
  27. * Classe de gestion de la database de dolibarr
  28. */
  29. class DoliDBMssql extends DoliDB
  30. {
  31. //! Database type
  32. public $type='mssql';
  33. //! Database label
  34. const LABEL='MSSQL';
  35. //! Charset used to force charset when creating database
  36. public $forcecharset='latin1'; // Can't be static as it may be forced with a dynamic value
  37. //! Collate used to force collate when creating database
  38. public $forcecollate='latin1_swedish_ci'; // Can't be static as it may be forced with a dynamic value
  39. //! Version min database
  40. const VERSIONMIN='2000';
  41. /** @var resource Resultset of last query */
  42. private $_results;
  43. /**
  44. * Constructor.
  45. * This create an opened connexion to a database server and eventually to a database
  46. *
  47. * @param string $type Type of database (mysql, pgsql...)
  48. * @param string $host Address of database server
  49. * @param string $user Nom de l'utilisateur autorise
  50. * @param string $pass Mot de passe
  51. * @param string $name Nom de la database
  52. * @param int $port Port of database server
  53. */
  54. public function __construct($type, $host, $user, $pass, $name = '', $port = 0)
  55. {
  56. global $langs;
  57. $this->database_user=$user;
  58. $this->database_host=$host;
  59. $this->database_port=$port;
  60. $this->transaction_opened=0;
  61. if (! function_exists("mssql_connect"))
  62. {
  63. $this->connected = false;
  64. $this->ok = false;
  65. $this->error="Mssql PHP functions for using MSSql driver are not available in this version of PHP";
  66. dol_syslog(get_class($this)."::DoliDBMssql : MSsql PHP functions for using MSsql driver are not available in this version of PHP", LOG_ERR);
  67. return $this->ok;
  68. }
  69. if (! $host)
  70. {
  71. $this->connected = false;
  72. $this->ok = false;
  73. $this->error=$langs->trans("ErrorWrongHostParameter");
  74. dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect, wrong host parameters", LOG_ERR);
  75. return $this->ok;
  76. }
  77. // Essai connexion serveur
  78. $this->db = $this->connect($host, $user, $pass, $name, $port);
  79. if ($this->db)
  80. {
  81. // Si client connecte avec charset different de celui de la base Dolibarr
  82. // (La base Dolibarr a ete forcee en this->forcecharset a l'install)
  83. $this->connected = true;
  84. $this->ok = true;
  85. }
  86. else
  87. {
  88. // host, login ou password incorrect
  89. $this->connected = false;
  90. $this->ok = false;
  91. $this->error=mssql_get_last_message();
  92. dol_syslog(get_class($this)."::DoliDBMssql : Erreur Connect mssql_get_last_message=".$this->error, LOG_ERR);
  93. }
  94. // Si connexion serveur ok et si connexion base demandee, on essaie connexion base
  95. if ($this->connected && $name)
  96. {
  97. if ($this->select_db($name))
  98. {
  99. $this->database_selected = true;
  100. $this->database_name = $name;
  101. $this->ok = true;
  102. }
  103. else
  104. {
  105. $this->database_selected = false;
  106. $this->database_name = '';
  107. $this->ok = false;
  108. $this->error=$this->error();
  109. dol_syslog(get_class($this)."::DoliDBMssql : Erreur Select_db ".$this->error, LOG_ERR);
  110. }
  111. }
  112. else
  113. {
  114. // Pas de selection de base demandee, ok ou ko
  115. $this->database_selected = false;
  116. }
  117. return $this->ok;
  118. }
  119. /**
  120. * Convert a SQL request in Mysql syntax to native syntax
  121. *
  122. * @param string $line SQL request line to convert
  123. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  124. * @return string SQL request line converted
  125. */
  126. public static function convertSQLFromMysql($line, $type = 'ddl')
  127. {
  128. return $line;
  129. }
  130. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  131. /**
  132. * Select a database
  133. *
  134. * @param string $database Name of database
  135. * @return boolean true if OK, false if KO
  136. */
  137. public function select_db($database)
  138. {
  139. // phpcs:enable
  140. return @mssql_select_db($database, $this->db);
  141. }
  142. /**
  143. * Connexion to server
  144. *
  145. * @param string $host database server host
  146. * @param string $login login
  147. * @param string $passwd password
  148. * @param string $name name of database (not used for mysql, used for pgsql)
  149. * @param int $port Port of database server
  150. * @return false|resource|true Database access handler
  151. * @see close()
  152. */
  153. public function connect($host, $login, $passwd, $name, $port = 0)
  154. {
  155. dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name");
  156. $newhost=$host;
  157. if ($port) $newhost.=':'.$port;
  158. $this->db = @mssql_connect($newhost, $login, $passwd);
  159. //force les enregistrement en latin1 si la base est en utf8 par defaut
  160. // Supprime car plante sur mon PHP-Mysql. De plus, la base est forcement en latin1 avec
  161. // les nouvelles version de Dolibarr car force par l'install Dolibarr.
  162. //$this->query('SET NAMES '.$this->forcecharset);
  163. //print "Resultat fonction connect: ".$this->db;
  164. $set_options=array('SET ANSI_PADDING ON;',
  165. "SET ANSI_NULLS ON;",
  166. "SET ANSI_WARNINGS ON;",
  167. "SET ARITHABORT ON;",
  168. "SET CONCAT_NULL_YIELDS_NULL ON;",
  169. "SET QUOTED_IDENTIFIER ON;"
  170. );
  171. mssql_query(implode(' ', $set_options), $this->db);
  172. return $this->db;
  173. }
  174. /**
  175. * Return version of database server
  176. *
  177. * @return string Version string
  178. */
  179. public function getVersion()
  180. {
  181. $resql=$this->query("SELECT @@VERSION");
  182. if ($resql)
  183. {
  184. $version=$this->fetch_array($resql);
  185. return $version['computed'];
  186. }
  187. else return '';
  188. }
  189. /**
  190. * Return version of database client driver
  191. *
  192. * @return string Version string
  193. */
  194. public function getDriverInfo()
  195. {
  196. return 'php mssql driver';
  197. }
  198. /**
  199. * Close database connexion
  200. *
  201. * @return bool True if disconnect successfull, false otherwise
  202. * @see connect()
  203. */
  204. public function close()
  205. {
  206. if ($this->db) {
  207. if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
  208. $this->connected=false;
  209. return mssql_close($this->db);
  210. }
  211. return false;
  212. }
  213. /**
  214. * Start transaction
  215. *
  216. * @return bool true if transaction successfuly opened or already opened, false if error
  217. */
  218. public function begin()
  219. {
  220. $res=mssql_query('select @@TRANCOUNT');
  221. $this->transaction_opened=mssql_result($res, 0, 0);
  222. if ($this->transaction_opened == 0)
  223. {
  224. //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTIONS ON' generate also a mess
  225. $ret=mssql_query("SET IMPLICIT_TRANSACTIONS OFF;BEGIN TRANSACTION;", $this->db);
  226. if ($ret)
  227. {
  228. dol_syslog("BEGIN Transaction", LOG_DEBUG);
  229. }
  230. return $ret;
  231. }
  232. else
  233. {
  234. return true;
  235. }
  236. }
  237. /**
  238. * Validate a database transaction
  239. *
  240. * @param string $log Add more log to default log line
  241. * @return bool true if validation is OK or transaction level no started, false if ERROR
  242. */
  243. public function commit($log = '')
  244. {
  245. $res=mssql_query('select @@TRANCOUNT');
  246. $this->transaction_opened=mssql_result($res, 0, 0);
  247. if ($this->transaction_opened == 1)
  248. {
  249. //return 1; //There is a mess with auto_commit and 'SET IMPLICIT_TRANSACTION ON' generate also a mess
  250. $ret=mssql_query("COMMIT TRANSACTION", $this->db);
  251. if ($ret)
  252. {
  253. dol_syslog("COMMIT Transaction", LOG_DEBUG);
  254. return true;
  255. }
  256. else
  257. {
  258. return false;
  259. }
  260. }
  261. elseif ($this->transaction_opened > 1)
  262. {
  263. return true;
  264. }
  265. trigger_error("Commit requested but no transaction remain");
  266. return false;
  267. }
  268. /**
  269. * Annulation d'une transaction et retour aux anciennes valeurs
  270. *
  271. * @param string $log Add more log to default log line
  272. * @return bool true si annulation ok ou transaction non ouverte, false en cas d'erreur
  273. */
  274. public function rollback($log = '')
  275. {
  276. $res=mssql_query('select @@TRANCOUNT');
  277. $this->transaction_opened=mssql_result($res, 0, 0);
  278. if ($this->transaction_opened == 1)
  279. {
  280. $ret=mssql_query("ROLLBACK TRANSACTION", $this->db);
  281. dol_syslog("ROLLBACK Transaction".($log?' '.$log:''), LOG_DEBUG);
  282. return $ret;
  283. }
  284. elseif ($this->transaction_opened > 1)
  285. {
  286. return true;
  287. }
  288. trigger_error("Rollback requested but no transaction remain");
  289. return false;
  290. }
  291. /**
  292. * Execute a SQL request and return the resultset
  293. *
  294. * @param string $query SQL query string
  295. * @param int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
  296. * Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
  297. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  298. * @return false|resource|true Resultset of answer
  299. */
  300. public function query($query, $usesavepoint = 0, $type = 'auto')
  301. {
  302. $query = trim($query);
  303. if (preg_match('/^--/', $query)) return true;
  304. // Conversion syntaxe MySql vers MSDE.
  305. $query = str_ireplace("now()", "getdate()", $query);
  306. // Erreur SQL: cannot update timestamp field
  307. $query = str_ireplace(", tms = tms", "", $query);
  308. $query=preg_replace("/([. ,\t(])(percent|file|public)([. ,=\t)])/", "$1[$2]$3", $query);
  309. if ($type=="auto" || $type='dml')
  310. {
  311. $query=preg_replace('/AUTO_INCREMENT/i', 'IDENTITY', $query);
  312. $query=preg_replace('/double/i', 'float', $query);
  313. $query=preg_replace('/float\((.*)\)/', 'numeric($1)', $query);
  314. $query=preg_replace('/([ \t])unsigned|IF NOT EXISTS[ \t]/i', '$1', $query);
  315. $query=preg_replace('/([ \t])(MEDIUM|TINY|LONG){0,1}TEXT([ \t,])/i', "$1VARCHAR(MAX)$3", $query);
  316. $matches=array();
  317. $original_query='';
  318. if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+(?:(UNIQUE)|INDEX)\h+(?:INDEX)?\h*(\w+?)\h*\((.+)\)/is', $query, $matches))
  319. {
  320. $original_query=$query;
  321. $query="CREATE ".trim($matches[2])." INDEX [".trim($matches[3])."] ON [".trim($matches[1])."] (".trim($matches[4]).")";
  322. if ($matches[2]) {
  323. //check if columun is nullable cause Sql server only allow 1 null value if unique index.
  324. $fields=explode(",", trim($matches[4]));
  325. $fields_clear=array_map('trim', $fields);
  326. $infos=$this->GetFieldInformation(trim($matches[1]), $fields_clear);
  327. $query_comp=array();
  328. foreach($infos as $fld) {
  329. if ($fld->IS_NULLABLE == 'YES') {
  330. $query_comp[]=$fld->COLUMN_NAME." IS NOT NULL";
  331. }
  332. }
  333. if (! empty($query_comp))
  334. $query.=" WHERE ".implode(" AND ", $query_comp);
  335. }
  336. }
  337. else
  338. {
  339. if (preg_match('/ALTER TABLE\h+(\w+?)\h+ADD\h+PRIMARY\h+KEY\h+(\w+?)\h*\((.+)\)/is', $query, $matches))
  340. {
  341. $original_query=$query;
  342. $query="ALTER TABLE [".$matches[1]."] ADD CONSTRAINT [".$matches[2]."] PRIMARY KEY CLUSTERED (".$matches[3].")";
  343. }
  344. }
  345. }
  346. if ($type=="auto" || $type='ddl')
  347. {
  348. $itemfound = stripos($query, " limit ");
  349. if ($itemfound !== false) {
  350. // Extraire le nombre limite
  351. $number = stristr($query, " limit ");
  352. $number = substr($number, 7);
  353. // Inserer l'instruction TOP et le nombre limite
  354. $query = str_ireplace("select ", "select top ".$number." ", $query);
  355. // Supprimer l'instruction MySql
  356. $query = str_ireplace(" limit ".$number, "", $query);
  357. }
  358. $itemfound = stripos($query, " week(");
  359. if ($itemfound !== false) {
  360. // Recreer une requete sans instruction Mysql
  361. $positionMySql = stripos($query, " week(");
  362. $newquery = substr($query, 0, $positionMySql);
  363. // Recuperer la date passee en parametre
  364. $extractvalue = stristr($query, " week(");
  365. $extractvalue = substr($extractvalue, 6);
  366. $positionMySql = stripos($extractvalue, ")");
  367. // Conserver la fin de la requete
  368. $endofquery = substr($extractvalue, $positionMySql);
  369. $extractvalue = substr($extractvalue, 0, $positionMySql);
  370. // Remplacer l'instruction MySql en Sql Server
  371. // Inserer la date en parametre et le reste de la requete
  372. $query = $newquery." DATEPART(week, ".$extractvalue.$endofquery;
  373. }
  374. if (preg_match('/^insert\h+(?:INTO)?\h*(\w+?)\h*\(.*\b(?:row)?id\b.*\)\h+VALUES/i', $query, $matches))
  375. {
  376. //var_dump($query);
  377. //var_dump($matches);
  378. //if (stripos($query,'llx_c_departements') !== false) var_dump($query);
  379. $sql='SET IDENTITY_INSERT ['.trim($matches[1]).'] ON;';
  380. @mssql_query($sql, $this->db);
  381. $post_query='SET IDENTITY_INSERT ['.trim($matches[1]).'] OFF;';
  382. }
  383. }
  384. //print "<!--".$query."-->";
  385. if (! in_array($query, array('BEGIN','COMMIT','ROLLBACK')))
  386. {
  387. $SYSLOG_SQL_LIMIT = 10000; // limit log to 10kb per line to limit DOS attacks
  388. dol_syslog('sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
  389. }
  390. if (! $this->database_name)
  391. {
  392. // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
  393. $ret = mssql_query($query, $this->db);
  394. }
  395. else
  396. {
  397. $ret = mssql_query($query, $this->db);
  398. }
  399. if (!empty($post_query))
  400. {
  401. @mssql_query($post_query, $this->db);
  402. }
  403. if (! preg_match("/^COMMIT/i", $query) && ! preg_match("/^ROLLBACK/i", $query))
  404. {
  405. // Si requete utilisateur, on la sauvegarde ainsi que son resultset
  406. if (! $ret)
  407. {
  408. $result = mssql_query("SELECT @@ERROR as code", $this->db);
  409. $row = mssql_fetch_array($result);
  410. $this->lastqueryerror = $query;
  411. $this->lasterror = $this->error();
  412. $this->lasterrno = $row["code"];
  413. dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
  414. if ($original_query) dol_syslog(get_class($this)."::query SQL Original query: ".$original_query, LOG_ERR);
  415. dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterror." (".$this->lasterrno.")", LOG_ERR);
  416. }
  417. $this->lastquery=$query;
  418. $this->_results = $ret;
  419. }
  420. return $ret;
  421. }
  422. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  423. /**
  424. * Renvoie la ligne courante (comme un objet) pour le curseur resultset
  425. *
  426. * @param resource $resultset Curseur de la requete voulue
  427. * @return object|false Object result line or false if KO or end of cursor
  428. */
  429. public function fetch_object($resultset)
  430. {
  431. // phpcs:enable
  432. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  433. if (! is_resource($resultset)) { $resultset=$this->_results; }
  434. return mssql_fetch_object($resultset);
  435. }
  436. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  437. /**
  438. * Return datas as an array
  439. *
  440. * @param resource $resultset Resultset of request
  441. * @return array|false Array or false if KO or end of cursor
  442. */
  443. public function fetch_array($resultset)
  444. {
  445. // phpcs:enable
  446. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  447. if (! is_resource($resultset)) { $resultset=$this->_results; }
  448. return mssql_fetch_array($resultset);
  449. }
  450. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  451. /**
  452. * Return datas as an array
  453. *
  454. * @param resource $resultset Resultset of request
  455. * @return array|false Array or false if KO or end of cursor
  456. */
  457. public function fetch_row($resultset)
  458. {
  459. // phpcs:enable
  460. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  461. if (! is_resource($resultset)) { $resultset=$this->_results; }
  462. return @mssql_fetch_row($resultset);
  463. }
  464. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  465. /**
  466. * Return number of lines for result of a SELECT
  467. *
  468. * @param resource $resultset Resulset of requests
  469. * @return int Nb of lines
  470. * @see affected_rows()
  471. */
  472. public function num_rows($resultset)
  473. {
  474. // phpcs:enable
  475. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  476. if (! is_resource($resultset)) { $resultset=$this->_results; }
  477. return mssql_num_rows($resultset);
  478. }
  479. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  480. /**
  481. * Return the number of lines in the result of a request INSERT, DELETE or UPDATE
  482. *
  483. * @param resource $resultset Curseur de la requete voulue
  484. * @return int Number of lines
  485. * @see num_rows()
  486. */
  487. public function affected_rows($resultset)
  488. {
  489. // phpcs:enable
  490. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  491. if (! is_resource($resultset)) { $resultset=$this->_results; }
  492. // mssql necessite un link de base pour cette fonction contrairement
  493. // a pqsql qui prend un resultset
  494. $rsRows = mssql_query("select @@rowcount as rows", $this->db);
  495. return mssql_result($rsRows, 0, "rows");
  496. //return mssql_affected_rows($this->db);
  497. }
  498. /**
  499. * Free last resultset used.
  500. *
  501. * @param resource $resultset Curseur de la requete voulue
  502. * @return bool
  503. */
  504. public function free($resultset = null)
  505. {
  506. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  507. if (! is_resource($resultset)) { $resultset=$this->_results; }
  508. // Si resultset en est un, on libere la memoire
  509. if (is_resource($resultset)) mssql_free_result($resultset);
  510. }
  511. /**
  512. * Escape a string to insert data
  513. *
  514. * @param string $stringtoencode String to escape
  515. * @return string String escaped
  516. */
  517. public function escape($stringtoencode)
  518. {
  519. return addslashes($stringtoencode);
  520. }
  521. /**
  522. * Convert (by PHP) a GM Timestamp date into a PHP server TZ to insert into a date field.
  523. * Function to use to build INSERT, UPDATE or WHERE predica
  524. *
  525. * @param string $param Date TMS to convert
  526. * @return string Date in a string YYYY-MM-DD HH:MM:SS
  527. */
  528. public function idate($param)
  529. {
  530. return dol_print_date($param, "%Y-%m-%d %H:%M:%S");
  531. }
  532. /**
  533. * Return generic error code of last operation.
  534. *
  535. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  536. */
  537. public function errno()
  538. {
  539. if (! $this->connected)
  540. {
  541. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  542. return 'DB_ERROR_FAILED_TO_CONNECT';
  543. }
  544. else
  545. {
  546. // Constants to convert a MSSql error code to a generic Dolibarr error code
  547. $errorcode_map = array(
  548. 1004 => 'DB_ERROR_CANNOT_CREATE',
  549. 1005 => 'DB_ERROR_CANNOT_CREATE',
  550. 1006 => 'DB_ERROR_CANNOT_CREATE',
  551. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  552. 1008 => 'DB_ERROR_CANNOT_DROP',
  553. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  554. 1046 => 'DB_ERROR_NODBSELECTED',
  555. 1048 => 'DB_ERROR_CONSTRAINT',
  556. 2714 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
  557. 1051 => 'DB_ERROR_NOSUCHTABLE',
  558. 1054 => 'DB_ERROR_NOSUCHFIELD',
  559. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  560. 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  561. 2627 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  562. 102 => 'DB_ERROR_SYNTAX',
  563. 8120 => 'DB_ERROR_GROUP_BY_SYNTAX',
  564. 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  565. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  566. 1091 => 'DB_ERROR_NOSUCHFIELD',
  567. 1100 => 'DB_ERROR_NOT_LOCKED',
  568. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  569. 1146 => 'DB_ERROR_NOSUCHTABLE',
  570. 1216 => 'DB_ERROR_NO_PARENT',
  571. 1217 => 'DB_ERROR_CHILD_EXISTS',
  572. 1451 => 'DB_ERROR_CHILD_EXISTS',
  573. 1913 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS'
  574. );
  575. if (isset($errorcode_map[$this->lasterrno]))
  576. {
  577. return $errorcode_map[$this->lasterrno];
  578. }
  579. $errno=$this->lasterrno;
  580. return ($errno?'DB_ERROR_'.$errno:'0');
  581. }
  582. }
  583. /**
  584. * Return description of last error
  585. *
  586. * @return string Error text
  587. */
  588. public function error()
  589. {
  590. if (! $this->connected) {
  591. // Si il y a eu echec de connexion, $this->db n'est pas valide pour mssql_get_last_message.
  592. return 'Not connected. Check setup parameters in conf/conf.php file and your mssql client and server versions';
  593. }
  594. else {
  595. return mssql_get_last_message();
  596. }
  597. }
  598. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  599. /**
  600. * Get last ID after an insert INSERT
  601. *
  602. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  603. * @param string $fieldid Field name
  604. * @return int Id of row or -1 on error
  605. */
  606. public function last_insert_id($tab, $fieldid = 'rowid')
  607. {
  608. // phpcs:enable
  609. $res = $this->query("SELECT @@IDENTITY as id");
  610. if ($res && $data = $this->fetch_array($res))
  611. {
  612. return $data["id"];
  613. }
  614. else
  615. {
  616. return -1;
  617. }
  618. }
  619. /**
  620. * Encrypt sensitive data in database
  621. * Warning: This function includes the escape, so it must use direct value
  622. *
  623. * @param string $fieldorvalue Field name or value to encrypt
  624. * @param int $withQuotes Return string with quotes
  625. * @return string XXX(field) or XXX('value') or field or 'value'
  626. */
  627. public function encrypt($fieldorvalue, $withQuotes = 0)
  628. {
  629. global $conf;
  630. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  631. $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
  632. //Encryption key
  633. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
  634. $return = $fieldorvalue;
  635. return ($withQuotes?"'":"").$this->escape($return).($withQuotes?"'":"");
  636. }
  637. /**
  638. * Decrypt sensitive data in database
  639. *
  640. * @param string $value Value to decrypt
  641. * @return string Decrypted value if used
  642. */
  643. public function decrypt($value)
  644. {
  645. global $conf;
  646. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  647. $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0);
  648. //Encryption key
  649. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
  650. $return = $value;
  651. return $return;
  652. }
  653. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  654. /**
  655. * Return connexion ID
  656. *
  657. * @return string Id connexion
  658. */
  659. public function DDLGetConnectId()
  660. {
  661. // phpcs:enable
  662. $resql=$this->query('SELECT CONNECTION_ID()');
  663. if ($resql)
  664. {
  665. $row=$this->fetch_row($resql);
  666. return $row[0];
  667. }
  668. else return '?';
  669. }
  670. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  671. /**
  672. * Create a new database
  673. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  674. * We force to create database with charset this->forcecharset and collate this->forcecollate
  675. *
  676. * @param string $database Database name to create
  677. * @param string $charset Charset used to store data
  678. * @param string $collation Charset used to sort data
  679. * @param string $owner Username of database owner
  680. * @return false|resource|true resource defined if OK, false if KO
  681. */
  682. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  683. {
  684. // phpcs:enable
  685. /*if (empty($charset)) $charset=$this->forcecharset;
  686. if (empty($collation)) $collation=$this->forcecollate;
  687. */
  688. $sql = 'CREATE DATABASE '.$this->EscapeFieldName($database);
  689. //TODO: Check if we need to force a charset
  690. //$sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation;
  691. $ret=$this->query($sql);
  692. $this->select_db($database);
  693. $sql="CREATE USER [$owner] FOR LOGIN [$owner]";
  694. mssql_query($sql, $this->db);
  695. $sql="ALTER ROLE [db_owner] ADD MEMBER [$owner]";
  696. mssql_query($sql, $this->db);
  697. $sql="ALTER DATABASE [$database] SET ANSI_NULL_DEFAULT ON;";
  698. @mssql_query($sql, $this->db);
  699. $sql="ALTER DATABASE [$database] SET ANSI_NULL ON;";
  700. @mssql_query($sql, $this->db);
  701. return $ret;
  702. }
  703. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  704. /**
  705. * List tables into a database
  706. *
  707. * @param string $database Name of database
  708. * @param string $table Nmae of table filter ('xxx%')
  709. * @return array List of tables in an array
  710. */
  711. public function DDLListTables($database, $table = '')
  712. {
  713. // phpcs:enable
  714. $this->_results = mssql_list_tables($database, $this->db);
  715. return $this->_results;
  716. }
  717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  718. /**
  719. * List information of columns into a table.
  720. *
  721. * @param string $table Name of table
  722. * @return array Tableau des informations des champs de la table
  723. */
  724. public function DDLInfoTable($table)
  725. {
  726. // phpcs:enable
  727. // FIXME: Dummy method
  728. // TODO: Implement
  729. // May help: https://stackoverflow.com/questions/600446/sql-server-how-do-you-return-the-column-names-from-a-table
  730. $infotables=array();
  731. return $infotables;
  732. }
  733. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  734. /**
  735. * Create a table into database
  736. *
  737. * @param string $table Nom de la table
  738. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  739. * @param string $primary_key Nom du champ qui sera la clef primaire
  740. * @param string $type Type de la table
  741. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  742. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  743. * @param array $keys Tableau des champs cles noms => valeur
  744. * @return int <0 if KO, >=0 if OK
  745. */
  746. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  747. {
  748. // phpcs:enable
  749. // FIXME: $fulltext_keys parameter is unused
  750. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  751. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  752. $sql = "create table ".$table."(";
  753. $i=0;
  754. foreach($fields as $field_name => $field_desc)
  755. {
  756. $sqlfields[$i] = $field_name." ";
  757. $sqlfields[$i] .= $field_desc['type'];
  758. if( preg_match("/^[^\s]/i", $field_desc['value']))
  759. $sqlfields[$i] .= "(".$field_desc['value'].")";
  760. elseif( preg_match("/^[^\s]/i", $field_desc['attribute']))
  761. $sqlfields[$i] .= " ".$field_desc['attribute'];
  762. elseif( preg_match("/^[^\s]/i", $field_desc['default']))
  763. {
  764. if(preg_match("/null/i", $field_desc['default']))
  765. $sqlfields[$i] .= " default ".$field_desc['default'];
  766. else
  767. $sqlfields[$i] .= " default '".$field_desc['default']."'";
  768. }
  769. elseif (preg_match("/^[^\s]/i", $field_desc['null']))
  770. $sqlfields[$i] .= " ".$field_desc['null'];
  771. elseif (preg_match("/^[^\s]/i", $field_desc['extra']))
  772. $sqlfields[$i] .= " ".$field_desc['extra'];
  773. $i++;
  774. }
  775. if($primary_key != "")
  776. $pk = "primary key(".$primary_key.")";
  777. if(is_array($unique_keys))
  778. {
  779. $i = 0;
  780. foreach($unique_keys as $key => $value)
  781. {
  782. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
  783. $i++;
  784. }
  785. }
  786. if(is_array($keys))
  787. {
  788. $i = 0;
  789. foreach($keys as $key => $value)
  790. {
  791. $sqlk[$i] = "KEY ".$key." (".$value.")";
  792. $i++;
  793. }
  794. }
  795. $sql .= implode(',', $sqlfields);
  796. if($primary_key != "")
  797. $sql .= ",".$pk;
  798. if(is_array($unique_keys))
  799. $sql .= ",".implode(',', $sqluq);
  800. if(is_array($keys))
  801. $sql .= ",".implode(',', $sqlk);
  802. $sql .=") type=".$type;
  803. dol_syslog($sql);
  804. if(! $this -> query($sql))
  805. return -1;
  806. else
  807. return 1;
  808. }
  809. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  810. /**
  811. * Drop a table into database
  812. *
  813. * @param string $table Name of table
  814. * @return int <0 if KO, >=0 if OK
  815. */
  816. public function DDLDropTable($table)
  817. {
  818. // phpcs:enable
  819. $sql = "DROP TABLE ".$table;
  820. if (! $this->query($sql))
  821. return -1;
  822. else
  823. return 1;
  824. }
  825. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  826. /**
  827. * Return a pointer of line with description of a table or field
  828. *
  829. * @param string $table Name of table
  830. * @param string $field Optionnel : Name of field if we want description of field
  831. * @return false|resource|true Resource
  832. */
  833. public function DDLDescTable($table, $field = "")
  834. {
  835. // phpcs:enable
  836. $sql="DESC ".$table." ".$field;
  837. dol_syslog($sql);
  838. $this->_results = $this->query($sql);
  839. return $this->_results;
  840. }
  841. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  842. /**
  843. * Create a new field into table
  844. *
  845. * @param string $table Name of table
  846. * @param string $field_name Name of field to add
  847. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  848. * @param string $field_position Optionnel ex.: "after champtruc"
  849. * @return int <0 if KO, >0 if OK
  850. */
  851. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  852. {
  853. // phpcs:enable
  854. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  855. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  856. $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
  857. $sql .= $field_desc['type'];
  858. if( preg_match("/^[^\s]/i", $field_desc['value']))
  859. $sql .= "(".$field_desc['value'].")";
  860. if( preg_match("/^[^\s]/i", $field_desc['attribute']))
  861. $sql .= " ".$field_desc['attribute'];
  862. if( preg_match("/^[^\s]/i", $field_desc['null']))
  863. $sql .= " ".$field_desc['null'];
  864. if( preg_match("/^[^\s]/i", $field_desc['default']))
  865. if(preg_match("/null/i", $field_desc['default']))
  866. $sql .= " default ".$field_desc['default'];
  867. else
  868. $sql .= " default '".$field_desc['default']."'";
  869. if( preg_match("/^[^\s]/i", $field_desc['extra']))
  870. $sql .= " ".$field_desc['extra'];
  871. $sql .= " ".$field_position;
  872. if(! $this -> query($sql))
  873. return -1;
  874. else
  875. return 1;
  876. }
  877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  878. /**
  879. * Update format of a field into a table
  880. *
  881. * @param string $table Name of table
  882. * @param string $field_name Name of field to modify
  883. * @param string $field_desc Array with description of field format
  884. * @return int <0 if KO, >0 if OK
  885. */
  886. public function DDLUpdateField($table, $field_name, $field_desc)
  887. {
  888. // phpcs:enable
  889. $sql = "ALTER TABLE ".$table;
  890. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  891. if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
  892. $sql.="(".$field_desc['value'].")";
  893. }
  894. dol_syslog($sql, LOG_DEBUG);
  895. if (! $this->query($sql))
  896. return -1;
  897. else
  898. return 1;
  899. }
  900. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  901. /**
  902. * Drop a field from table
  903. *
  904. * @param string $table Name of table
  905. * @param string $field_name Name of field to drop
  906. * @return int <0 if KO, >0 if OK
  907. */
  908. public function DDLDropField($table, $field_name)
  909. {
  910. // phpcs:enable
  911. $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
  912. dol_syslog($sql, LOG_DEBUG);
  913. if (! $this->query($sql))
  914. {
  915. $this->error=$this->lasterror();
  916. return -1;
  917. }
  918. else return 1;
  919. }
  920. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  921. /**
  922. * Create a user and privileges to connect to database (even if database does not exists yet)
  923. *
  924. * @param string $dolibarr_main_db_host Ip serveur
  925. * @param string $dolibarr_main_db_user Nom user a creer
  926. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  927. * @param string $dolibarr_main_db_name Database name where user must be granted
  928. * @return int <0 if KO, >=0 if OK
  929. */
  930. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  931. {
  932. // phpcs:enable
  933. $sql = "CREATE LOGIN ".$this->EscapeFieldName($dolibarr_main_db_user)." WITH PASSWORD='$dolibarr_main_db_pass'";
  934. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  935. $resql=$this->query($sql);
  936. if (! $resql)
  937. {
  938. if ($this->lasterrno != '15025')
  939. {
  940. return -1;
  941. }
  942. else
  943. {
  944. // If user already exists, we continue to set permissions
  945. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
  946. }
  947. }
  948. $sql="SELECT name from sys.databases where name='".$dolibarr_main_db_name."'";
  949. $ressql=$this->query($sql);
  950. if (! $ressql)
  951. {
  952. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
  953. return -1;
  954. }
  955. else
  956. {
  957. if ($num)
  958. {
  959. $this->select_db($dolibarr_main_db_name);
  960. $sql="CREATE USER [$dolibarr_main_db_user] FOR LOGIN [$dolibarr_main_db_user]";
  961. $this->query($sql);
  962. $sql="ALTER ROLE [db_owner] ADD MEMBER [$dolibarr_main_db_user]";
  963. $this->query($sql);
  964. }
  965. }
  966. return 1;
  967. }
  968. /**
  969. * Return charset used to store data in database
  970. *
  971. * @return string Charset
  972. */
  973. public function getDefaultCharacterSetDatabase()
  974. {
  975. // FIXME: Dummy method
  976. // TODO: Implement
  977. return '';
  978. }
  979. /**
  980. * Return list of available charset that can be used to store data in database
  981. *
  982. * @return array List of Charset
  983. */
  984. public function getListOfCharacterSet()
  985. {
  986. // FIXME: Dummy method
  987. // TODO: Implement
  988. return '';
  989. }
  990. /**
  991. * Return collation used in database
  992. *
  993. * @return string Collation value
  994. */
  995. public function getDefaultCollationDatabase()
  996. {
  997. $resql=$this->query("SELECT SERVERPROPERTY('collation')");
  998. if (!$resql)
  999. {
  1000. return $this->forcecollate;
  1001. }
  1002. $liste=$this->fetch_array($resql);
  1003. return $liste['computed'];
  1004. }
  1005. /**
  1006. * Return list of available collation that can be used for database
  1007. *
  1008. * @return array Liste of Collation
  1009. */
  1010. public function getListOfCollation()
  1011. {
  1012. // FIXME: Dummy method
  1013. // TODO: Implement
  1014. return array();
  1015. }
  1016. /**
  1017. * Return full path of dump program
  1018. *
  1019. * @return string Full path of dump program
  1020. */
  1021. public function getPathOfDump()
  1022. {
  1023. // FIXME: Dummy method
  1024. // TODO: Implement
  1025. return '';
  1026. }
  1027. /**
  1028. * Return full path of restore program
  1029. *
  1030. * @return string Full path of restore program
  1031. */
  1032. public function getPathOfRestore()
  1033. {
  1034. // FIXME: Dummy method
  1035. // TODO: Implement
  1036. return '';
  1037. }
  1038. /**
  1039. * Return value of server parameters
  1040. *
  1041. * @param string $filter Filter list on a particular value
  1042. * @return array Array of key-values (key=>value)
  1043. */
  1044. public function getServerParametersValues($filter = '')
  1045. {
  1046. // FIXME: Dummy method
  1047. // TODO: Implement
  1048. // May help: SELECT SERVERPROPERTY
  1049. $result=array();
  1050. return $result;
  1051. }
  1052. /**
  1053. * Return value of server status
  1054. *
  1055. * @param string $filter Filter list on a particular value
  1056. * @return array Array of key-values (key=>value)
  1057. */
  1058. public function getServerStatusValues($filter = '')
  1059. {
  1060. // FIXME: Dummy method
  1061. // TODO: Implement
  1062. // May help: http://www.experts-exchange.com/Database/MS-SQL-Server/Q_20971756.html
  1063. return array();
  1064. }
  1065. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1066. /**
  1067. * Escape a field name according to escape's syntax
  1068. *
  1069. * @param string $fieldname Field's name to escape
  1070. * @return string field's name escaped
  1071. */
  1072. public function EscapeFieldName($fieldname)
  1073. {
  1074. // phpcs:enable
  1075. return "[".$fieldname."]";
  1076. }
  1077. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1078. /**
  1079. * Get information on field
  1080. *
  1081. * @param string $table Table name which contains fields
  1082. * @param mixed $fields String for one field or array of string for multiple field
  1083. * @return false|object
  1084. */
  1085. public function GetFieldInformation($table, $fields)
  1086. {
  1087. // phpcs:enable
  1088. $sql="SELECT * from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='".$this->escape($table)."' AND COLUMN_NAME";
  1089. if (is_array($fields))
  1090. {
  1091. $where=" IN ('".implode("','", $fields)."')";
  1092. }
  1093. else
  1094. {
  1095. $where="='".$this->escape($fields)."'";
  1096. }
  1097. $result=array();
  1098. $ret=mssql_query($sql.$where, $this->db);
  1099. if ($ret)
  1100. {
  1101. while($obj=mssql_fetch_object($ret))
  1102. {
  1103. $result[]=$obj;
  1104. }
  1105. }
  1106. else
  1107. return false;
  1108. return $result;
  1109. }
  1110. }