sqlite3.class.php 46 KB

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