sqlite3.class.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. <?php
  2. /* Copyright (C) 2001 Fabien Seisen <seisen@linuxfr.org>
  3. * Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  4. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file htdocs/core/db/sqlite3.class.php
  24. * \brief Class file to manage Dolibarr database access for a SQLite database
  25. */
  26. require_once DOL_DOCUMENT_ROOT.'/core/db/DoliDB.class.php';
  27. /**
  28. * Class to manage Dolibarr database access for a SQLite database
  29. */
  30. class DoliDBSqlite3 extends DoliDB
  31. {
  32. //! Database type
  33. public $type = 'sqlite3';
  34. //! Database label
  35. const LABEL = 'Sqlite3';
  36. //! Version min database
  37. const VERSIONMIN = '3.0.0';
  38. /**
  39. * @var SQLite3Result|boolean Resultset of last query
  40. */
  41. private $_results;
  42. const WEEK_MONDAY_FIRST = 1;
  43. const WEEK_YEAR = 2;
  44. const WEEK_FIRST_WEEKDAY = 4;
  45. /**
  46. * Constructor.
  47. * This create an opened connexion to a database server and eventually to a database
  48. *
  49. * @param string $type Type of database (mysql, pgsql...)
  50. * @param string $host Address of database server
  51. * @param string $user Nom de l'utilisateur autorise
  52. * @param string $pass Mot de passe
  53. * @param string $name Nom de la database
  54. * @param int $port Port of database server
  55. */
  56. public function __construct($type, $host, $user, $pass, $name = '', $port = 0)
  57. {
  58. global $conf;
  59. // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
  60. if (!empty($conf->db->character_set)) {
  61. $this->forcecharset = $conf->db->character_set;
  62. }
  63. if (!empty($conf->db->dolibarr_main_db_collation)) {
  64. $this->forcecollate = $conf->db->dolibarr_main_db_collation;
  65. }
  66. $this->database_user = $user;
  67. $this->database_host = $host;
  68. $this->database_port = $port;
  69. $this->transaction_opened = 0;
  70. //print "Name DB: $host,$user,$pass,$name<br>";
  71. /*if (! function_exists("sqlite_query"))
  72. {
  73. $this->connected = false;
  74. $this->ok = false;
  75. $this->error="Sqlite PHP functions for using Sqlite driver are not available in this version of PHP. Try to use another driver.";
  76. dol_syslog(get_class($this)."::DoliDBSqlite3 : Sqlite PHP functions for using Sqlite driver are not available in this version of PHP. Try to use another driver.",LOG_ERR);
  77. return $this->ok;
  78. }*/
  79. /*if (! $host)
  80. {
  81. $this->connected = false;
  82. $this->ok = false;
  83. $this->error=$langs->trans("ErrorWrongHostParameter");
  84. dol_syslog(get_class($this)."::DoliDBSqlite3 : Erreur Connect, wrong host parameters",LOG_ERR);
  85. return $this->ok;
  86. }*/
  87. // Essai connexion serveur
  88. // We do not try to connect to database, only to server. Connect to database is done later in constrcutor
  89. $this->db = $this->connect($host, $user, $pass, $name, $port);
  90. if ($this->db) {
  91. $this->connected = true;
  92. $this->ok = true;
  93. $this->database_selected = true;
  94. $this->database_name = $name;
  95. $this->addCustomFunction('IF');
  96. $this->addCustomFunction('MONTH');
  97. $this->addCustomFunction('CURTIME');
  98. $this->addCustomFunction('CURDATE');
  99. $this->addCustomFunction('WEEK', 1);
  100. $this->addCustomFunction('WEEK', 2);
  101. $this->addCustomFunction('WEEKDAY');
  102. $this->addCustomFunction('date_format');
  103. //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  104. } else {
  105. // host, login ou password incorrect
  106. $this->connected = false;
  107. $this->ok = false;
  108. $this->database_selected = false;
  109. $this->database_name = '';
  110. //$this->error=sqlite_connect_error();
  111. dol_syslog(get_class($this)."::DoliDBSqlite3 : Error Connect ".$this->error, LOG_ERR);
  112. }
  113. return $this->ok;
  114. }
  115. /**
  116. * Convert a SQL request in Mysql syntax to native syntax
  117. *
  118. * @param string $line SQL request line to convert
  119. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  120. * @return string SQL request line converted
  121. */
  122. public static function convertSQLFromMysql($line, $type = 'ddl')
  123. {
  124. // Removed empty line if this is a comment line for SVN tagging
  125. if (preg_match('/^--\s\$Id/i', $line)) {
  126. return '';
  127. }
  128. // Return line if this is a comment
  129. if (preg_match('/^#/i', $line) || preg_match('/^$/i', $line) || preg_match('/^--/i', $line)) {
  130. return $line;
  131. }
  132. if ($line != "") {
  133. if ($type == 'auto') {
  134. if (preg_match('/ALTER TABLE/i', $line)) {
  135. $type = 'dml';
  136. } elseif (preg_match('/CREATE TABLE/i', $line)) {
  137. $type = 'dml';
  138. } elseif (preg_match('/DROP TABLE/i', $line)) {
  139. $type = 'dml';
  140. }
  141. }
  142. if ($type == 'dml') {
  143. $line = preg_replace('/\s/', ' ', $line); // Replace tabulation with space
  144. // we are inside create table statement so lets process datatypes
  145. if (preg_match('/(ISAM|innodb)/i', $line)) { // end of create table sequence
  146. $line = preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
  147. $line = preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i', ');', $line);
  148. $line = preg_replace('/,$/', '', $line);
  149. }
  150. // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
  151. if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i', $line, $reg)) {
  152. $newline = preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i', '\\1 \\2 integer PRIMARY KEY AUTOINCREMENT', $line);
  153. //$line = "-- ".$line." replaced by --\n".$newline;
  154. $line = $newline;
  155. }
  156. // tinyint type conversion
  157. $line = str_replace('tinyint', 'smallint', $line);
  158. // nuke unsigned
  159. $line = preg_replace('/(int\w+|smallint)\s+unsigned/i', '\\1', $line);
  160. // blob -> text
  161. $line = preg_replace('/\w*blob/i', 'text', $line);
  162. // tinytext/mediumtext -> text
  163. $line = preg_replace('/tinytext/i', 'text', $line);
  164. $line = preg_replace('/mediumtext/i', 'text', $line);
  165. // change not null datetime field to null valid ones
  166. // (to support remapping of "zero time" to null
  167. $line = preg_replace('/datetime not null/i', 'datetime', $line);
  168. $line = preg_replace('/datetime/i', 'timestamp', $line);
  169. // double -> numeric
  170. $line = preg_replace('/^double/i', 'numeric', $line);
  171. $line = preg_replace('/(\s*)double/i', '\\1numeric', $line);
  172. // float -> numeric
  173. $line = preg_replace('/^float/i', 'numeric', $line);
  174. $line = preg_replace('/(\s*)float/i', '\\1numeric', $line);
  175. // unique index(field1,field2)
  176. if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line)) {
  177. $line = preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i', 'UNIQUE\(\\1\)', $line);
  178. }
  179. // We remove end of requests "AFTER fieldxxx"
  180. $line = preg_replace('/AFTER [a-z0-9_]+/i', '', $line);
  181. // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX
  182. $line = preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i', 'DROP INDEX', $line);
  183. // Translate order to rename fields
  184. if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i', $line, $reg)) {
  185. $line = "-- ".$line." replaced by --\n";
  186. $line .= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3];
  187. }
  188. // Translate order to modify field format
  189. if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i', $line, $reg)) {
  190. $line = "-- ".$line." replaced by --\n";
  191. $newreg3 = $reg[3];
  192. $newreg3 = preg_replace('/ DEFAULT NULL/i', '', $newreg3);
  193. $newreg3 = preg_replace('/ NOT NULL/i', '', $newreg3);
  194. $newreg3 = preg_replace('/ NULL/i', '', $newreg3);
  195. $newreg3 = preg_replace('/ DEFAULT 0/i', '', $newreg3);
  196. $newreg3 = preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i', '', $newreg3);
  197. $line .= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3;
  198. // TODO Add alter to set default value or null/not null if there is this in $reg[3]
  199. }
  200. // alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported
  201. // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity);
  202. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i', $line, $reg)) {
  203. $line = "-- ".$line." replaced by --\n";
  204. $line .= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3];
  205. }
  206. // Translate order to drop foreign keys
  207. // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx;
  208. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i', $line, $reg)) {
  209. $line = "-- ".$line." replaced by --\n";
  210. $line .= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2];
  211. }
  212. // alter table add [unique] [index] (field1, field2 ...)
  213. // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version)
  214. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
  215. $fieldlist = $reg[4];
  216. $idxname = $reg[3];
  217. $tablename = $reg[1];
  218. $line = "-- ".$line." replaced by --\n";
  219. $line .= "CREATE ".(preg_match('/UNIQUE/', $reg[2]) ? 'UNIQUE ' : '')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")";
  220. }
  221. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i', $line, $reg)) {
  222. // Pour l'instant les contraintes ne sont pas créées
  223. dol_syslog(get_class().'::query line emptied');
  224. $line = 'SELECT 0;';
  225. }
  226. //if (preg_match('/rowid\s+.*\s+PRIMARY\s+KEY,/i', $line)) {
  227. //preg_replace('/(rowid\s+.*\s+PRIMARY\s+KEY\s*,)/i', '/* \\1 */', $line);
  228. //}
  229. }
  230. // Delete using criteria on other table must not declare twice the deleted table
  231. // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable
  232. if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', $line, $reg)) {
  233. if ($reg[1] == $reg[2]) { // If same table, we remove second one
  234. $line = preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i', 'DELETE FROM \\1 USING \\3', $line);
  235. }
  236. }
  237. // Remove () in the tables in FROM if one table
  238. $line = preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i', 'FROM \\1', $line);
  239. //print $line."\n";
  240. // Remove () in the tables in FROM if two table
  241. $line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2', $line);
  242. //print $line."\n";
  243. // Remove () in the tables in FROM if two table
  244. $line = preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i', 'FROM \\1, \\2, \\3', $line);
  245. //print $line."\n";
  246. //print "type=".$type." newline=".$line."<br>\n";
  247. }
  248. return $line;
  249. }
  250. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  251. /**
  252. * Select a database
  253. *
  254. * @param string $database Name of database
  255. * @return boolean true if OK, false if KO
  256. */
  257. public function select_db($database)
  258. {
  259. // phpcs:enable
  260. dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
  261. // sqlite_select_db() does not exist
  262. //return sqlite_select_db($this->db,$database);
  263. return true;
  264. }
  265. /**
  266. * Connexion to server
  267. *
  268. * @param string $host database server host
  269. * @param string $login login
  270. * @param string $passwd password
  271. * @param string $name name of database (not used for mysql, used for pgsql)
  272. * @param integer $port Port of database server
  273. * @return SQLite3 Database access handler
  274. * @see close()
  275. */
  276. public function connect($host, $login, $passwd, $name, $port = 0)
  277. {
  278. global $main_data_dir;
  279. dol_syslog(get_class($this)."::connect name=".$name, LOG_DEBUG);
  280. $dir = $main_data_dir;
  281. if (empty($dir)) {
  282. $dir = DOL_DATA_ROOT;
  283. }
  284. // With sqlite, port must be in connect parameters
  285. //if (! $newport) $newport=3306;
  286. $database_name = $dir.'/database_'.$name.'.sdb';
  287. try {
  288. /*** connect to SQLite database ***/
  289. //$this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb');
  290. $this->db = new SQLite3($database_name);
  291. //$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  292. } catch (Exception $e) {
  293. $this->error = self::LABEL.' '.$e->getMessage().' current dir='.$database_name;
  294. return '';
  295. }
  296. //print "Resultat fonction connect: ".$this->db;
  297. return $this->db;
  298. }
  299. /**
  300. * Return version of database server
  301. *
  302. * @return string Version string
  303. */
  304. public function getVersion()
  305. {
  306. $tmp = $this->db->version();
  307. return $tmp['versionString'];
  308. }
  309. /**
  310. * Return version of database client driver
  311. *
  312. * @return string Version string
  313. */
  314. public function getDriverInfo()
  315. {
  316. return 'sqlite3 php driver';
  317. }
  318. /**
  319. * Close database connexion
  320. *
  321. * @return bool True if disconnect successfull, false otherwise
  322. * @see connect()
  323. */
  324. public function close()
  325. {
  326. if ($this->db) {
  327. if ($this->transaction_opened > 0) {
  328. dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
  329. }
  330. $this->connected = false;
  331. $this->db->close();
  332. unset($this->db); // Clean this->db
  333. return true;
  334. }
  335. return false;
  336. }
  337. /**
  338. * Execute a SQL request and return the resultset
  339. *
  340. * @param string $query SQL query string
  341. * @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).
  342. * 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.
  343. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  344. * @param int $result_mode Result mode (not used with sqlite)
  345. * @return bool|SQLite3Result Resultset of answer
  346. */
  347. public function query($query, $usesavepoint = 0, $type = 'auto', $result_mode = 0)
  348. {
  349. global $conf, $dolibarr_main_db_readonly;
  350. $ret = null;
  351. $query = trim($query);
  352. $this->error = '';
  353. // Convert MySQL syntax to SQLite syntax
  354. $reg = array();
  355. if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+CONSTRAINT\s+(.*)\s*FOREIGN\s+KEY\s*\(([\w,\s]+)\)\s*REFERENCES\s+(\w+)\s*\(([\w,\s]+)\)/i', $query, $reg)) {
  356. // Ajout d'une clef étrangère à la table
  357. // procédure de remplacement de la table pour ajouter la contrainte
  358. // Exemple : ALTER TABLE llx_adherent ADD CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid)
  359. // -> CREATE TABLE ( ... ,CONSTRAINT adherent_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid))
  360. $foreignFields = $reg[5];
  361. $foreignTable = $reg[4];
  362. $localfields = $reg[3];
  363. $constraintname = trim($reg[2]);
  364. $tablename = trim($reg[1]);
  365. $descTable = $this->db->querySingle("SELECT sql FROM sqlite_master WHERE name='".$this->escape($tablename)."'");
  366. // 1- Renommer la table avec un nom temporaire
  367. $this->query("ALTER TABLE ".$tablename." RENAME TO tmp_".$tablename);
  368. // 2- Recréer la table avec la contrainte ajoutée
  369. // on bricole la requete pour ajouter la contrainte
  370. $descTable = substr($descTable, 0, strlen($descTable) - 1);
  371. $descTable .= ", CONSTRAINT ".$constraintname." FOREIGN KEY (".$localfields.") REFERENCES ".$foreignTable."(".$foreignFields.")";
  372. // fermeture de l'instruction
  373. $descTable .= ')';
  374. // Création proprement dite de la table
  375. $this->query($descTable);
  376. // 3- Transférer les données
  377. $this->query("INSERT INTO ".$tablename." SELECT * FROM tmp_".$tablename);
  378. // 4- Supprimer la table temporaire
  379. $this->query("DROP TABLE tmp_".$tablename);
  380. // dummy statement
  381. $query = "SELECT 0";
  382. } else {
  383. $query = $this->convertSQLFromMysql($query, $type);
  384. }
  385. //print "After convertSQLFromMysql:\n".$query."<br>\n";
  386. if (!in_array($query, array('BEGIN', 'COMMIT', 'ROLLBACK'))) {
  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 (empty($query)) {
  391. return false; // Return false = error if empty request
  392. }
  393. if (!empty($dolibarr_main_db_readonly)) {
  394. if (preg_match('/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
  395. $this->lasterror = 'Application in read-only mode';
  396. $this->lasterrno = 'APPREADONLY';
  397. $this->lastquery = $query;
  398. return false;
  399. }
  400. }
  401. // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
  402. try {
  403. //$ret = $this->db->exec($query);
  404. $ret = $this->db->query($query); // $ret is a Sqlite3Result
  405. if ($ret) {
  406. $ret->queryString = $query;
  407. }
  408. } catch (Exception $e) {
  409. $this->error = $this->db->lastErrorMsg();
  410. }
  411. if (!preg_match("/^COMMIT/i", $query) && !preg_match("/^ROLLBACK/i", $query)) {
  412. // Si requete utilisateur, on la sauvegarde ainsi que son resultset
  413. if (!is_object($ret) || $this->error) {
  414. $this->lastqueryerror = $query;
  415. $this->lasterror = $this->error();
  416. $this->lasterrno = $this->errno();
  417. dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR);
  418. $errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror;
  419. if (preg_match('/[0-9]/', $this->lasterrno)) {
  420. $errormsg .= ' ('.$this->lasterrno.')';
  421. }
  422. if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) {
  423. dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
  424. }
  425. dol_syslog(get_class($this)."::query SQL Error message: ".$errormsg, LOG_ERR);
  426. }
  427. $this->lastquery = $query;
  428. $this->_results = $ret;
  429. }
  430. return $ret;
  431. }
  432. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  433. /**
  434. * Returns the current line (as an object) for the resultset cursor
  435. *
  436. * @param SQLite3Result $resultset Curseur de la requete voulue
  437. * @return false|object Object result line or false if KO or end of cursor
  438. */
  439. public function fetch_object($resultset)
  440. {
  441. // phpcs:enable
  442. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  443. if (!is_object($resultset)) {
  444. $resultset = $this->_results;
  445. }
  446. //return $resultset->fetch(PDO::FETCH_OBJ);
  447. $ret = $resultset->fetchArray(SQLITE3_ASSOC);
  448. if ($ret) {
  449. return (object) $ret;
  450. }
  451. return false;
  452. }
  453. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  454. /**
  455. * Return datas as an array
  456. *
  457. * @param SQLite3Result $resultset Resultset of request
  458. * @return false|array Array or false if KO or end of cursor
  459. */
  460. public function fetch_array($resultset)
  461. {
  462. // phpcs:enable
  463. // If resultset not provided, we take the last used by connexion
  464. if (!is_object($resultset)) {
  465. $resultset = $this->_results;
  466. }
  467. //return $resultset->fetch(PDO::FETCH_ASSOC);
  468. $ret = $resultset->fetchArray(SQLITE3_ASSOC);
  469. return $ret;
  470. }
  471. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  472. /**
  473. * Return datas as an array
  474. *
  475. * @param SQLite3Result $resultset Resultset of request
  476. * @return false|array Array or false if KO or end of cursor
  477. */
  478. public function fetch_row($resultset)
  479. {
  480. // phpcs:enable
  481. // If resultset not provided, we take the last used by connexion
  482. if (!is_bool($resultset)) {
  483. if (!is_object($resultset)) {
  484. $resultset = $this->_results;
  485. }
  486. return $resultset->fetchArray(SQLITE3_NUM);
  487. } else {
  488. // si le curseur est un booleen on retourne la valeur 0
  489. return false;
  490. }
  491. }
  492. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  493. /**
  494. * Return number of lines for result of a SELECT
  495. *
  496. * @param SQLite3Result $resultset Resulset of requests
  497. * @return int Nb of lines
  498. * @see affected_rows()
  499. */
  500. public function num_rows($resultset)
  501. {
  502. // phpcs:enable
  503. // FIXME: SQLite3Result does not have a queryString member
  504. // If resultset not provided, we take the last used by connexion
  505. if (!is_object($resultset)) {
  506. $resultset = $this->_results;
  507. }
  508. if (preg_match("/^SELECT/i", $resultset->queryString)) {
  509. return $this->db->querySingle("SELECT count(*) FROM (".$resultset->queryString.") q");
  510. }
  511. return 0;
  512. }
  513. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  514. /**
  515. * Return number of lines for result of a SELECT
  516. *
  517. * @param SQLite3Result $resultset Resulset of requests
  518. * @return int Nb of lines
  519. * @see affected_rows()
  520. */
  521. public function affected_rows($resultset)
  522. {
  523. // phpcs:enable
  524. // FIXME: SQLite3Result does not have a queryString member
  525. // If resultset not provided, we take the last used by connexion
  526. if (!is_object($resultset)) {
  527. $resultset = $this->_results;
  528. }
  529. if (preg_match("/^SELECT/i", $resultset->queryString)) {
  530. return $this->num_rows($resultset);
  531. }
  532. // mysql necessite un link de base pour cette fonction contrairement
  533. // a pqsql qui prend un resultset
  534. return $this->db->changes();
  535. }
  536. /**
  537. * Free last resultset used.
  538. *
  539. * @param SQLite3Result $resultset Curseur de la requete voulue
  540. * @return void
  541. */
  542. public function free($resultset = null)
  543. {
  544. // If resultset not provided, we take the last used by connexion
  545. if (!is_object($resultset)) {
  546. $resultset = $this->_results;
  547. }
  548. // Si resultset en est un, on libere la memoire
  549. if ($resultset && is_object($resultset)) {
  550. $resultset->finalize();
  551. }
  552. }
  553. /**
  554. * Escape a string to insert data
  555. *
  556. * @param string $stringtoencode String to escape
  557. * @return string String escaped
  558. */
  559. public function escape($stringtoencode)
  560. {
  561. return Sqlite3::escapeString($stringtoencode);
  562. }
  563. /**
  564. * Escape a string to insert data
  565. *
  566. * @param string $stringtoencode String to escape
  567. * @return string String escaped
  568. * @deprecated
  569. */
  570. public function escapeunderscore($stringtoencode)
  571. {
  572. return str_replace('_', '\_', (string) $stringtoencode);
  573. }
  574. /**
  575. * Escape a string to insert data into a like
  576. *
  577. * @param string $stringtoencode String to escape
  578. * @return string String escaped
  579. */
  580. public function escapeforlike($stringtoencode)
  581. {
  582. return str_replace(array('_', '\\', '%'), array('\_', '\\\\', '\%'), (string) $stringtoencode);
  583. }
  584. /**
  585. * Renvoie le code erreur generique de l'operation precedente.
  586. *
  587. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  588. */
  589. public function errno()
  590. {
  591. if (!$this->connected) {
  592. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  593. return 'DB_ERROR_FAILED_TO_CONNECT';
  594. } else {
  595. // Constants to convert error code to a generic Dolibarr error code
  596. /*$errorcode_map = array(
  597. 1004 => 'DB_ERROR_CANNOT_CREATE',
  598. 1005 => 'DB_ERROR_CANNOT_CREATE',
  599. 1006 => 'DB_ERROR_CANNOT_CREATE',
  600. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  601. 1008 => 'DB_ERROR_CANNOT_DROP',
  602. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  603. 1044 => 'DB_ERROR_ACCESSDENIED',
  604. 1046 => 'DB_ERROR_NODBSELECTED',
  605. 1048 => 'DB_ERROR_CONSTRAINT',
  606. 'HY000' => 'DB_ERROR_TABLE_ALREADY_EXISTS',
  607. 1051 => 'DB_ERROR_NOSUCHTABLE',
  608. 1054 => 'DB_ERROR_NOSUCHFIELD',
  609. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  610. 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  611. 1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  612. 1064 => 'DB_ERROR_SYNTAX',
  613. 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  614. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  615. 1091 => 'DB_ERROR_NOSUCHFIELD',
  616. 1100 => 'DB_ERROR_NOT_LOCKED',
  617. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  618. 1146 => 'DB_ERROR_NOSUCHTABLE',
  619. 1216 => 'DB_ERROR_NO_PARENT',
  620. 1217 => 'DB_ERROR_CHILD_EXISTS',
  621. 1451 => 'DB_ERROR_CHILD_EXISTS'
  622. );
  623. if (isset($errorcode_map[$this->db->errorCode()]))
  624. {
  625. return $errorcode_map[$this->db->errorCode()];
  626. }*/
  627. $errno = $this->db->lastErrorCode();
  628. if ($errno == 'HY000' || $errno == 0) {
  629. if (preg_match('/table.*already exists/i', $this->error)) {
  630. return 'DB_ERROR_TABLE_ALREADY_EXISTS';
  631. } elseif (preg_match('/index.*already exists/i', $this->error)) {
  632. return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
  633. } elseif (preg_match('/syntax error/i', $this->error)) {
  634. return 'DB_ERROR_SYNTAX';
  635. }
  636. }
  637. if ($errno == '23000') {
  638. if (preg_match('/column.* not unique/i', $this->error)) {
  639. return 'DB_ERROR_RECORD_ALREADY_EXISTS';
  640. } elseif (preg_match('/PRIMARY KEY must be unique/i', $this->error)) {
  641. return 'DB_ERROR_RECORD_ALREADY_EXISTS';
  642. }
  643. }
  644. if ($errno > 1) {
  645. // TODO Voir la liste des messages d'erreur
  646. }
  647. return ($errno ? 'DB_ERROR_'.$errno : '0');
  648. }
  649. }
  650. /**
  651. * Renvoie le texte de l'erreur mysql de l'operation precedente.
  652. *
  653. * @return string Error text
  654. */
  655. public function error()
  656. {
  657. if (!$this->connected) {
  658. // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
  659. return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
  660. } else {
  661. return $this->error;
  662. }
  663. }
  664. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  665. /**
  666. * Get last ID after an insert INSERT
  667. *
  668. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  669. * @param string $fieldid Field name
  670. * @return int Id of row
  671. */
  672. public function last_insert_id($tab, $fieldid = 'rowid')
  673. {
  674. // phpcs:enable
  675. return $this->db->lastInsertRowId();
  676. }
  677. /**
  678. * Encrypt sensitive data in database
  679. * Warning: This function includes the escape and add the SQL simple quotes on strings.
  680. *
  681. * @param string $fieldorvalue Field name or value to encrypt
  682. * @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
  683. * @return string XXX(field) or XXX('value') or field or 'value'
  684. */
  685. public function encrypt($fieldorvalue, $withQuotes = 1)
  686. {
  687. global $conf;
  688. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  689. $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
  690. //Encryption key
  691. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  692. $escapedstringwithquotes = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
  693. if ($cryptType && !empty($cryptKey)) {
  694. if ($cryptType == 2) {
  695. $escapedstringwithquotes = "AES_ENCRYPT(".$escapedstringwithquotes.", '".$this->escape($cryptKey)."')";
  696. } elseif ($cryptType == 1) {
  697. $escapedstringwithquotes = "DES_ENCRYPT(".$escapedstringwithquotes.", '".$this->escape($cryptKey)."')";
  698. }
  699. }
  700. return $escapedstringwithquotes;
  701. }
  702. /**
  703. * Decrypt sensitive data in database
  704. *
  705. * @param string $value Value to decrypt
  706. * @return string Decrypted value if used
  707. */
  708. public function decrypt($value)
  709. {
  710. global $conf;
  711. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  712. $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
  713. //Encryption key
  714. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  715. $return = $value;
  716. if ($cryptType && !empty($cryptKey)) {
  717. if ($cryptType == 2) {
  718. $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  719. } elseif ($cryptType == 1) {
  720. $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  721. }
  722. }
  723. return $return;
  724. }
  725. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  726. /**
  727. * Return connexion ID
  728. *
  729. * @return string Id connexion
  730. */
  731. public function DDLGetConnectId()
  732. {
  733. // phpcs:enable
  734. return '?';
  735. }
  736. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  737. /**
  738. * Create a new database
  739. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  740. * We force to create database with charset this->forcecharset and collate this->forcecollate
  741. *
  742. * @param string $database Database name to create
  743. * @param string $charset Charset used to store data
  744. * @param string $collation Charset used to sort data
  745. * @param string $owner Username of database owner
  746. * @return SQLite3Result resource defined if OK, null if KO
  747. */
  748. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  749. {
  750. // phpcs:enable
  751. if (empty($charset)) {
  752. $charset = $this->forcecharset;
  753. }
  754. if (empty($collation)) {
  755. $collation = $this->forcecollate;
  756. }
  757. // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
  758. $sql = "CREATE DATABASE ".$this->escape($database);
  759. $sql .= " DEFAULT CHARACTER SET ".$this->escape($charset)." DEFAULT COLLATE ".$this->escape($collation);
  760. dol_syslog($sql, LOG_DEBUG);
  761. $ret = $this->query($sql);
  762. return $ret;
  763. }
  764. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  765. /**
  766. * List tables into a database
  767. *
  768. * @param string $database Name of database
  769. * @param string $table Name of table filter ('xxx%')
  770. * @return array List of tables in an array
  771. */
  772. public function DDLListTables($database, $table = '')
  773. {
  774. // phpcs:enable
  775. $listtables = array();
  776. $like = '';
  777. if ($table) {
  778. $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
  779. $like = "LIKE '".$this->escape($tmptable)."'";
  780. }
  781. $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i', '', $database);
  782. $sql = "SHOW TABLES FROM ".$tmpdatabase." ".$like.";";
  783. //print $sql;
  784. $result = $this->query($sql);
  785. if ($result) {
  786. while ($row = $this->fetch_row($result)) {
  787. $listtables[] = $row[0];
  788. }
  789. }
  790. return $listtables;
  791. }
  792. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  793. /**
  794. * List information of columns into a table.
  795. *
  796. * @param string $table Name of table
  797. * @return array Tableau des informations des champs de la table
  798. * TODO modify for sqlite
  799. */
  800. public function DDLInfoTable($table)
  801. {
  802. // phpcs:enable
  803. $infotables = array();
  804. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  805. $sql = "SHOW FULL COLUMNS FROM ".$tmptable.";";
  806. dol_syslog($sql, LOG_DEBUG);
  807. $result = $this->query($sql);
  808. if ($result) {
  809. while ($row = $this->fetch_row($result)) {
  810. $infotables[] = $row;
  811. }
  812. }
  813. return $infotables;
  814. }
  815. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  816. /**
  817. * Create a table into database
  818. *
  819. * @param string $table Nom de la table
  820. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  821. * @param string $primary_key Nom du champ qui sera la clef primaire
  822. * @param string $type Type de la table
  823. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  824. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  825. * @param array $keys Tableau des champs cles noms => valeur
  826. * @return int <0 if KO, >=0 if OK
  827. */
  828. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  829. {
  830. // phpcs:enable
  831. // FIXME: $fulltext_keys parameter is unused
  832. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  833. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  834. $sql = "create table ".$table."(";
  835. $i = 0;
  836. foreach ($fields as $field_name => $field_desc) {
  837. $sqlfields[$i] = $field_name." ";
  838. $sqlfields[$i] .= $field_desc['type'];
  839. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  840. $sqlfields[$i] .= "(".$field_desc['value'].")";
  841. } elseif (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  842. $sqlfields[$i] .= " ".$field_desc['attribute'];
  843. } elseif (preg_match("/^[^\s]/i", $field_desc['default'])) {
  844. if (preg_match("/null/i", $field_desc['default'])) {
  845. $sqlfields[$i] .= " default ".$field_desc['default'];
  846. } else {
  847. $sqlfields[$i] .= " default '".$this->escape($field_desc['default'])."'";
  848. }
  849. } elseif (preg_match("/^[^\s]/i", $field_desc['null'])) {
  850. $sqlfields[$i] .= " ".$field_desc['null'];
  851. } elseif (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  852. $sqlfields[$i] .= " ".$field_desc['extra'];
  853. }
  854. $i++;
  855. }
  856. if ($primary_key != "") {
  857. $pk = "primary key(".$primary_key.")";
  858. }
  859. if (is_array($unique_keys)) {
  860. $i = 0;
  861. foreach ($unique_keys as $key => $value) {
  862. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$this->escape($value)."')";
  863. $i++;
  864. }
  865. }
  866. if (is_array($keys)) {
  867. $i = 0;
  868. foreach ($keys as $key => $value) {
  869. $sqlk[$i] = "KEY ".$key." (".$value.")";
  870. $i++;
  871. }
  872. }
  873. $sql .= implode(',', $sqlfields);
  874. if ($primary_key != "") {
  875. $sql .= ",".$pk;
  876. }
  877. if (is_array($unique_keys)) {
  878. $sql .= ",".implode(',', $sqluq);
  879. }
  880. if (is_array($keys)) {
  881. $sql .= ",".implode(',', $sqlk);
  882. }
  883. $sql .= ") type=".$type;
  884. dol_syslog($sql, LOG_DEBUG);
  885. if (!$this -> query($sql)) {
  886. return -1;
  887. }
  888. return 1;
  889. }
  890. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  891. /**
  892. * Drop a table into database
  893. *
  894. * @param string $table Name of table
  895. * @return int <0 if KO, >=0 if OK
  896. */
  897. public function DDLDropTable($table)
  898. {
  899. // phpcs:enable
  900. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  901. $sql = "DROP TABLE ".$tmptable;
  902. if (!$this->query($sql)) {
  903. return -1;
  904. } else {
  905. return 1;
  906. }
  907. }
  908. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  909. /**
  910. * Return a pointer of line with description of a table or field
  911. *
  912. * @param string $table Name of table
  913. * @param string $field Optionnel : Name of field if we want description of field
  914. * @return bool|SQLite3Result Resource
  915. */
  916. public function DDLDescTable($table, $field = "")
  917. {
  918. // phpcs:enable
  919. $sql = "DESC ".$table." ".$field;
  920. dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
  921. $this->_results = $this->query($sql);
  922. return $this->_results;
  923. }
  924. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  925. /**
  926. * Create a new field into table
  927. *
  928. * @param string $table Name of table
  929. * @param string $field_name Name of field to add
  930. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  931. * @param string $field_position Optionnel ex.: "after champtruc"
  932. * @return int <0 if KO, >0 if OK
  933. */
  934. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  935. {
  936. // phpcs:enable
  937. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  938. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  939. $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
  940. $sql .= $field_desc['type'];
  941. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  942. if (!in_array($field_desc['type'], array('date', 'datetime'))) {
  943. $sql .= "(".$field_desc['value'].")";
  944. }
  945. }
  946. if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  947. $sql .= " ".$field_desc['attribute'];
  948. }
  949. if (preg_match("/^[^\s]/i", $field_desc['null'])) {
  950. $sql .= " ".$field_desc['null'];
  951. }
  952. if (preg_match("/^[^\s]/i", $field_desc['default'])) {
  953. if (preg_match("/null/i", $field_desc['default'])) {
  954. $sql .= " default ".$field_desc['default'];
  955. } else {
  956. $sql .= " default '".$this->escape($field_desc['default'])."'";
  957. }
  958. }
  959. if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  960. $sql .= " ".$field_desc['extra'];
  961. }
  962. $sql .= " ".$field_position;
  963. dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
  964. if (!$this->query($sql)) {
  965. return -1;
  966. }
  967. return 1;
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Update format of a field into a table
  972. *
  973. * @param string $table Name of table
  974. * @param string $field_name Name of field to modify
  975. * @param string $field_desc Array with description of field format
  976. * @return int <0 if KO, >0 if OK
  977. */
  978. public function DDLUpdateField($table, $field_name, $field_desc)
  979. {
  980. // phpcs:enable
  981. $sql = "ALTER TABLE ".$table;
  982. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  983. if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
  984. $sql .= "(".$field_desc['value'].")";
  985. }
  986. dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
  987. if (!$this->query($sql)) {
  988. return -1;
  989. }
  990. return 1;
  991. }
  992. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  993. /**
  994. * Drop a field from table
  995. *
  996. * @param string $table Name of table
  997. * @param string $field_name Name of field to drop
  998. * @return int <0 if KO, >0 if OK
  999. */
  1000. public function DDLDropField($table, $field_name)
  1001. {
  1002. // phpcs:enable
  1003. $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
  1004. $sql = "ALTER TABLE ".$table." DROP COLUMN `".$tmp_field_name."`";
  1005. if (!$this->query($sql)) {
  1006. $this->error = $this->lasterror();
  1007. return -1;
  1008. }
  1009. return 1;
  1010. }
  1011. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1012. /**
  1013. * Create a user and privileges to connect to database (even if database does not exists yet)
  1014. *
  1015. * @param string $dolibarr_main_db_host Ip serveur
  1016. * @param string $dolibarr_main_db_user Nom user a creer
  1017. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  1018. * @param string $dolibarr_main_db_name Database name where user must be granted
  1019. * @return int <0 if KO, >=0 if OK
  1020. */
  1021. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  1022. {
  1023. // phpcs:enable
  1024. $sql = "INSERT INTO user ";
  1025. $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
  1026. $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
  1027. $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
  1028. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  1029. $resql = $this->query($sql);
  1030. if (!$resql) {
  1031. return -1;
  1032. }
  1033. $sql = "INSERT INTO db ";
  1034. $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
  1035. $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
  1036. $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
  1037. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
  1038. $resql = $this->query($sql);
  1039. if (!$resql) {
  1040. return -1;
  1041. }
  1042. $sql = "FLUSH Privileges";
  1043. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
  1044. $resql = $this->query($sql);
  1045. if (!$resql) {
  1046. return -1;
  1047. }
  1048. return 1;
  1049. }
  1050. /**
  1051. * Return charset used to store data in database
  1052. *
  1053. * @return string Charset
  1054. */
  1055. public function getDefaultCharacterSetDatabase()
  1056. {
  1057. return 'UTF-8';
  1058. }
  1059. /**
  1060. * Return list of available charset that can be used to store data in database
  1061. *
  1062. * @return array List of Charset
  1063. */
  1064. public function getListOfCharacterSet()
  1065. {
  1066. $liste = array();
  1067. $i = 0;
  1068. $liste[$i]['charset'] = 'UTF-8';
  1069. $liste[$i]['description'] = 'UTF-8';
  1070. return $liste;
  1071. }
  1072. /**
  1073. * Return collation used in database
  1074. *
  1075. * @return string Collation value
  1076. */
  1077. public function getDefaultCollationDatabase()
  1078. {
  1079. return 'UTF-8';
  1080. }
  1081. /**
  1082. * Return list of available collation that can be used for database
  1083. *
  1084. * @return array List of Collation
  1085. */
  1086. public function getListOfCollation()
  1087. {
  1088. $liste = array();
  1089. $i = 0;
  1090. $liste[$i]['charset'] = 'UTF-8';
  1091. $liste[$i]['description'] = 'UTF-8';
  1092. return $liste;
  1093. }
  1094. /**
  1095. * Return full path of dump program
  1096. *
  1097. * @return string Full path of dump program
  1098. */
  1099. public function getPathOfDump()
  1100. {
  1101. // FIXME: not for SQLite
  1102. $fullpathofdump = '/pathtomysqldump/mysqldump';
  1103. $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
  1104. if ($resql) {
  1105. $liste = $this->fetch_array($resql);
  1106. $basedir = $liste['Value'];
  1107. $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
  1108. }
  1109. return $fullpathofdump;
  1110. }
  1111. /**
  1112. * Return full path of restore program
  1113. *
  1114. * @return string Full path of restore program
  1115. */
  1116. public function getPathOfRestore()
  1117. {
  1118. // FIXME: not for SQLite
  1119. $fullpathofimport = '/pathtomysql/mysql';
  1120. $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
  1121. if ($resql) {
  1122. $liste = $this->fetch_array($resql);
  1123. $basedir = $liste['Value'];
  1124. $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
  1125. }
  1126. return $fullpathofimport;
  1127. }
  1128. /**
  1129. * Return value of server parameters
  1130. *
  1131. * @param string $filter Filter list on a particular value
  1132. * @return array Array of key-values (key=>value)
  1133. */
  1134. public function getServerParametersValues($filter = '')
  1135. {
  1136. $result = array();
  1137. static $pragmas;
  1138. if (!isset($pragmas)) {
  1139. // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
  1140. // indépendante de la base de données.
  1141. // cf. http://www.sqlite.org/pragma.html
  1142. $pragmas = array(
  1143. 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
  1144. 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
  1145. 'compile_options', 'data_version', /*'database_list',*/
  1146. 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
  1147. 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
  1148. 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
  1149. 'max_page_count', 'page_count', 'page_size', 'parser_trace',
  1150. 'query_only', 'quick_check', 'read_uncommitted', 'recursive_triggers',
  1151. 'reverse_unordered_selects', 'schema_version', 'user_version',
  1152. 'secure_delete', 'short_column_names', 'shrink_memory', 'soft_heap_limit',
  1153. 'synchronous', 'temp_store', /*'temp_store_directory',*/ 'threads',
  1154. 'vdbe_addoptrace', 'vdbe_debug', 'vdbe_listing', 'vdbe_trace',
  1155. 'wal_autocheckpoint',
  1156. );
  1157. }
  1158. // TODO prendre en compte le filtre
  1159. foreach ($pragmas as $var) {
  1160. $sql = "PRAGMA $var";
  1161. $resql = $this->query($sql);
  1162. if ($resql) {
  1163. $obj = $this->fetch_row($resql);
  1164. //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
  1165. $result[$var] = $obj[0];
  1166. } else {
  1167. // TODO Récupérer le message
  1168. $result[$var] = 'FAIL';
  1169. }
  1170. }
  1171. return $result;
  1172. }
  1173. /**
  1174. * Return value of server status
  1175. *
  1176. * @param string $filter Filter list on a particular value
  1177. * @return array Array of key-values (key=>value)
  1178. */
  1179. public function getServerStatusValues($filter = '')
  1180. {
  1181. $result = array();
  1182. /*
  1183. $sql='SHOW STATUS';
  1184. if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
  1185. $resql=$this->query($sql);
  1186. if ($resql)
  1187. {
  1188. while ($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
  1189. }
  1190. */
  1191. return $result;
  1192. }
  1193. /**
  1194. * Permet le chargement d'une fonction personnalisee dans le moteur de base de donnees.
  1195. * Note: le nom de la fonction personnalisee est prefixee par 'db'. La fonction doit être
  1196. * statique et publique. Le nombre de parametres est determine automatiquement.
  1197. *
  1198. * @param string $name Le nom de la fonction a definir dans Sqlite
  1199. * @param int $arg_count Arg count
  1200. * @return void
  1201. */
  1202. private function addCustomFunction($name, $arg_count = -1)
  1203. {
  1204. if ($this->db) {
  1205. $newname = preg_replace('/_/', '', $name);
  1206. $localname = __CLASS__.'::db'.$newname;
  1207. $reflectClass = new ReflectionClass(__CLASS__);
  1208. $reflectFunction = $reflectClass->getMethod('db'.$newname);
  1209. if ($arg_count < 0) {
  1210. $arg_count = $reflectFunction->getNumberOfParameters();
  1211. }
  1212. if (!$this->db->createFunction($name, $localname, $arg_count)) {
  1213. $this->error = "unable to create custom function '$name'";
  1214. }
  1215. }
  1216. }
  1217. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1218. /**
  1219. * calc_daynr
  1220. *
  1221. * @param int $year Year
  1222. * @param int $month Month
  1223. * @param int $day Day
  1224. * @return int Formatted date
  1225. */
  1226. private static function calc_daynr($year, $month, $day)
  1227. {
  1228. // phpcs:enable
  1229. $y = $year;
  1230. if ($y == 0 && $month == 0) {
  1231. return 0;
  1232. }
  1233. $num = (365 * $y + 31 * ($month - 1) + $day);
  1234. if ($month <= 2) {
  1235. $y--;
  1236. } else {
  1237. $num -= floor(($month * 4 + 23) / 10);
  1238. }
  1239. $temp = floor(($y / 100 + 1) * 3 / 4);
  1240. return $num + floor($y / 4) - $temp;
  1241. }
  1242. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1243. /**
  1244. * calc_weekday
  1245. *
  1246. * @param int $daynr ???
  1247. * @param bool $sunday_first_day_of_week ???
  1248. * @return int
  1249. */
  1250. private static function calc_weekday($daynr, $sunday_first_day_of_week)
  1251. {
  1252. // phpcs:enable
  1253. $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
  1254. return $ret;
  1255. }
  1256. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1257. /**
  1258. * calc_days_in_year
  1259. *
  1260. * @param string $year Year
  1261. * @return int Nb of days in year
  1262. */
  1263. private static function calc_days_in_year($year)
  1264. {
  1265. // phpcs:enable
  1266. return (($year & 3) == 0 && ($year % 100 || ($year % 400 == 0 && $year)) ? 366 : 365);
  1267. }
  1268. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1269. /**
  1270. * calc_week
  1271. *
  1272. * @param string $year Year
  1273. * @param string $month Month
  1274. * @param string $day Day
  1275. * @param string $week_behaviour Week behaviour
  1276. * @param string $calc_year ???
  1277. * @return string ???
  1278. */
  1279. private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year)
  1280. {
  1281. // phpcs:enable
  1282. $daynr = self::calc_daynr($year, $month, $day);
  1283. $first_daynr = self::calc_daynr($year, 1, 1);
  1284. $monday_first = ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
  1285. $week_year = ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
  1286. $first_weekday = ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
  1287. $weekday = self::calc_weekday($first_daynr, !$monday_first);
  1288. $calc_year = $year;
  1289. if ($month == 1 && $day <= 7 - $weekday) {
  1290. if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4))) {
  1291. return 0;
  1292. }
  1293. $week_year = 1;
  1294. $calc_year--;
  1295. $first_daynr -= ($days = self::calc_days_in_year($calc_year));
  1296. $weekday = ($weekday + 53 * 7 - $days) % 7;
  1297. }
  1298. if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
  1299. $days = $daynr - ($first_daynr + (7 - $weekday));
  1300. } else {
  1301. $days = $daynr - ($first_daynr - $weekday);
  1302. }
  1303. if ($week_year && $days >= 52 * 7) {
  1304. $weekday = ($weekday + self::calc_days_in_year($calc_year)) % 7;
  1305. if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0)) {
  1306. $calc_year++;
  1307. return 1;
  1308. }
  1309. }
  1310. return floor($days / 7 + 1);
  1311. }
  1312. }