mssql.class.php 37 KB

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