export.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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 'FormSelect':
  315. if (is_numeric($ValueField) && $ValueField > 0) {
  316. $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
  317. } else {
  318. $szFilterQuery = " 1=1"; // Test always true
  319. }
  320. break;
  321. case 'Status':
  322. case 'List':
  323. if (is_numeric($ValueField)) {
  324. $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
  325. } else {
  326. if (!(strpos($ValueField, '%') === false)) {
  327. $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
  328. } else {
  329. $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
  330. }
  331. }
  332. break;
  333. default:
  334. 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);
  335. }
  336. return $szFilterQuery;
  337. }
  338. /**
  339. * conditionDate
  340. *
  341. * @param string $Field Field operand 1
  342. * @param string $Value Value operand 2
  343. * @param string $Sens Comparison operator
  344. * @return string
  345. */
  346. public function conditionDate($Field, $Value, $Sens)
  347. {
  348. // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
  349. if (strlen($Value) == 4) {
  350. $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
  351. } elseif (strlen($Value) == 6) {
  352. $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
  353. } else {
  354. $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
  355. }
  356. return $Condition;
  357. }
  358. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  359. /**
  360. * Build an input field used to filter the query
  361. *
  362. * @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
  363. * @param string $NameField Name of the field to filter
  364. * @param string $ValueField Initial value of the field to filter
  365. * @return string html string of the input field ex : "<input type=text name=... value=...>"
  366. */
  367. public function build_filterField($TypeField, $NameField, $ValueField)
  368. {
  369. // phpcs:enable
  370. global $conf, $langs, $form;
  371. $szFilterField = '';
  372. $InfoFieldList = explode(":", $TypeField);
  373. // build the input field on depend of the type of file
  374. switch ($InfoFieldList[0]) {
  375. case 'Text':
  376. case 'Date':
  377. $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
  378. break;
  379. case 'Duree':
  380. case 'Numeric':
  381. case 'Number':
  382. // Must be a string text to allow to use comparison strings like "<= 99.9"
  383. $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
  384. break;
  385. case 'Status':
  386. $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
  387. break;
  388. case 'Boolean':
  389. $szFilterField = '<select name="'.$NameField.'" class="flat">';
  390. $szFilterField .= '<option ';
  391. if ($ValueField == '') {
  392. $szFilterField .= ' selected ';
  393. }
  394. $szFilterField .= ' value="">&nbsp;</option>';
  395. $szFilterField .= '<option ';
  396. if ($ValueField == 'yes' || $ValueField == '1') {
  397. $szFilterField .= ' selected ';
  398. }
  399. $szFilterField .= ' value="1">'.yn(1).'</option>';
  400. $szFilterField .= '<option ';
  401. if ($ValueField == 'no' || $ValueField == '0') {
  402. $szFilterField .= ' selected ';
  403. }
  404. $szFilterField .= ' value="0">'.yn(0).'</option>';
  405. $szFilterField .= "</select>";
  406. break;
  407. case 'FormSelect':
  408. //var_dump($NameField);
  409. if ($InfoFieldList[1] == 'select_company') {
  410. $szFilterField .= $form->select_company('', $NameField, '', 1);
  411. } elseif ($InfoFieldList[1] == 'selectcontacts') {
  412. $szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;');
  413. } elseif ($InfoFieldList[1] == 'select_dolusers') {
  414. $szFilterField .= $form->select_dolusers('', $NameField, 1);
  415. }
  416. break;
  417. case 'List':
  418. // 0 : Type du champ
  419. // 1 : Nom de la table
  420. // 2 : Nom du champ contenant le libelle
  421. // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
  422. // 4 : Name of element for getEntity().
  423. if (!empty($InfoFieldList[3])) {
  424. $keyList = $InfoFieldList[3];
  425. } else {
  426. $keyList = 'rowid';
  427. }
  428. $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
  429. if ($InfoFieldList[1] == 'c_stcomm') {
  430. $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
  431. }
  432. if ($InfoFieldList[1] == 'c_country') {
  433. $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
  434. }
  435. $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
  436. if (!empty($InfoFieldList[4])) {
  437. $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
  438. }
  439. $resql = $this->db->query($sql);
  440. if ($resql) {
  441. $szFilterField = '<select class="flat" name="'.$NameField.'">';
  442. $szFilterField .= '<option value="0">&nbsp;</option>';
  443. $num = $this->db->num_rows($resql);
  444. $i = 0;
  445. if ($num) {
  446. while ($i < $num) {
  447. $obj = $this->db->fetch_object($resql);
  448. if ($obj->label == '-') {
  449. // Discard entry '-'
  450. $i++;
  451. continue;
  452. }
  453. //var_dump($InfoFieldList[1]);
  454. $labeltoshow = dol_trunc($obj->label, 18);
  455. if ($InfoFieldList[1] == 'c_stcomm') {
  456. $langs->load("companies");
  457. $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
  458. }
  459. if ($InfoFieldList[1] == 'c_country') {
  460. //var_dump($sql);
  461. $langs->load("dict");
  462. $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
  463. }
  464. if (!empty($ValueField) && $ValueField == $obj->rowid) {
  465. $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  466. } else {
  467. $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
  468. }
  469. $i++;
  470. }
  471. }
  472. $szFilterField .= "</select>";
  473. $this->db->free($resql);
  474. } else {
  475. dol_print_error($this->db);
  476. }
  477. break;
  478. }
  479. return $szFilterField;
  480. }
  481. /**
  482. * Build an input field used to filter the query
  483. *
  484. * @param string $TypeField Type of Field to filter
  485. * @return string html string of the input field ex : "<input type=text name=... value=...>"
  486. */
  487. public function genDocFilter($TypeField)
  488. {
  489. global $langs;
  490. $szMsg = '';
  491. $InfoFieldList = explode(":", $TypeField);
  492. // build the input field on depend of the type of file
  493. switch ($InfoFieldList[0]) {
  494. case 'Text':
  495. $szMsg = $langs->trans('ExportStringFilter');
  496. break;
  497. case 'Date':
  498. $szMsg = $langs->trans('ExportDateFilter');
  499. break;
  500. case 'Duree':
  501. break;
  502. case 'Numeric':
  503. $szMsg = $langs->trans('ExportNumericFilter');
  504. break;
  505. case 'Boolean':
  506. break;
  507. case 'List':
  508. break;
  509. }
  510. return $szMsg;
  511. }
  512. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  513. /**
  514. * Build export file.
  515. * File is built into directory $conf->export->dir_temp.'/'.$user->id
  516. * Arrays this->array_export_xxx are already loaded for required datatoexport
  517. *
  518. * @param User $user User that export
  519. * @param string $model Export format
  520. * @param string $datatoexport Name of dataset to export
  521. * @param array $array_selected Filter on array of fields to export
  522. * @param array $array_filterValue Filter on array of fields with a filter
  523. * @param string $sqlquery If set, transmit the sql request for select (otherwise, sql request is generated from arrays)
  524. * @return int <0 if KO, >0 if OK
  525. */
  526. public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
  527. {
  528. // phpcs:enable
  529. global $conf, $langs, $mysoc;
  530. $indice = 0;
  531. asort($array_selected);
  532. dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
  533. // Check parameters or context properties
  534. if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
  535. $this->error = "ErrorBadParameter";
  536. dol_syslog($this->error, LOG_ERR);
  537. return -1;
  538. }
  539. // Creation of class to export using model ExportXXX
  540. $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
  541. $file = "export_".$model.".modules.php";
  542. $classname = "Export".$model;
  543. require_once $dir.$file;
  544. $objmodel = new $classname($this->db);
  545. if (!empty($sqlquery)) {
  546. $sql = $sqlquery;
  547. } else {
  548. // Define value for indice from $datatoexport
  549. $foundindice = 0;
  550. foreach ($this->array_export_code as $key => $dataset) {
  551. if ($datatoexport == $dataset) {
  552. $indice = $key;
  553. $foundindice++;
  554. //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
  555. break;
  556. }
  557. }
  558. if (empty($foundindice)) {
  559. $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
  560. return -1;
  561. }
  562. $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
  563. }
  564. // Run the sql
  565. $this->sqlusedforexport = $sql;
  566. dol_syslog(__METHOD__, LOG_DEBUG);
  567. $resql = $this->db->query($sql);
  568. if ($resql) {
  569. //$this->array_export_label[$indice]
  570. if (!empty($conf->global->EXPORT_PREFIX_SPEC)) {
  571. $filename = $conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
  572. } else {
  573. $filename = "export_".$datatoexport;
  574. }
  575. if (!empty($conf->global->EXPORT_NAME_WITH_DT)) {
  576. $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
  577. }
  578. $filename .= '.'.$objmodel->getDriverExtension();
  579. $dirname = $conf->export->dir_temp.'/'.$user->id;
  580. $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
  581. // Open file
  582. dol_mkdir($dirname);
  583. $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
  584. if ($result >= 0) {
  585. // Genere en-tete
  586. $objmodel->write_header($outputlangs);
  587. // Genere ligne de titre
  588. $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
  589. while ($obj = $this->db->fetch_object($resql)) {
  590. // Process special operations
  591. if (!empty($this->array_export_special[$indice])) {
  592. foreach ($this->array_export_special[$indice] as $key => $value) {
  593. if (!array_key_exists($key, $array_selected)) {
  594. continue; // Field not selected
  595. }
  596. // Operation NULLIFNEG
  597. if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') {
  598. //$alias=$this->array_export_alias[$indice][$key];
  599. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  600. if ($obj->$alias < 0) {
  601. $obj->$alias = '';
  602. }
  603. } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') {
  604. // Operation ZEROIFNEG
  605. //$alias=$this->array_export_alias[$indice][$key];
  606. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  607. if ($obj->$alias < 0) {
  608. $obj->$alias = '0';
  609. }
  610. } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') {
  611. // Operation GETNUMOPENDAYS (for Holiday module)
  612. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  613. //$alias=$this->array_export_alias[$indice][$key];
  614. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  615. $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);
  616. } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') {
  617. // Operation INVOICEREMAINTOPAY
  618. //$alias=$this->array_export_alias[$indice][$key];
  619. $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
  620. $remaintopay = '';
  621. if ($obj->f_rowid > 0) {
  622. global $tmpobjforcomputecall;
  623. if (!is_object($tmpobjforcomputecall)) {
  624. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  625. $tmpobjforcomputecall = new Facture($this->db);
  626. }
  627. $tmpobjforcomputecall->id = $obj->f_rowid;
  628. $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
  629. $tmpobjforcomputecall->close_code = $obj->f_close_code;
  630. $remaintopay = $tmpobjforcomputecall->getRemainToPay();
  631. }
  632. $obj->$alias = $remaintopay;
  633. } else {
  634. // TODO FIXME
  635. // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
  636. // Also the formula may contains objects of class that are not loaded.
  637. $computestring = $this->array_export_special[$indice][$key];
  638. //$tmp = dol_eval($computestring, 1, 0);
  639. //$obj->$alias = $tmp;
  640. $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
  641. return -1;
  642. }
  643. }
  644. }
  645. // end of special operation processing
  646. $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
  647. }
  648. // Genere en-tete
  649. $objmodel->write_footer($outputlangs);
  650. // Close file
  651. $objmodel->close_file();
  652. return 1;
  653. } else {
  654. $this->error = $objmodel->error;
  655. dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
  656. return -1;
  657. }
  658. } else {
  659. $this->error = $this->db->error()." - sql=".$sql;
  660. return -1;
  661. }
  662. }
  663. /**
  664. * Save an export model in database
  665. *
  666. * @param User $user Object user that save
  667. * @return int <0 if KO, >0 if OK
  668. */
  669. public function create($user)
  670. {
  671. global $conf;
  672. dol_syslog("Export.class.php::create");
  673. $this->db->begin();
  674. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
  675. $sql .= 'label,';
  676. $sql .= 'type,';
  677. $sql .= 'field,';
  678. $sql .= 'fk_user,';
  679. $sql .= 'filter';
  680. $sql .= ') VALUES (';
  681. $sql .= "'".$this->db->escape($this->model_name)."',";
  682. $sql .= " '".$this->db->escape($this->datatoexport)."',";
  683. $sql .= " '".$this->db->escape($this->hexa)."',";
  684. $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
  685. $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
  686. $sql .= ")";
  687. $resql = $this->db->query($sql);
  688. if ($resql) {
  689. $this->db->commit();
  690. return 1;
  691. } else {
  692. $this->error = $this->db->lasterror();
  693. $this->errno = $this->db->lasterrno();
  694. $this->db->rollback();
  695. return -1;
  696. }
  697. }
  698. /**
  699. * Load an export profil from database
  700. *
  701. * @param int $id Id of profil to load
  702. * @return int <0 if KO, >0 if OK
  703. */
  704. public function fetch($id)
  705. {
  706. $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
  707. $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
  708. $sql .= ' WHERE em.rowid = '.((int) $id);
  709. dol_syslog("Export::fetch", LOG_DEBUG);
  710. $result = $this->db->query($sql);
  711. if ($result) {
  712. $obj = $this->db->fetch_object($result);
  713. if ($obj) {
  714. $this->id = $obj->rowid;
  715. $this->model_name = $obj->label;
  716. $this->datatoexport = $obj->type;
  717. $this->hexa = $obj->field;
  718. $this->hexafiltervalue = $obj->filter;
  719. return 1;
  720. } else {
  721. $this->error = "ModelNotFound";
  722. return -2;
  723. }
  724. } else {
  725. dol_print_error($this->db);
  726. return -3;
  727. }
  728. }
  729. /**
  730. * Delete object in database
  731. *
  732. * @param User $user User that delete
  733. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  734. * @return int <0 if KO, >0 if OK
  735. */
  736. public function delete($user, $notrigger = 0)
  737. {
  738. global $conf, $langs;
  739. $error = 0;
  740. $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
  741. $sql .= " WHERE rowid=".((int) $this->id);
  742. $this->db->begin();
  743. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  744. $resql = $this->db->query($sql);
  745. if (!$resql) {
  746. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  747. }
  748. // Commit or rollback
  749. if ($error) {
  750. foreach ($this->errors as $errmsg) {
  751. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  752. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  753. }
  754. $this->db->rollback();
  755. return -1 * $error;
  756. } else {
  757. $this->db->commit();
  758. return 1;
  759. }
  760. }
  761. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  762. /**
  763. * Output list all export models
  764. * TODO Move this into a class htmlxxx.class.php
  765. *
  766. * @return void
  767. */
  768. public function list_export_model()
  769. {
  770. // phpcs:enable
  771. global $conf, $langs;
  772. $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
  773. $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
  774. $sql .= " ORDER BY rowid";
  775. $result = $this->db->query($sql);
  776. if ($result) {
  777. $num = $this->db->num_rows($result);
  778. $i = 0;
  779. while ($i < $num) {
  780. $obj = $this->db->fetch_object($result);
  781. $keyModel = array_search($obj->type, $this->array_export_code);
  782. print "<tr>";
  783. print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
  784. print '<td>';
  785. print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
  786. print $this->array_export_module[$keyModel]->getName().' - ';
  787. // recuperation du nom de l'export
  788. $string = $langs->trans($this->array_export_label[$keyModel]);
  789. print ($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
  790. print '</td>';
  791. //print '<td>'.$obj->type.$keyModel.'</td>';
  792. print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
  793. if (!empty($obj->filter)) {
  794. $filter = json_decode($obj->filter, true);
  795. print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
  796. print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
  797. }
  798. // suppression de l'export
  799. print '<td class="right">';
  800. print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
  801. print img_delete();
  802. print '</a>';
  803. print "</tr>";
  804. $i++;
  805. }
  806. } else {
  807. dol_print_error($this->db);
  808. }
  809. }
  810. }