export.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. <?php
  2. /* Copyright (C) 2005-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2012 Charles-Fr BENKE <charles.fr@benke.fr>
  5. * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file htdocs/exports/class/export.class.php
  22. * \ingroup export
  23. * \brief File of class to manage exports
  24. */
  25. /**
  26. * Class to manage exports
  27. */
  28. class Export
  29. {
  30. /**
  31. * @var DoliDB Database handler.
  32. */
  33. public $db;
  34. /**
  35. * @var int
  36. */
  37. public $id;
  38. public $array_export_icon;
  39. public $array_export_perms;
  40. /**
  41. * @var string Last error message
  42. */
  43. public $error;
  44. /**
  45. * @var string Last error code
  46. */
  47. public $errno;
  48. /**
  49. * @var string[] Error messages
  50. */
  51. public $errors;
  52. public $array_export_code = array(); // Tableau de "idmodule_numexportprofile"
  53. public $array_export_code_for_sort = array(); // Tableau de "idmodule_numexportprofile"
  54. public $array_export_module = array(); // Tableau de "nom de modules"
  55. public $array_export_label = array(); // Tableau de "libelle de lots"
  56. public $array_export_sql_start = array(); // Tableau des "requetes sql"
  57. public $array_export_sql_end = array(); // Tableau des "requetes sql"
  58. public $array_export_sql_order = array(); // Tableau des "requetes sql"
  59. public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
  60. public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
  61. public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
  62. public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
  63. public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
  64. public $array_export_special = array(); // array of special operations to do on field
  65. public $array_export_examplevalues = array(); // array with examples for fields
  66. public $array_export_help = array(); // array with tooltip help for fields
  67. // To store export templates
  68. public $hexa; // List of fields in the export profile
  69. public $hexafiltervalue; // List of search criteria in the export profile
  70. public $datatoexport;
  71. public $model_name; // Name of export profile
  72. public $fk_user;
  73. public $sqlusedforexport;
  74. /**
  75. * Constructor
  76. *
  77. * @param DoliDB $db Database handler
  78. */
  79. public function __construct($db)
  80. {
  81. $this->db = $db;
  82. }
  83. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  84. /**
  85. * Load an exportable dataset
  86. *
  87. * @param User $user Object user making export
  88. * @param string $filter Load a particular dataset only
  89. * @return int Return integer <0 if KO, >0 if OK
  90. */
  91. public function load_arrays($user, $filter = '')
  92. {
  93. // phpcs:enable
  94. global $langs, $conf, $mysoc;
  95. dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
  96. $i = 0;
  97. // Define list of modules directories into modulesdir
  98. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  99. $modulesdir = dolGetModulesDirs();
  100. foreach ($modulesdir as $dir) {
  101. // Search available exports
  102. $handle = @opendir(dol_osencode($dir));
  103. if (is_resource($handle)) {
  104. // Search module files
  105. while (($file = readdir($handle)) !== false) {
  106. $reg = array();
  107. if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
  108. $modulename = $reg[1];
  109. // Defined if module is enabled
  110. $enabled = true;
  111. $part = strtolower(preg_replace('/^mod/i', '', $modulename));
  112. if ($part == 'propale') {
  113. $part = 'propal';
  114. }
  115. if (empty($conf->$part->enabled)) {
  116. $enabled = false;
  117. }
  118. if ($enabled) {
  119. // Loading Class
  120. $file = $dir.$modulename.".class.php";
  121. $classname = $modulename;
  122. require_once $file;
  123. $module = new $classname($this->db);
  124. if (isset($module->export_code) && is_array($module->export_code)) {
  125. foreach ($module->export_code as $r => $value) {
  126. //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
  127. if ($filter && ($filter != $module->export_code[$r])) {
  128. continue;
  129. }
  130. // Test if condition to show are ok
  131. if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) {
  132. continue;
  133. }
  134. // Test if permissions are ok
  135. $bool = true;
  136. if (isset($module->export_permission)) {
  137. foreach ($module->export_permission[$r] as $val) {
  138. $perm = $val;
  139. //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
  140. if (!empty($perm[2])) {
  141. $bool = isset($user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}) ? $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]} : false;
  142. } else {
  143. $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false;
  144. }
  145. if ($perm[0] == 'user' && $user->admin) {
  146. $bool = true;
  147. }
  148. if (!$bool) {
  149. break;
  150. }
  151. }
  152. }
  153. //print $bool." $perm[0]"."<br>";
  154. // Permissions ok
  155. // if ($bool)
  156. // {
  157. // Charge fichier lang en rapport
  158. $langtoload = $module->getLangFilesArray();
  159. if (is_array($langtoload)) {
  160. foreach ($langtoload as $key) {
  161. $langs->load($key);
  162. }
  163. }
  164. // Module
  165. $this->array_export_module[$i] = $module;
  166. // Permission
  167. $this->array_export_perms[$i] = $bool;
  168. // Icon
  169. $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
  170. // Code of the export dataset / Code du dataset export
  171. $this->array_export_code[$i] = $module->export_code[$r];
  172. // Define a key for sort
  173. $this->array_export_code_for_sort[$i] = $module->module_position.'_'.$module->export_code[$r]; // Add a key into the module
  174. // Export Dataset Label / Libelle du dataset export
  175. $this->array_export_label[$i] = $module->getExportDatasetLabel($r);
  176. // Table of fields to export / Tableau des champ a exporter (cle=champ, valeur=libelle)
  177. $this->array_export_fields[$i] = $module->export_fields_array[$r];
  178. // Table of fields to be filtered / Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres
  179. $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
  180. // Table of entities for export / Tableau des entites a exporter (cle=champ, valeur=entite)
  181. $this->array_export_entities[$i] = $module->export_entities_array[$r];
  182. // Table of entities requiring DISTINCT abandonment / Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records)
  183. $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
  184. // Table of special field operations / Tableau des operations speciales sur champ
  185. $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
  186. // Array of examples
  187. $this->array_export_examplevalues[$i] = (!empty($module->export_examplevalues_array[$r]) ? $module->export_examplevalues_array[$r] : null);
  188. // Array of help tooltips
  189. $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
  190. // SQL dataset query / Requete SQL du dataset
  191. $this->array_export_sql_start[$i] = $module->export_sql_start[$r];
  192. $this->array_export_sql_end[$i] = $module->export_sql_end[$r];
  193. $this->array_export_sql_order[$i] = (!empty($module->export_sql_order[$r]) ? $module->export_sql_order[$r] : null);
  194. //$this->array_export_sql[$i]=$module->export_sql[$r];
  195. dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(!empty($module->export_fields_code[$r]) ? count($module->export_fields_code[$r]) : ''));
  196. $i++;
  197. // }
  198. }
  199. }
  200. }
  201. }
  202. }
  203. closedir($handle);
  204. }
  205. }
  206. return 1;
  207. }
  208. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  209. /**
  210. * Build the sql export request.
  211. * Arrays this->array_export_xxx are already loaded for required datatoexport
  212. *
  213. * @param int $indice Indice of export
  214. * @param array $array_selected Filter fields on array of fields to export
  215. * @param array $array_filterValue Filter records on array of value for fields
  216. * @return string SQL String. Example "select s.rowid as r_rowid, s.status as s_status from ..."
  217. */
  218. public function build_sql($indice, $array_selected, $array_filterValue)
  219. {
  220. // phpcs:enable
  221. // Build the sql request
  222. $sql = $this->array_export_sql_start[$indice];
  223. $i = 0;
  224. //print_r($array_selected);
  225. foreach ($this->array_export_fields[$indice] as $key => $value) {
  226. if (!array_key_exists($key, $array_selected)) {
  227. continue; // Field not selected
  228. }
  229. if (preg_match('/^none\./', $key)) {
  230. continue; // A field that must not appears into SQL
  231. }
  232. if ($i > 0) {
  233. $sql .= ', ';
  234. } else {
  235. $i++;
  236. }
  237. if (strpos($key, ' as ') === false) {
  238. $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
  239. } else {
  240. $newfield = $key;
  241. }
  242. $sql .= $newfield;
  243. }
  244. $sql .= $this->array_export_sql_end[$indice];
  245. // Add the WHERE part. Filtering into sql if a filtering array is provided
  246. if (is_array($array_filterValue) && !empty($array_filterValue)) {
  247. $sqlWhere = '';
  248. // Loop on each condition to add
  249. foreach ($array_filterValue as $key => $value) {
  250. if (preg_match('/GROUP_CONCAT/i', $key)) {
  251. continue;
  252. }
  253. if ($value != '') {
  254. $sqlWhere .= " AND ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
  255. }
  256. }
  257. $sql .= $sqlWhere;
  258. }
  259. // Add the sort order
  260. $sql .= $this->array_export_sql_order[$indice];
  261. // Add the HAVING part.
  262. if (is_array($array_filterValue) && !empty($array_filterValue)) {
  263. // Loop on each condition to add
  264. foreach ($array_filterValue as $key => $value) {
  265. if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
  266. $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
  267. }
  268. }
  269. }
  270. return $sql;
  271. }
  272. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  273. /**
  274. * Build the conditionnal string from filter the query
  275. *
  276. * @param string $TypeField Type of Field to filter
  277. * @param string $NameField Name of the field to filter
  278. * @param string $ValueField Value of the field for filter. Must not be ''
  279. * @return string SQL string of then field ex : "field='xxx'"
  280. */
  281. public function build_filterQuery($TypeField, $NameField, $ValueField)
  282. {
  283. // phpcs:enable
  284. $NameField = sanitizeVal($NameField, 'aZ09');
  285. $szFilterQuery = '';
  286. //print $TypeField." ".$NameField." ".$ValueField;
  287. $InfoFieldList = explode(":", $TypeField);
  288. // build the input field on depend of the type of file
  289. switch ($InfoFieldList[0]) {
  290. case 'Text':
  291. if (!(strpos($ValueField, '%') === false)) {
  292. $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
  293. } else {
  294. $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
  295. }
  296. break;
  297. case 'Date':
  298. if (strpos($ValueField, "+") > 0) {
  299. // mode plage
  300. $ValueArray = explode("+", $ValueField);
  301. $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
  302. $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
  303. } else {
  304. if (is_numeric(substr($ValueField, 0, 1))) {
  305. $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
  306. } else {
  307. $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
  308. }
  309. }
  310. break;
  311. case 'Duree':
  312. break;
  313. case 'Numeric':
  314. // if there is a signe +
  315. if (strpos($ValueField, "+") > 0) {
  316. // mode plage
  317. $ValueArray = explode("+", $ValueField);
  318. $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
  319. $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
  320. } else {
  321. if (is_numeric(substr($ValueField, 0, 1))) {
  322. $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
  323. } else {
  324. $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
  325. }
  326. }
  327. break;
  328. case 'Boolean':
  329. $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
  330. break;
  331. case 'FormSelect':
  332. if (is_numeric($ValueField) && $ValueField > 0) {
  333. $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
  334. } else {
  335. $szFilterQuery = " 1=1"; // Test always true
  336. }
  337. break;
  338. case 'Status':
  339. case 'List':
  340. if (is_numeric($ValueField)) {
  341. $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
  342. } else {
  343. if (!(strpos($ValueField, '%') === false)) {
  344. $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
  345. } else {
  346. $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
  347. }
  348. }
  349. break;
  350. default:
  351. dol_syslog("Error we try to forge an sql export request with a condition on a field with type ".$InfoFieldList[0]." (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR);
  352. }
  353. return $szFilterQuery;
  354. }
  355. /**
  356. * conditionDate
  357. *
  358. * @param string $Field Field operand 1
  359. * @param string $Value Value operand 2
  360. * @param string $Sens Comparison operator
  361. * @return string
  362. */
  363. public function conditionDate($Field, $Value, $Sens)
  364. {
  365. // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
  366. if (strlen($Value) == 4) {
  367. $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
  368. } elseif (strlen($Value) == 6) {
  369. $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
  370. } else {
  371. $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
  372. }
  373. return $Condition;
  374. }
  375. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  376. /**
  377. * Build an input field used to filter the query
  378. *
  379. * @param string $TypeField Type of Field to filter. Example: Text, Date, List:c_country:label:rowid, List:c_stcom:label:code, Numeric or Number, Boolean
  380. * @param string $NameField Name of the field to filter
  381. * @param string $ValueField Initial value of the field to filter
  382. * @return string html string of the input field ex : "<input type=text name=... value=...>"
  383. */
  384. public function build_filterField($TypeField, $NameField, $ValueField)
  385. {
  386. // phpcs:enable
  387. global $conf, $langs, $form;
  388. $szFilterField = '';
  389. $InfoFieldList = explode(":", $TypeField);
  390. // build the input field on depend of the type of file
  391. switch ($InfoFieldList[0]) {
  392. case 'Text':
  393. case 'Date':
  394. $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
  395. break;
  396. case 'Duree':
  397. case 'Numeric':
  398. case 'Number':
  399. // Must be a string text to allow to use comparison strings like "<= 99.9"
  400. $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
  401. break;
  402. case 'Status':
  403. $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
  404. break;
  405. case 'Boolean':
  406. $szFilterField = '<select name="'.$NameField.'" class="flat">';
  407. $szFilterField .= '<option ';
  408. if ($ValueField == '') {
  409. $szFilterField .= ' selected ';
  410. }
  411. $szFilterField .= ' value="">&nbsp;</option>';
  412. $szFilterField .= '<option ';
  413. if ($ValueField == 'yes' || $ValueField == '1') {
  414. $szFilterField .= ' selected ';
  415. }
  416. $szFilterField .= ' value="1">'.yn(1).'</option>';
  417. $szFilterField .= '<option ';
  418. if ($ValueField == 'no' || $ValueField == '0') {
  419. $szFilterField .= ' selected ';
  420. }
  421. $szFilterField .= ' value="0">'.yn(0).'</option>';
  422. $szFilterField .= "</select>";
  423. break;
  424. case 'FormSelect':
  425. //var_dump($NameField);
  426. if ($InfoFieldList[1] == 'select_company') {
  427. $szFilterField .= $form->select_company('', $NameField, '', 1);
  428. } elseif ($InfoFieldList[1] == 'selectcontacts') {
  429. $szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;');
  430. } elseif ($InfoFieldList[1] == 'select_dolusers') {
  431. $szFilterField .= $form->select_dolusers('', $NameField, 1);
  432. }
  433. break;
  434. case 'List':
  435. // 0 : Type of the field / Type du champ
  436. // 1 : Name of the table / Nom de la table
  437. // 2 : Name of the field containing the label / Nom du champ contenant le libelle
  438. // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
  439. // 4 : Name of element for getEntity().
  440. if (!empty($InfoFieldList[3])) {
  441. $keyList = $InfoFieldList[3];
  442. } else {
  443. $keyList = 'rowid';
  444. }
  445. $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
  446. if ($InfoFieldList[1] == 'c_stcomm') {
  447. $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
  448. }
  449. if ($InfoFieldList[1] == 'c_country') {
  450. $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
  451. }
  452. $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
  453. if (!empty($InfoFieldList[4])) {
  454. $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
  455. }
  456. $resql = $this->db->query($sql);
  457. if ($resql) {
  458. $szFilterField = '<select class="flat" name="'.$NameField.'">';
  459. $szFilterField .= '<option value="0">&nbsp;</option>';
  460. $num = $this->db->num_rows($resql);
  461. $i = 0;
  462. if ($num) {
  463. while ($i < $num) {
  464. $obj = $this->db->fetch_object($resql);
  465. if ($obj->label == '-') {
  466. // Discard entry '-'
  467. $i++;
  468. continue;
  469. }
  470. //var_dump($InfoFieldList[1]);
  471. $labeltoshow = dol_trunc($obj->label, 18);
  472. if ($InfoFieldList[1] == 'c_stcomm') {
  473. $langs->load("companies");
  474. $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
  475. }
  476. if ($InfoFieldList[1] == 'c_country') {
  477. //var_dump($sql);
  478. $langs->load("dict");
  479. $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
  480. }
  481. if (!empty($ValueField) && $ValueField == $obj->rowid) {
  482. $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  483. } else {
  484. $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
  485. }
  486. $i++;
  487. }
  488. }
  489. $szFilterField .= "</select>";
  490. $this->db->free($resql);
  491. } else {
  492. dol_print_error($this->db);
  493. }
  494. break;
  495. }
  496. return $szFilterField;
  497. }
  498. /**
  499. * Build an input field used to filter the query
  500. *
  501. * @param string $TypeField Type of Field to filter
  502. * @return string html string of the input field ex : "<input type=text name=... value=...>"
  503. */
  504. public function genDocFilter($TypeField)
  505. {
  506. global $langs;
  507. $szMsg = '';
  508. $InfoFieldList = explode(":", $TypeField);
  509. // build the input field on depend of the type of file
  510. switch ($InfoFieldList[0]) {
  511. case 'Text':
  512. $szMsg = $langs->trans('ExportStringFilter');
  513. break;
  514. case 'Date':
  515. $szMsg = $langs->trans('ExportDateFilter');
  516. break;
  517. case 'Duree':
  518. break;
  519. case 'Numeric':
  520. $szMsg = $langs->trans('ExportNumericFilter');
  521. break;
  522. case 'Boolean':
  523. break;
  524. case 'List':
  525. break;
  526. }
  527. return $szMsg;
  528. }
  529. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  530. /**
  531. * Build export file.
  532. * File is built into directory $conf->export->dir_temp.'/'.$user->id
  533. * Arrays this->array_export_xxx are already loaded for required datatoexport
  534. *
  535. * @param User $user User that export
  536. * @param string $model Export format
  537. * @param string $datatoexport Name of dataset to export
  538. * @param array $array_selected Filter on array of fields to export
  539. * @param array $array_filterValue Filter on array of fields with a filter
  540. * @param string $sqlquery If set, transmit the sql request for select (otherwise, sql request is generated from arrays)
  541. * @param string $separator separator to fill $objmodel->separator with the new separator
  542. * @return int Return integer <0 if KO, >0 if OK
  543. */
  544. public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
  545. {
  546. // phpcs:enable
  547. global $conf, $langs, $mysoc;
  548. $indice = 0;
  549. asort($array_selected);
  550. dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
  551. // Check parameters or context properties
  552. if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
  553. $this->error = "ErrorBadParameter";
  554. dol_syslog($this->error, LOG_ERR);
  555. return -1;
  556. }
  557. // Creation of class to export using model ExportXXX
  558. $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
  559. $file = "export_".$model.".modules.php";
  560. $classname = "Export".$model;
  561. require_once $dir.$file;
  562. $objmodel = new $classname($this->db);
  563. if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator)) {
  564. $objmodel->separator = $separator;
  565. }
  566. if (!empty($sqlquery)) {
  567. $sql = $sqlquery;
  568. } else {
  569. // Define value for indice from $datatoexport
  570. $foundindice = 0;
  571. foreach ($this->array_export_code as $key => $dataset) {
  572. if ($datatoexport == $dataset) {
  573. $indice = $key;
  574. $foundindice++;
  575. //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
  576. break;
  577. }
  578. }
  579. if (empty($foundindice)) {
  580. $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
  581. return -1;
  582. }
  583. $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
  584. }
  585. // Run the SQL
  586. $this->sqlusedforexport = $sql;
  587. dol_syslog(__METHOD__, LOG_DEBUG);
  588. $resql = $this->db->query($sql);
  589. if ($resql) {
  590. //$this->array_export_label[$indice]
  591. if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
  592. $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
  593. } else {
  594. $filename = "export_".$datatoexport;
  595. }
  596. if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
  597. $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
  598. }
  599. $filename .= '.'.$objmodel->getDriverExtension();
  600. $dirname = $conf->export->dir_temp.'/'.$user->id;
  601. $outputlangs = clone $langs; // We clone to have an object we can modify (for example to change output charset by csv handler) without changing original value
  602. // Open file
  603. dol_mkdir($dirname);
  604. $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
  605. if ($result >= 0) {
  606. // Generate header
  607. $objmodel->write_header($outputlangs);
  608. // Generate title line
  609. $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
  610. while ($obj = $this->db->fetch_object($resql)) {
  611. // Process special operations
  612. if (!empty($this->array_export_special[$indice])) {
  613. foreach ($this->array_export_special[$indice] as $key => $value) {
  614. if (!array_key_exists($key, $array_selected)) {
  615. continue; // Field not selected
  616. }
  617. // Operation NULLIFNEG
  618. if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') {
  619. //$alias=$this->array_export_alias[$indice][$key];
  620. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  621. if ($obj->$alias < 0) {
  622. $obj->$alias = '';
  623. }
  624. } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') {
  625. // Operation ZEROIFNEG
  626. //$alias=$this->array_export_alias[$indice][$key];
  627. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  628. if ($obj->$alias < 0) {
  629. $obj->$alias = '0';
  630. }
  631. } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') {
  632. // Operation GETNUMOPENDAYS (for Holiday module)
  633. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  634. //$alias=$this->array_export_alias[$indice][$key];
  635. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  636. $obj->$alias = num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code);
  637. } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') {
  638. // Operation INVOICEREMAINTOPAY
  639. //$alias=$this->array_export_alias[$indice][$key];
  640. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  641. $remaintopay = '';
  642. if ($obj->f_rowid > 0) {
  643. global $tmpobjforcomputecall;
  644. if (!is_object($tmpobjforcomputecall)) {
  645. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  646. $tmpobjforcomputecall = new Facture($this->db);
  647. }
  648. $tmpobjforcomputecall->id = $obj->f_rowid;
  649. $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
  650. $tmpobjforcomputecall->close_code = $obj->f_close_code;
  651. $remaintopay = $tmpobjforcomputecall->getRemainToPay();
  652. }
  653. $obj->$alias = $remaintopay;
  654. } elseif (is_array($this->array_export_special[$indice][$key]) &&
  655. !empty($this->array_export_special[$indice][$key]['rule']) &&
  656. $this->array_export_special[$indice][$key]['rule'] == 'compute'
  657. ) {
  658. // Custom compute
  659. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  660. $value = '';
  661. if (!empty($this->array_export_special[$indice][$key]['class']) &&
  662. !empty($this->array_export_special[$indice][$key]['classfile']) &&
  663. !empty($this->array_export_special[$indice][$key]['method'])
  664. ) {
  665. if (!dol_include_once($this->array_export_special[$indice][$key]['classfile'])) {
  666. $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['classfile']} not found";
  667. return -1;
  668. }
  669. if (!class_exists($this->array_export_special[$indice][$key]['class'])) {
  670. $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['class']} class doesn't exist";
  671. return -1;
  672. }
  673. $className = $this->array_export_special[$indice][$key]['class'];
  674. $tmpObject = new $className($this->db);
  675. if (!method_exists($tmpObject, $this->array_export_special[$indice][$key]['method'])) {
  676. $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['method']} method doesn't exist";
  677. return -1;
  678. }
  679. $methodName = $this->array_export_special[$indice][$key]['method'];
  680. $params = [];
  681. if (!empty($this->array_export_special[$indice][$key]['method_params'])) {
  682. foreach ($this->array_export_special[$indice][$key]['method_params'] as $paramName) {
  683. $params[] = $obj->$paramName ?? null;
  684. }
  685. }
  686. $value = $tmpObject->$methodName(...$params);
  687. }
  688. $obj->$alias = $value;
  689. } else {
  690. // TODO FIXME
  691. // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
  692. // Also the formula may contains objects of class that are not loaded.
  693. $computestring = $this->array_export_special[$indice][$key];
  694. //$tmp = dol_eval($computestring, 1, 0, '1');
  695. //$obj->$alias = $tmp;
  696. $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
  697. return -1;
  698. }
  699. }
  700. }
  701. // end of special operation processing
  702. $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
  703. }
  704. // Generate Footer
  705. $objmodel->write_footer($outputlangs);
  706. // Close file
  707. $objmodel->close_file();
  708. return 1;
  709. } else {
  710. $this->error = $objmodel->error;
  711. dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
  712. return -1;
  713. }
  714. } else {
  715. $this->error = $this->db->error()." - sql=".$sql;
  716. return -1;
  717. }
  718. }
  719. /**
  720. * Save an export model in database
  721. *
  722. * @param User $user Object user that save
  723. * @return int Return integer <0 if KO, >0 if OK
  724. */
  725. public function create($user)
  726. {
  727. global $conf;
  728. dol_syslog("Export.class.php::create");
  729. $this->db->begin();
  730. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
  731. $sql .= 'label,';
  732. $sql .= 'type,';
  733. $sql .= 'field,';
  734. $sql .= 'fk_user,';
  735. $sql .= 'filter';
  736. $sql .= ') VALUES (';
  737. $sql .= "'".$this->db->escape($this->model_name)."',";
  738. $sql .= " '".$this->db->escape($this->datatoexport)."',";
  739. $sql .= " '".$this->db->escape($this->hexa)."',";
  740. $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
  741. $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
  742. $sql .= ")";
  743. $resql = $this->db->query($sql);
  744. if ($resql) {
  745. $this->db->commit();
  746. return 1;
  747. } else {
  748. $this->error = $this->db->lasterror();
  749. $this->errno = $this->db->lasterrno();
  750. $this->db->rollback();
  751. return -1;
  752. }
  753. }
  754. /**
  755. * Load an export profil from database
  756. *
  757. * @param int $id Id of profil to load
  758. * @return int Return integer <0 if KO, >0 if OK
  759. */
  760. public function fetch($id)
  761. {
  762. $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
  763. $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
  764. $sql .= ' WHERE em.rowid = '.((int) $id);
  765. dol_syslog("Export::fetch", LOG_DEBUG);
  766. $result = $this->db->query($sql);
  767. if ($result) {
  768. $obj = $this->db->fetch_object($result);
  769. if ($obj) {
  770. $this->id = $obj->rowid;
  771. $this->model_name = $obj->label;
  772. $this->datatoexport = $obj->type;
  773. $this->hexa = $obj->field;
  774. $this->hexafiltervalue = $obj->filter;
  775. return 1;
  776. } else {
  777. $this->error = "ModelNotFound";
  778. return -2;
  779. }
  780. } else {
  781. dol_print_error($this->db);
  782. return -3;
  783. }
  784. }
  785. /**
  786. * Delete object in database
  787. *
  788. * @param User $user User that delete
  789. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  790. * @return int Return integer <0 if KO, >0 if OK
  791. */
  792. public function delete($user, $notrigger = 0)
  793. {
  794. global $conf, $langs;
  795. $error = 0;
  796. $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
  797. $sql .= " WHERE rowid=".((int) $this->id);
  798. $this->db->begin();
  799. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  800. $resql = $this->db->query($sql);
  801. if (!$resql) {
  802. $error++;
  803. $this->errors[] = "Error ".$this->db->lasterror();
  804. }
  805. // Commit or rollback
  806. if ($error) {
  807. foreach ($this->errors as $errmsg) {
  808. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  809. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  810. }
  811. $this->db->rollback();
  812. return -1 * $error;
  813. } else {
  814. $this->db->commit();
  815. return 1;
  816. }
  817. }
  818. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  819. /**
  820. * Output list all export models
  821. * --TODO Move this into a class htmlxxx.class.php--
  822. *
  823. * @return void
  824. */
  825. public function list_export_model()
  826. {
  827. // phpcs:enable
  828. global $conf, $langs;
  829. $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
  830. $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
  831. $sql .= " ORDER BY rowid";
  832. $result = $this->db->query($sql);
  833. if ($result) {
  834. $num = $this->db->num_rows($result);
  835. $i = 0;
  836. while ($i < $num) {
  837. $obj = $this->db->fetch_object($result);
  838. $keyModel = array_search($obj->type, $this->array_export_code);
  839. print "<tr>";
  840. print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
  841. print '<td>';
  842. print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
  843. print $this->array_export_module[$keyModel]->getName().' - ';
  844. // recover export name / recuperation du nom de l'export
  845. $string = $langs->trans($this->array_export_label[$keyModel]);
  846. print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
  847. print '</td>';
  848. //print '<td>'.$obj->type.$keyModel.'</td>';
  849. print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
  850. if (!empty($obj->filter)) {
  851. $filter = json_decode($obj->filter, true);
  852. print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
  853. print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
  854. }
  855. // remove export / suppression de l'export
  856. print '<td class="right">';
  857. print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
  858. print img_delete();
  859. print '</a>';
  860. print "</tr>";
  861. $i++;
  862. }
  863. } else {
  864. dol_print_error($this->db);
  865. }
  866. }
  867. }