export.class.php 31 KB

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