sqlite3.class.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  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. */
  569. public function escapeunderscore($stringtoencode)
  570. {
  571. return str_replace('_', '\_', $stringtoencode);
  572. }
  573. /**
  574. * Renvoie le code erreur generique de l'operation precedente.
  575. *
  576. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  577. */
  578. public function errno()
  579. {
  580. if (!$this->connected) {
  581. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  582. return 'DB_ERROR_FAILED_TO_CONNECT';
  583. } else {
  584. // Constants to convert error code to a generic Dolibarr error code
  585. /*$errorcode_map = array(
  586. 1004 => 'DB_ERROR_CANNOT_CREATE',
  587. 1005 => 'DB_ERROR_CANNOT_CREATE',
  588. 1006 => 'DB_ERROR_CANNOT_CREATE',
  589. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  590. 1008 => 'DB_ERROR_CANNOT_DROP',
  591. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  592. 1044 => 'DB_ERROR_ACCESSDENIED',
  593. 1046 => 'DB_ERROR_NODBSELECTED',
  594. 1048 => 'DB_ERROR_CONSTRAINT',
  595. 'HY000' => 'DB_ERROR_TABLE_ALREADY_EXISTS',
  596. 1051 => 'DB_ERROR_NOSUCHTABLE',
  597. 1054 => 'DB_ERROR_NOSUCHFIELD',
  598. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  599. 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  600. 1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  601. 1064 => 'DB_ERROR_SYNTAX',
  602. 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  603. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  604. 1091 => 'DB_ERROR_NOSUCHFIELD',
  605. 1100 => 'DB_ERROR_NOT_LOCKED',
  606. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  607. 1146 => 'DB_ERROR_NOSUCHTABLE',
  608. 1216 => 'DB_ERROR_NO_PARENT',
  609. 1217 => 'DB_ERROR_CHILD_EXISTS',
  610. 1451 => 'DB_ERROR_CHILD_EXISTS'
  611. );
  612. if (isset($errorcode_map[$this->db->errorCode()]))
  613. {
  614. return $errorcode_map[$this->db->errorCode()];
  615. }*/
  616. $errno = $this->db->lastErrorCode();
  617. if ($errno == 'HY000' || $errno == 0) {
  618. if (preg_match('/table.*already exists/i', $this->error)) {
  619. return 'DB_ERROR_TABLE_ALREADY_EXISTS';
  620. } elseif (preg_match('/index.*already exists/i', $this->error)) {
  621. return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS';
  622. } elseif (preg_match('/syntax error/i', $this->error)) {
  623. return 'DB_ERROR_SYNTAX';
  624. }
  625. }
  626. if ($errno == '23000') {
  627. if (preg_match('/column.* not unique/i', $this->error)) {
  628. return 'DB_ERROR_RECORD_ALREADY_EXISTS';
  629. } elseif (preg_match('/PRIMARY KEY must be unique/i', $this->error)) {
  630. return 'DB_ERROR_RECORD_ALREADY_EXISTS';
  631. }
  632. }
  633. if ($errno > 1) {
  634. // TODO Voir la liste des messages d'erreur
  635. }
  636. return ($errno ? 'DB_ERROR_'.$errno : '0');
  637. }
  638. }
  639. /**
  640. * Renvoie le texte de l'erreur mysql de l'operation precedente.
  641. *
  642. * @return string Error text
  643. */
  644. public function error()
  645. {
  646. if (!$this->connected) {
  647. // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error.
  648. return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version';
  649. } else {
  650. return $this->error;
  651. }
  652. }
  653. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  654. /**
  655. * Get last ID after an insert INSERT
  656. *
  657. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  658. * @param string $fieldid Field name
  659. * @return int Id of row
  660. */
  661. public function last_insert_id($tab, $fieldid = 'rowid')
  662. {
  663. // phpcs:enable
  664. return $this->db->lastInsertRowId();
  665. }
  666. /**
  667. * Encrypt sensitive data in database
  668. * Warning: This function includes the escape and add the SQL simple quotes on strings.
  669. *
  670. * @param string $fieldorvalue Field name or value to encrypt
  671. * @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
  672. * @return string XXX(field) or XXX('value') or field or 'value'
  673. */
  674. public function encrypt($fieldorvalue, $withQuotes = 1)
  675. {
  676. global $conf;
  677. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  678. $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
  679. //Encryption key
  680. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  681. $escapedstringwithquotes = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
  682. if ($cryptType && !empty($cryptKey)) {
  683. if ($cryptType == 2) {
  684. $escapedstringwithquotes = "AES_ENCRYPT(".$escapedstringwithquotes.", '".$this->escape($cryptKey)."')";
  685. } elseif ($cryptType == 1) {
  686. $escapedstringwithquotes = "DES_ENCRYPT(".$escapedstringwithquotes.", '".$this->escape($cryptKey)."')";
  687. }
  688. }
  689. return $escapedstringwithquotes;
  690. }
  691. /**
  692. * Decrypt sensitive data in database
  693. *
  694. * @param string $value Value to decrypt
  695. * @return string Decrypted value if used
  696. */
  697. public function decrypt($value)
  698. {
  699. global $conf;
  700. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  701. $cryptType = ($conf->db->dolibarr_main_db_encryption ? $conf->db->dolibarr_main_db_encryption : 0);
  702. //Encryption key
  703. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  704. $return = $value;
  705. if ($cryptType && !empty($cryptKey)) {
  706. if ($cryptType == 2) {
  707. $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  708. } elseif ($cryptType == 1) {
  709. $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  710. }
  711. }
  712. return $return;
  713. }
  714. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  715. /**
  716. * Return connexion ID
  717. *
  718. * @return string Id connexion
  719. */
  720. public function DDLGetConnectId()
  721. {
  722. // phpcs:enable
  723. return '?';
  724. }
  725. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  726. /**
  727. * Create a new database
  728. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  729. * We force to create database with charset this->forcecharset and collate this->forcecollate
  730. *
  731. * @param string $database Database name to create
  732. * @param string $charset Charset used to store data
  733. * @param string $collation Charset used to sort data
  734. * @param string $owner Username of database owner
  735. * @return SQLite3Result resource defined if OK, null if KO
  736. */
  737. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  738. {
  739. // phpcs:enable
  740. if (empty($charset)) {
  741. $charset = $this->forcecharset;
  742. }
  743. if (empty($collation)) {
  744. $collation = $this->forcecollate;
  745. }
  746. // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
  747. $sql = "CREATE DATABASE ".$this->escape($database);
  748. $sql .= " DEFAULT CHARACTER SET ".$this->escape($charset)." DEFAULT COLLATE ".$this->escape($collation);
  749. dol_syslog($sql, LOG_DEBUG);
  750. $ret = $this->query($sql);
  751. return $ret;
  752. }
  753. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  754. /**
  755. * List tables into a database
  756. *
  757. * @param string $database Name of database
  758. * @param string $table Name of table filter ('xxx%')
  759. * @return array List of tables in an array
  760. */
  761. public function DDLListTables($database, $table = '')
  762. {
  763. // phpcs:enable
  764. $listtables = array();
  765. $like = '';
  766. if ($table) {
  767. $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
  768. $like = "LIKE '".$this->escape($tmptable)."'";
  769. }
  770. $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i', '', $database);
  771. $sql = "SHOW TABLES FROM ".$tmpdatabase." ".$like.";";
  772. //print $sql;
  773. $result = $this->query($sql);
  774. if ($result) {
  775. while ($row = $this->fetch_row($result)) {
  776. $listtables[] = $row[0];
  777. }
  778. }
  779. return $listtables;
  780. }
  781. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  782. /**
  783. * List information of columns into a table.
  784. *
  785. * @param string $table Name of table
  786. * @return array Tableau des informations des champs de la table
  787. * TODO modify for sqlite
  788. */
  789. public function DDLInfoTable($table)
  790. {
  791. // phpcs:enable
  792. $infotables = array();
  793. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  794. $sql = "SHOW FULL COLUMNS FROM ".$tmptable.";";
  795. dol_syslog($sql, LOG_DEBUG);
  796. $result = $this->query($sql);
  797. if ($result) {
  798. while ($row = $this->fetch_row($result)) {
  799. $infotables[] = $row;
  800. }
  801. }
  802. return $infotables;
  803. }
  804. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  805. /**
  806. * Create a table into database
  807. *
  808. * @param string $table Nom de la table
  809. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  810. * @param string $primary_key Nom du champ qui sera la clef primaire
  811. * @param string $type Type de la table
  812. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  813. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  814. * @param array $keys Tableau des champs cles noms => valeur
  815. * @return int <0 if KO, >=0 if OK
  816. */
  817. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  818. {
  819. // phpcs:enable
  820. // FIXME: $fulltext_keys parameter is unused
  821. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  822. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  823. $sql = "create table ".$table."(";
  824. $i = 0;
  825. foreach ($fields as $field_name => $field_desc) {
  826. $sqlfields[$i] = $field_name." ";
  827. $sqlfields[$i] .= $field_desc['type'];
  828. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  829. $sqlfields[$i] .= "(".$field_desc['value'].")";
  830. } elseif (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  831. $sqlfields[$i] .= " ".$field_desc['attribute'];
  832. } elseif (preg_match("/^[^\s]/i", $field_desc['default'])) {
  833. if (preg_match("/null/i", $field_desc['default'])) {
  834. $sqlfields[$i] .= " default ".$field_desc['default'];
  835. } else {
  836. $sqlfields[$i] .= " default '".$this->escape($field_desc['default'])."'";
  837. }
  838. } elseif (preg_match("/^[^\s]/i", $field_desc['null'])) {
  839. $sqlfields[$i] .= " ".$field_desc['null'];
  840. } elseif (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  841. $sqlfields[$i] .= " ".$field_desc['extra'];
  842. }
  843. $i++;
  844. }
  845. if ($primary_key != "") {
  846. $pk = "primary key(".$primary_key.")";
  847. }
  848. if (is_array($unique_keys)) {
  849. $i = 0;
  850. foreach ($unique_keys as $key => $value) {
  851. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$this->escape($value)."')";
  852. $i++;
  853. }
  854. }
  855. if (is_array($keys)) {
  856. $i = 0;
  857. foreach ($keys as $key => $value) {
  858. $sqlk[$i] = "KEY ".$key." (".$value.")";
  859. $i++;
  860. }
  861. }
  862. $sql .= implode(',', $sqlfields);
  863. if ($primary_key != "") {
  864. $sql .= ",".$pk;
  865. }
  866. if (is_array($unique_keys)) {
  867. $sql .= ",".implode(',', $sqluq);
  868. }
  869. if (is_array($keys)) {
  870. $sql .= ",".implode(',', $sqlk);
  871. }
  872. $sql .= ") type=".$type;
  873. dol_syslog($sql, LOG_DEBUG);
  874. if (!$this -> query($sql)) {
  875. return -1;
  876. }
  877. return 1;
  878. }
  879. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  880. /**
  881. * Drop a table into database
  882. *
  883. * @param string $table Name of table
  884. * @return int <0 if KO, >=0 if OK
  885. */
  886. public function DDLDropTable($table)
  887. {
  888. // phpcs:enable
  889. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  890. $sql = "DROP TABLE ".$tmptable;
  891. if (!$this->query($sql)) {
  892. return -1;
  893. } else {
  894. return 1;
  895. }
  896. }
  897. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  898. /**
  899. * Return a pointer of line with description of a table or field
  900. *
  901. * @param string $table Name of table
  902. * @param string $field Optionnel : Name of field if we want description of field
  903. * @return bool|SQLite3Result Resource
  904. */
  905. public function DDLDescTable($table, $field = "")
  906. {
  907. // phpcs:enable
  908. $sql = "DESC ".$table." ".$field;
  909. dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
  910. $this->_results = $this->query($sql);
  911. return $this->_results;
  912. }
  913. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  914. /**
  915. * Create a new field into table
  916. *
  917. * @param string $table Name of table
  918. * @param string $field_name Name of field to add
  919. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  920. * @param string $field_position Optionnel ex.: "after champtruc"
  921. * @return int <0 if KO, >0 if OK
  922. */
  923. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  924. {
  925. // phpcs:enable
  926. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  927. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  928. $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
  929. $sql .= $field_desc['type'];
  930. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  931. if (!in_array($field_desc['type'], array('date', 'datetime'))) {
  932. $sql .= "(".$field_desc['value'].")";
  933. }
  934. }
  935. if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  936. $sql .= " ".$field_desc['attribute'];
  937. }
  938. if (preg_match("/^[^\s]/i", $field_desc['null'])) {
  939. $sql .= " ".$field_desc['null'];
  940. }
  941. if (preg_match("/^[^\s]/i", $field_desc['default'])) {
  942. if (preg_match("/null/i", $field_desc['default'])) {
  943. $sql .= " default ".$field_desc['default'];
  944. } else {
  945. $sql .= " default '".$this->escape($field_desc['default'])."'";
  946. }
  947. }
  948. if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  949. $sql .= " ".$field_desc['extra'];
  950. }
  951. $sql .= " ".$field_position;
  952. dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
  953. if (!$this->query($sql)) {
  954. return -1;
  955. }
  956. return 1;
  957. }
  958. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  959. /**
  960. * Update format of a field into a table
  961. *
  962. * @param string $table Name of table
  963. * @param string $field_name Name of field to modify
  964. * @param string $field_desc Array with description of field format
  965. * @return int <0 if KO, >0 if OK
  966. */
  967. public function DDLUpdateField($table, $field_name, $field_desc)
  968. {
  969. // phpcs:enable
  970. $sql = "ALTER TABLE ".$table;
  971. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  972. if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
  973. $sql .= "(".$field_desc['value'].")";
  974. }
  975. dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
  976. if (!$this->query($sql)) {
  977. return -1;
  978. }
  979. return 1;
  980. }
  981. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  982. /**
  983. * Drop a field from table
  984. *
  985. * @param string $table Name of table
  986. * @param string $field_name Name of field to drop
  987. * @return int <0 if KO, >0 if OK
  988. */
  989. public function DDLDropField($table, $field_name)
  990. {
  991. // phpcs:enable
  992. $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
  993. $sql = "ALTER TABLE ".$table." DROP COLUMN `".$tmp_field_name."`";
  994. if (!$this->query($sql)) {
  995. $this->error = $this->lasterror();
  996. return -1;
  997. }
  998. return 1;
  999. }
  1000. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1001. /**
  1002. * Create a user and privileges to connect to database (even if database does not exists yet)
  1003. *
  1004. * @param string $dolibarr_main_db_host Ip serveur
  1005. * @param string $dolibarr_main_db_user Nom user a creer
  1006. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  1007. * @param string $dolibarr_main_db_name Database name where user must be granted
  1008. * @return int <0 if KO, >=0 if OK
  1009. */
  1010. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  1011. {
  1012. // phpcs:enable
  1013. $sql = "INSERT INTO user ";
  1014. $sql .= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
  1015. $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')";
  1016. $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
  1017. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  1018. $resql = $this->query($sql);
  1019. if (!$resql) {
  1020. return -1;
  1021. }
  1022. $sql = "INSERT INTO db ";
  1023. $sql .= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)";
  1024. $sql .= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'";
  1025. $sql .= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')";
  1026. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
  1027. $resql = $this->query($sql);
  1028. if (!$resql) {
  1029. return -1;
  1030. }
  1031. $sql = "FLUSH Privileges";
  1032. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
  1033. $resql = $this->query($sql);
  1034. if (!$resql) {
  1035. return -1;
  1036. }
  1037. return 1;
  1038. }
  1039. /**
  1040. * Return charset used to store data in database
  1041. *
  1042. * @return string Charset
  1043. */
  1044. public function getDefaultCharacterSetDatabase()
  1045. {
  1046. return 'UTF-8';
  1047. }
  1048. /**
  1049. * Return list of available charset that can be used to store data in database
  1050. *
  1051. * @return array List of Charset
  1052. */
  1053. public function getListOfCharacterSet()
  1054. {
  1055. $liste = array();
  1056. $i = 0;
  1057. $liste[$i]['charset'] = 'UTF-8';
  1058. $liste[$i]['description'] = 'UTF-8';
  1059. return $liste;
  1060. }
  1061. /**
  1062. * Return collation used in database
  1063. *
  1064. * @return string Collation value
  1065. */
  1066. public function getDefaultCollationDatabase()
  1067. {
  1068. return 'UTF-8';
  1069. }
  1070. /**
  1071. * Return list of available collation that can be used for database
  1072. *
  1073. * @return array List of Collation
  1074. */
  1075. public function getListOfCollation()
  1076. {
  1077. $liste = array();
  1078. $i = 0;
  1079. $liste[$i]['charset'] = 'UTF-8';
  1080. $liste[$i]['description'] = 'UTF-8';
  1081. return $liste;
  1082. }
  1083. /**
  1084. * Return full path of dump program
  1085. *
  1086. * @return string Full path of dump program
  1087. */
  1088. public function getPathOfDump()
  1089. {
  1090. // FIXME: not for SQLite
  1091. $fullpathofdump = '/pathtomysqldump/mysqldump';
  1092. $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
  1093. if ($resql) {
  1094. $liste = $this->fetch_array($resql);
  1095. $basedir = $liste['Value'];
  1096. $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
  1097. }
  1098. return $fullpathofdump;
  1099. }
  1100. /**
  1101. * Return full path of restore program
  1102. *
  1103. * @return string Full path of restore program
  1104. */
  1105. public function getPathOfRestore()
  1106. {
  1107. // FIXME: not for SQLite
  1108. $fullpathofimport = '/pathtomysql/mysql';
  1109. $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
  1110. if ($resql) {
  1111. $liste = $this->fetch_array($resql);
  1112. $basedir = $liste['Value'];
  1113. $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
  1114. }
  1115. return $fullpathofimport;
  1116. }
  1117. /**
  1118. * Return value of server parameters
  1119. *
  1120. * @param string $filter Filter list on a particular value
  1121. * @return array Array of key-values (key=>value)
  1122. */
  1123. public function getServerParametersValues($filter = '')
  1124. {
  1125. $result = array();
  1126. static $pragmas;
  1127. if (!isset($pragmas)) {
  1128. // Définition de la liste des pragmas utilisés qui ne retournent qu'une seule valeur
  1129. // indépendante de la base de données.
  1130. // cf. http://www.sqlite.org/pragma.html
  1131. $pragmas = array(
  1132. 'application_id', 'auto_vacuum', 'automatic_index', 'busy_timeout', 'cache_size',
  1133. 'cache_spill', 'case_sensitive_like', 'checkpoint_fullsync', 'collation_list',
  1134. 'compile_options', 'data_version', /*'database_list',*/
  1135. 'defer_foreign_keys', 'encoding', 'foreign_key_check', 'freelist_count',
  1136. 'full_column_names', 'fullsync', 'ingore_check_constraints', 'integrity_check',
  1137. 'journal_mode', 'journal_size_limit', 'legacy_file_format', 'locking_mode',
  1138. 'max_page_count', 'page_count', 'page_size', 'parser_trace',
  1139. 'query_only', 'quick_check', 'read_uncommitted', 'recursive_triggers',
  1140. 'reverse_unordered_selects', 'schema_version', 'user_version',
  1141. 'secure_delete', 'short_column_names', 'shrink_memory', 'soft_heap_limit',
  1142. 'synchronous', 'temp_store', /*'temp_store_directory',*/ 'threads',
  1143. 'vdbe_addoptrace', 'vdbe_debug', 'vdbe_listing', 'vdbe_trace',
  1144. 'wal_autocheckpoint',
  1145. );
  1146. }
  1147. // TODO prendre en compte le filtre
  1148. foreach ($pragmas as $var) {
  1149. $sql = "PRAGMA $var";
  1150. $resql = $this->query($sql);
  1151. if ($resql) {
  1152. $obj = $this->fetch_row($resql);
  1153. //dol_syslog(get_class($this)."::select_db getServerParametersValues $var=". print_r($obj, true), LOG_DEBUG);
  1154. $result[$var] = $obj[0];
  1155. } else {
  1156. // TODO Récupérer le message
  1157. $result[$var] = 'FAIL';
  1158. }
  1159. }
  1160. return $result;
  1161. }
  1162. /**
  1163. * Return value of server status
  1164. *
  1165. * @param string $filter Filter list on a particular value
  1166. * @return array Array of key-values (key=>value)
  1167. */
  1168. public function getServerStatusValues($filter = '')
  1169. {
  1170. $result = array();
  1171. /*
  1172. $sql='SHOW STATUS';
  1173. if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
  1174. $resql=$this->query($sql);
  1175. if ($resql)
  1176. {
  1177. while ($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
  1178. }
  1179. */
  1180. return $result;
  1181. }
  1182. /**
  1183. * Permet le chargement d'une fonction personnalisee dans le moteur de base de donnees.
  1184. * Note: le nom de la fonction personnalisee est prefixee par 'db'. La fonction doit être
  1185. * statique et publique. Le nombre de parametres est determine automatiquement.
  1186. *
  1187. * @param string $name Le nom de la fonction a definir dans Sqlite
  1188. * @param int $arg_count Arg count
  1189. * @return void
  1190. */
  1191. private function addCustomFunction($name, $arg_count = -1)
  1192. {
  1193. if ($this->db) {
  1194. $newname = preg_replace('/_/', '', $name);
  1195. $localname = __CLASS__.'::db'.$newname;
  1196. $reflectClass = new ReflectionClass(__CLASS__);
  1197. $reflectFunction = $reflectClass->getMethod('db'.$newname);
  1198. if ($arg_count < 0) {
  1199. $arg_count = $reflectFunction->getNumberOfParameters();
  1200. }
  1201. if (!$this->db->createFunction($name, $localname, $arg_count)) {
  1202. $this->error = "unable to create custom function '$name'";
  1203. }
  1204. }
  1205. }
  1206. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1207. /**
  1208. * calc_daynr
  1209. *
  1210. * @param int $year Year
  1211. * @param int $month Month
  1212. * @param int $day Day
  1213. * @return int Formatted date
  1214. */
  1215. private static function calc_daynr($year, $month, $day)
  1216. {
  1217. // phpcs:enable
  1218. $y = $year;
  1219. if ($y == 0 && $month == 0) {
  1220. return 0;
  1221. }
  1222. $num = (365 * $y + 31 * ($month - 1) + $day);
  1223. if ($month <= 2) {
  1224. $y--;
  1225. } else {
  1226. $num -= floor(($month * 4 + 23) / 10);
  1227. }
  1228. $temp = floor(($y / 100 + 1) * 3 / 4);
  1229. return $num + floor($y / 4) - $temp;
  1230. }
  1231. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1232. /**
  1233. * calc_weekday
  1234. *
  1235. * @param int $daynr ???
  1236. * @param bool $sunday_first_day_of_week ???
  1237. * @return int
  1238. */
  1239. private static function calc_weekday($daynr, $sunday_first_day_of_week)
  1240. {
  1241. // phpcs:enable
  1242. $ret = floor(($daynr + 5 + ($sunday_first_day_of_week ? 1 : 0)) % 7);
  1243. return $ret;
  1244. }
  1245. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1246. /**
  1247. * calc_days_in_year
  1248. *
  1249. * @param string $year Year
  1250. * @return int Nb of days in year
  1251. */
  1252. private static function calc_days_in_year($year)
  1253. {
  1254. // phpcs:enable
  1255. return (($year & 3) == 0 && ($year % 100 || ($year % 400 == 0 && $year)) ? 366 : 365);
  1256. }
  1257. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1258. /**
  1259. * calc_week
  1260. *
  1261. * @param string $year Year
  1262. * @param string $month Month
  1263. * @param string $day Day
  1264. * @param string $week_behaviour Week behaviour
  1265. * @param string $calc_year ???
  1266. * @return string ???
  1267. */
  1268. private static function calc_week($year, $month, $day, $week_behaviour, &$calc_year)
  1269. {
  1270. // phpcs:enable
  1271. $daynr = self::calc_daynr($year, $month, $day);
  1272. $first_daynr = self::calc_daynr($year, 1, 1);
  1273. $monday_first = ($week_behaviour & self::WEEK_MONDAY_FIRST) ? 1 : 0;
  1274. $week_year = ($week_behaviour & self::WEEK_YEAR) ? 1 : 0;
  1275. $first_weekday = ($week_behaviour & self::WEEK_FIRST_WEEKDAY) ? 1 : 0;
  1276. $weekday = self::calc_weekday($first_daynr, !$monday_first);
  1277. $calc_year = $year;
  1278. if ($month == 1 && $day <= 7 - $weekday) {
  1279. if (!$week_year && (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4))) {
  1280. return 0;
  1281. }
  1282. $week_year = 1;
  1283. $calc_year--;
  1284. $first_daynr -= ($days = self::calc_days_in_year($calc_year));
  1285. $weekday = ($weekday + 53 * 7 - $days) % 7;
  1286. }
  1287. if (($first_weekday && $weekday != 0) || (!$first_weekday && $weekday >= 4)) {
  1288. $days = $daynr - ($first_daynr + (7 - $weekday));
  1289. } else {
  1290. $days = $daynr - ($first_daynr - $weekday);
  1291. }
  1292. if ($week_year && $days >= 52 * 7) {
  1293. $weekday = ($weekday + self::calc_days_in_year($calc_year)) % 7;
  1294. if ((!$first_weekday && $weekday < 4) || ($first_weekday && $weekday == 0)) {
  1295. $calc_year++;
  1296. return 1;
  1297. }
  1298. }
  1299. return floor($days / 7 + 1);
  1300. }
  1301. }