html.formfile.class.php 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  1. <?php
  2. /* Copyright (C) 2008-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2010-2014 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2016 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2013 Charles-Fr BENKE <charles.fr@benke.fr>
  6. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  7. * Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2015 Bahfir Abbes <bafbes@gmail.com>
  9. * Copyright (C) 2016-2017 Ferran Marcet <fmarcet@2byte.es>
  10. * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/core/class/html.formfile.class.php
  27. * \ingroup core
  28. * \brief File of class to offer components to list and upload files
  29. */
  30. /**
  31. * Class to offer components to list and upload files
  32. */
  33. class FormFile
  34. {
  35. private $db;
  36. /**
  37. * @var string Error code (or message)
  38. */
  39. public $error;
  40. public $numoffiles;
  41. public $infofiles; // Used to return informations by function getDocumentsLink
  42. /**
  43. * Constructor
  44. *
  45. * @param DoliDB $db Database handler
  46. */
  47. public function __construct($db)
  48. {
  49. $this->db = $db;
  50. $this->numoffiles = 0;
  51. }
  52. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  53. /**
  54. * Show form to upload a new file.
  55. *
  56. * @param string $url Url
  57. * @param string $title Title zone (Title or '' or 'none')
  58. * @param int $addcancel 1=Add 'Cancel' button
  59. * @param int $sectionid If upload must be done inside a particular ECM section (is sectionid defined, sectiondir must not be)
  60. * @param int $perm Value of permission to allow upload
  61. * @param int $size Length of input file area. Deprecated.
  62. * @param Object $object Object to use (when attachment is done on an element)
  63. * @param string $options Add an option column
  64. * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option).
  65. * Deprecated 2 should never be used and if 1 is used, option should no be enabled.
  66. * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
  67. * @param integer $linkfiles 1=Also add form to link files, 0=Do not show form to link files
  68. * @param string $htmlname Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM)
  69. * @param string $accept Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*')
  70. * @param string $sectiondir If upload must be done inside a particular directory (if sectiondir defined, sectionid must not be)
  71. * @param int $usewithoutform 0=Default, 1=Disable <form> and <input hidden> to use in existing form area, 2=Disable the tag <form> only
  72. * @param int $capture 1=Add tag capture="capture" to force use of micro or video recording to generate file. When setting this to 1, you must also provide a value for $accept.
  73. * @param int $disablemulti 0=Default, 1=Disable multiple file upload
  74. * @param int $nooutput 0=Output result with print, 1=Return result
  75. * @return int|string <0 if KO, >0 if OK, or string if $noouput=1
  76. */
  77. public function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '', $sectiondir = '', $usewithoutform = 0, $capture = 0, $disablemulti = 0, $nooutput = 0)
  78. {
  79. // phpcs:enable
  80. global $conf, $langs, $hookmanager;
  81. $hookmanager->initHooks(array('formfile'));
  82. // Deprecation warning
  83. if ($useajax == 2) {
  84. dol_syslog(__METHOD__.": using 2 for useajax is deprecated and should be not used", LOG_WARNING);
  85. }
  86. if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') {
  87. $useajax = 0;
  88. }
  89. if ((!empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax == 2)) {
  90. // TODO: Check this works with 2 forms on same page
  91. // TODO: Check this works with GED module, otherwise, force useajax to 0
  92. // TODO: This does not support option savingdocmask
  93. // TODO: This break feature to upload links too
  94. // TODO: Thisdoes not work when param nooutput=1
  95. return $this->_formAjaxFileUpload($object);
  96. } else {
  97. //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
  98. if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
  99. if ($nooutput) {
  100. return '';
  101. } else {
  102. return 1;
  103. }
  104. }
  105. $out = "\n\n".'<!-- Start form attach new file --><div class="formattachnewfile">'."\n";
  106. if (empty($title)) {
  107. $title = $langs->trans("AttachANewFile");
  108. }
  109. if ($title != 'none') {
  110. $out .= load_fiche_titre($title, null, null);
  111. }
  112. if (empty($usewithoutform)) { // Try to avoid this and set instead the form by the caller.
  113. // Add a param as GET parameter to detect when POST were cleaned by PHP because a file larger than post_max_size
  114. $url .= (strpos($url, '?') === false ? '?' : '&').'uploadform=1';
  115. $out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">'."\n";
  116. }
  117. if (empty($usewithoutform) || $usewithoutform == 2) {
  118. $out .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  119. $out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="'.$sectiondir.'">'."\n";
  120. $out .= '<input type="hidden" id="'.$htmlname.'_section_id" name="section_id" value="'.$sectionid.'">'."\n";
  121. $out .= '<input type="hidden" name="sortfield" value="'.GETPOST('sortfield', 'aZ09comma').'">'."\n";
  122. $out .= '<input type="hidden" name="sortorder" value="'.GETPOST('sortorder', 'aZ09comma').'">'."\n";
  123. $out .= '<input type="hidden" name="page_y" value="">'."\n";
  124. }
  125. $out .= '<table class="nobordernopadding centpercent">';
  126. $out .= '<tr>';
  127. if (!empty($options)) {
  128. $out .= '<td>'.$options.'</td>';
  129. }
  130. $out .= '<td class="valignmiddle nowrap">';
  131. $max = $conf->global->MAIN_UPLOAD_DOC; // In Kb
  132. $maxphp = @ini_get('upload_max_filesize'); // In unknown
  133. if (preg_match('/k$/i', $maxphp)) {
  134. $maxphp = preg_replace('/k$/i', '', $maxphp);
  135. $maxphp = $maxphp * 1;
  136. }
  137. if (preg_match('/m$/i', $maxphp)) {
  138. $maxphp = preg_replace('/m$/i', '', $maxphp);
  139. $maxphp = $maxphp * 1024;
  140. }
  141. if (preg_match('/g$/i', $maxphp)) {
  142. $maxphp = preg_replace('/g$/i', '', $maxphp);
  143. $maxphp = $maxphp * 1024 * 1024;
  144. }
  145. if (preg_match('/t$/i', $maxphp)) {
  146. $maxphp = preg_replace('/t$/i', '', $maxphp);
  147. $maxphp = $maxphp * 1024 * 1024 * 1024;
  148. }
  149. $maxphp2 = @ini_get('post_max_size'); // In unknown
  150. if (preg_match('/k$/i', $maxphp2)) {
  151. $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
  152. $maxphp2 = $maxphp2 * 1;
  153. }
  154. if (preg_match('/m$/i', $maxphp2)) {
  155. $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
  156. $maxphp2 = $maxphp2 * 1024;
  157. }
  158. if (preg_match('/g$/i', $maxphp2)) {
  159. $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
  160. $maxphp2 = $maxphp2 * 1024 * 1024;
  161. }
  162. if (preg_match('/t$/i', $maxphp2)) {
  163. $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
  164. $maxphp2 = $maxphp2 * 1024 * 1024 * 1024;
  165. }
  166. // Now $max and $maxphp and $maxphp2 are in Kb
  167. $maxmin = $max;
  168. $maxphptoshow = $maxphptoshowparam = '';
  169. if ($maxphp > 0) {
  170. $maxmin = min($max, $maxphp);
  171. $maxphptoshow = $maxphp;
  172. $maxphptoshowparam = 'upload_max_filesize';
  173. }
  174. if ($maxphp2 > 0) {
  175. $maxmin = min($max, $maxphp2);
  176. if ($maxphp2 < $maxphp) {
  177. $maxphptoshow = $maxphp2;
  178. $maxphptoshowparam = 'post_max_size';
  179. }
  180. }
  181. if ($maxmin > 0) {
  182. // MAX_FILE_SIZE doit précéder le champ input de type file
  183. $out .= '<input type="hidden" name="max_file_size" value="'.($maxmin * 1024).'">';
  184. }
  185. $out .= '<input class="flat minwidth400 maxwidth200onsmartphone" type="file"';
  186. //$out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic') ? ' name="userfile"' : ' name="userfile[]" multiple');
  187. $out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $disablemulti) ? ' name="userfile"' : ' name="userfile[]" multiple');
  188. $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
  189. $out .= (!empty($accept) ? ' accept="'.$accept.'"' : ' accept=""');
  190. $out .= (!empty($capture) ? ' capture="capture"' : '');
  191. $out .= '>';
  192. $out .= ' ';
  193. if ($sectionid) { // Show overwrite if exists for ECM module only
  194. $langs->load('link');
  195. $out .= '<span class="nowraponsmartphone"><input style="margin-right: 2px;" type="checkbox" id="overwritefile" name="overwritefile" value="1"><label for="overwritefile">'.$langs->trans("OverwriteIfExists").'</label></span>';
  196. }
  197. $out .= '<input type="submit" class="button small reposition" name="sendit" value="'.$langs->trans("Upload").'"';
  198. $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
  199. $out .= '>';
  200. if ($addcancel) {
  201. $out .= ' &nbsp; ';
  202. $out .= '<input type="submit" class="button small button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  203. }
  204. if (!empty($conf->global->MAIN_UPLOAD_DOC)) {
  205. if ($perm) {
  206. $menudolibarrsetupmax = $langs->transnoentitiesnoconv("Home").'-'.$langs->transnoentitiesnoconv("Setup").'-'.$langs->transnoentitiesnoconv("Security");
  207. $langs->load('other');
  208. $out .= ' ';
  209. $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetupAt", $menudolibarrsetupmax, $max, $maxphptoshowparam, $maxphptoshow), 1);
  210. }
  211. } else {
  212. $out .= ' ('.$langs->trans("UploadDisabled").')';
  213. }
  214. $out .= "</td></tr>";
  215. if ($savingdocmask) {
  216. //add a global variable for disable the auto renaming on upload
  217. $rename = (empty($conf->global->MAIN_DOC_UPLOAD_NOT_RENAME_BY_DEFAULT) ? 'checked' : '');
  218. $out .= '<tr>';
  219. if (!empty($options)) {
  220. $out .= '<td>'.$options.'</td>';
  221. }
  222. $out .= '<td valign="middle" class="nowrap">';
  223. $out .= '<input type="checkbox" '.$rename.' class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> ';
  224. $out .= '<span class="opacitymedium">';
  225. $out .= $langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/', $langs->transnoentitiesnoconv("OriginFileName"), $savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
  226. $out .= '</span>';
  227. $out .= '</td>';
  228. $out .= '</tr>';
  229. }
  230. $out .= "</table>";
  231. if (empty($usewithoutform)) {
  232. $out .= '</form>';
  233. if (empty($sectionid)) {
  234. $out .= '<br>';
  235. }
  236. }
  237. $out .= "\n</div><!-- End form attach new file -->\n";
  238. if ($linkfiles) {
  239. $out .= "\n".'<!-- Start form link new url --><div class="formlinknewurl">'."\n";
  240. $langs->load('link');
  241. $title = $langs->trans("LinkANewFile");
  242. $out .= load_fiche_titre($title, null, null);
  243. if (empty($usewithoutform)) {
  244. $out .= '<form name="'.$htmlname.'_link" id="'.$htmlname.'_link" action="'.$url.'" method="POST">'."\n";
  245. $out .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  246. $out .= '<input type="hidden" id="'.$htmlname.'_link_section_dir" name="link_section_dir" value="">'."\n";
  247. $out .= '<input type="hidden" id="'.$htmlname.'_link_section_id" name="link_section_id" value="'.$sectionid.'">'."\n";
  248. $out .= '<input type="hidden" name="page_y" value="">'."\n";
  249. }
  250. $out .= '<div class="valignmiddle">';
  251. $out .= '<div class="inline-block" style="padding-right: 10px;">';
  252. if (!empty($conf->global->OPTIMIZEFORTEXTBROWSER)) {
  253. $out .= '<label for="link">'.$langs->trans("URLToLink").':</label> ';
  254. }
  255. $out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
  256. $out .= '</div>';
  257. $out .= '<div class="inline-block" style="padding-right: 10px;">';
  258. if (!empty($conf->global->OPTIMIZEFORTEXTBROWSER)) {
  259. $out .= '<label for="label">'.$langs->trans("Label").':</label> ';
  260. }
  261. $out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
  262. $out .= '<input type="hidden" name="objecttype" value="'.$object->element.'">';
  263. $out .= '<input type="hidden" name="objectid" value="'.$object->id.'">';
  264. $out .= '</div>';
  265. $out .= '<div class="inline-block" style="padding-right: 10px;">';
  266. $out .= '<input type="submit" class="button small reposition" name="linkit" value="'.$langs->trans("ToLink").'"';
  267. $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
  268. $out .= '>';
  269. $out .= '</div>';
  270. $out .= '</div>';
  271. if (empty($usewithoutform)) {
  272. $out .= '<div class="clearboth"></div>';
  273. $out .= '</form><br>';
  274. }
  275. $out .= "\n</div><!-- End form link new url -->\n";
  276. }
  277. $parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'url'=>$url, 'perm'=>$perm, 'options'=>$options);
  278. $res = $hookmanager->executeHooks('formattachOptions', $parameters, $object);
  279. if (empty($res)) {
  280. $out = '<div class="'.($usewithoutform ? 'inline-block valignmiddle' : 'attacharea attacharea'.$htmlname).'">'.$out.'</div>';
  281. }
  282. $out .= $hookmanager->resPrint;
  283. if ($nooutput) {
  284. return $out;
  285. } else {
  286. print $out;
  287. return 1;
  288. }
  289. }
  290. }
  291. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  292. /**
  293. * Show the box with list of available documents for object
  294. *
  295. * @param string $modulepart propal, facture, facture_fourn, ...
  296. * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
  297. * @param string $filedir Directory to scan
  298. * @param string $urlsource Url of origin page (for return)
  299. * @param int $genallowed Generation is allowed (1/0 or array of formats)
  300. * @param int $delallowed Remove is allowed (1/0)
  301. * @param string $modelselected Model to preselect by default
  302. * @param integer $allowgenifempty Show warning if no model activated
  303. * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined)
  304. * @param int $iconPDF Show only PDF icon with link (1/0)
  305. * @param int $notused Not used
  306. * @param integer $noform Do not output html form tags
  307. * @param string $param More param on http links
  308. * @param string $title Title to show on top of form
  309. * @param string $buttonlabel Label on submit button
  310. * @param string $codelang Default language code to use on lang combo box if multilang is enabled
  311. * @return int <0 if KO, number of shown files if OK
  312. * @deprecated Use print xxx->showdocuments() instead.
  313. */
  314. public function show_documents($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '')
  315. {
  316. // phpcs:enable
  317. $this->numoffiles = 0;
  318. print $this->showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed, $modelselected, $allowgenifempty, $forcenomultilang, $iconPDF, $notused, $noform, $param, $title, $buttonlabel, $codelang);
  319. return $this->numoffiles;
  320. }
  321. /**
  322. * Return a string to show the box with list of available documents for object.
  323. * This also set the property $this->numoffiles
  324. *
  325. * @param string $modulepart Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule:MyObject', 'mymodule_temp', ...)
  326. * @param string $modulesubdir Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into a subdir of module.
  327. * @param string $filedir Directory to scan (must not end with a /). Example: '/mydolibarrdocuments/facture/FAYYMM-1234'
  328. * @param string $urlsource Url of origin page (for return)
  329. * @param int|string[] $genallowed Generation is allowed (1/0 or array list of templates)
  330. * @param int $delallowed Remove is allowed (1/0)
  331. * @param string $modelselected Model to preselect by default
  332. * @param integer $allowgenifempty Allow generation even if list of template ($genallowed) is empty (show however a warning)
  333. * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined)
  334. * @param int $iconPDF Deprecated, see getDocumentsLink
  335. * @param int $notused Not used
  336. * @param integer $noform Do not output html form tags
  337. * @param string $param More param on http links
  338. * @param string $title Title to show on top of form. Example: '' (Default to "Documents") or 'none'
  339. * @param string $buttonlabel Label on submit button
  340. * @param string $codelang Default language code to use on lang combo box if multilang is enabled
  341. * @param string $morepicto Add more HTML content into cell with picto
  342. * @param Object $object Object when method is called from an object card.
  343. * @param int $hideifempty Hide section of generated files if there is no file
  344. * @param string $removeaction (optional) The action to remove a file
  345. * @param string $tooltipontemplatecombo Text to show on a tooltip after the combo list of templates
  346. * @return string Output string with HTML array of documents (might be empty string)
  347. */
  348. public function showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '', $morepicto = '', $object = null, $hideifempty = 0, $removeaction = 'remove_file', $tooltipontemplatecombo = '')
  349. {
  350. global $dolibarr_main_url_root;
  351. // Deprecation warning
  352. if (!empty($iconPDF)) {
  353. dol_syslog(__METHOD__.": passing iconPDF parameter is deprecated", LOG_WARNING);
  354. }
  355. global $langs, $conf, $user, $hookmanager;
  356. global $form;
  357. $reshook = 0;
  358. if (is_object($hookmanager)) {
  359. $parameters = array(
  360. 'modulepart'=>&$modulepart,
  361. 'modulesubdir'=>&$modulesubdir,
  362. 'filedir'=>&$filedir,
  363. 'urlsource'=>&$urlsource,
  364. 'genallowed'=>&$genallowed,
  365. 'delallowed'=>&$delallowed,
  366. 'modelselected'=>&$modelselected,
  367. 'allowgenifempty'=>&$allowgenifempty,
  368. 'forcenomultilang'=>&$forcenomultilang,
  369. 'noform'=>&$noform,
  370. 'param'=>&$param,
  371. 'title'=>&$title,
  372. 'buttonlabel'=>&$buttonlabel,
  373. 'codelang'=>&$codelang,
  374. 'morepicto'=>&$morepicto,
  375. 'hideifempty'=>&$hideifempty,
  376. 'removeaction'=>&$removeaction
  377. );
  378. $reshook = $hookmanager->executeHooks('showDocuments', $parameters, $object); // Note that parameters may have been updated by hook
  379. // May report error
  380. if ($reshook < 0) {
  381. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  382. }
  383. }
  384. // Remode default action if $reskook > 0
  385. if ($reshook > 0) {
  386. return $hookmanager->resPrint;
  387. }
  388. if (!is_object($form)) {
  389. $form = new Form($this->db);
  390. }
  391. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  392. // For backward compatibility
  393. if (!empty($iconPDF)) {
  394. return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
  395. }
  396. // Add entity in $param if not already exists
  397. if (!preg_match('/entity\=[0-9]+/', $param)) {
  398. $param .= ($param ? '&' : '').'entity='.(!empty($object->entity) ? $object->entity : $conf->entity);
  399. }
  400. $printer = 0;
  401. // The direct print feature is implemented only for such elements
  402. if (in_array($modulepart, array('contract', 'facture', 'supplier_proposal', 'propal', 'proposal', 'order', 'commande', 'expedition', 'commande_fournisseur', 'expensereport', 'delivery', 'ticket'))) {
  403. $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled)) ?true:false;
  404. }
  405. $hookmanager->initHooks(array('formfile'));
  406. // Get list of files
  407. $file_list = null;
  408. if (!empty($filedir)) {
  409. $file_list = dol_dir_list($filedir, 'files', 0, '', '(\.meta|_preview.*.*\.png)$', 'date', SORT_DESC);
  410. }
  411. if ($hideifempty && empty($file_list)) {
  412. return '';
  413. }
  414. $out = '';
  415. $forname = 'builddoc';
  416. $headershown = 0;
  417. $showempty = 0;
  418. $i = 0;
  419. $out .= "\n".'<!-- Start show_document -->'."\n";
  420. //print 'filedir='.$filedir;
  421. if (preg_match('/massfilesarea_/', $modulepart)) {
  422. $out .= '<div id="show_files"><br></div>'."\n";
  423. $title = $langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
  424. $title .= '<script>
  425. jQuery(document).ready(function() {
  426. jQuery(\'#togglemassfilesarea\').click(function() {
  427. if (jQuery(\'#togglemassfilesarea\').attr(\'ref\') == "shown")
  428. {
  429. jQuery(\'#'.$modulepart.'_table\').hide();
  430. jQuery(\'#togglemassfilesarea\').attr("ref", "hidden");
  431. jQuery(\'#togglemassfilesarea\').text("('.dol_escape_js($langs->trans("Show")).')");
  432. }
  433. else
  434. {
  435. jQuery(\'#'.$modulepart.'_table\').show();
  436. jQuery(\'#togglemassfilesarea\').attr("ref","shown");
  437. jQuery(\'#togglemassfilesarea\').text("('.dol_escape_js($langs->trans("Hide")).')");
  438. }
  439. return false;
  440. });
  441. });
  442. </script>';
  443. }
  444. $titletoshow = $langs->trans("Documents");
  445. if (!empty($title)) {
  446. $titletoshow = ($title == 'none' ? '' : $title);
  447. }
  448. // Show table
  449. if ($genallowed) {
  450. $modellist = array();
  451. if ($modulepart == 'company') {
  452. $showempty = 1; // can have no template active
  453. if (is_array($genallowed)) {
  454. $modellist = $genallowed;
  455. } else {
  456. include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
  457. $modellist = ModeleThirdPartyDoc::liste_modeles($this->db);
  458. }
  459. } elseif ($modulepart == 'propal') {
  460. if (is_array($genallowed)) {
  461. $modellist = $genallowed;
  462. } else {
  463. include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
  464. $modellist = ModelePDFPropales::liste_modeles($this->db);
  465. }
  466. } elseif ($modulepart == 'supplier_proposal') {
  467. if (is_array($genallowed)) {
  468. $modellist = $genallowed;
  469. } else {
  470. include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
  471. $modellist = ModelePDFSupplierProposal::liste_modeles($this->db);
  472. }
  473. } elseif ($modulepart == 'commande') {
  474. if (is_array($genallowed)) {
  475. $modellist = $genallowed;
  476. } else {
  477. include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
  478. $modellist = ModelePDFCommandes::liste_modeles($this->db);
  479. }
  480. } elseif ($modulepart == 'expedition') {
  481. if (is_array($genallowed)) {
  482. $modellist = $genallowed;
  483. } else {
  484. include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
  485. $modellist = ModelePDFExpedition::liste_modeles($this->db);
  486. }
  487. } elseif ($modulepart == 'reception') {
  488. if (is_array($genallowed)) {
  489. $modellist = $genallowed;
  490. } else {
  491. include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php';
  492. $modellist = ModelePdfReception::liste_modeles($this->db);
  493. }
  494. } elseif ($modulepart == 'delivery') {
  495. if (is_array($genallowed)) {
  496. $modellist = $genallowed;
  497. } else {
  498. include_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/modules_delivery.php';
  499. $modellist = ModelePDFDeliveryOrder::liste_modeles($this->db);
  500. }
  501. } elseif ($modulepart == 'ficheinter') {
  502. if (is_array($genallowed)) {
  503. $modellist = $genallowed;
  504. } else {
  505. include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
  506. $modellist = ModelePDFFicheinter::liste_modeles($this->db);
  507. }
  508. } elseif ($modulepart == 'facture') {
  509. if (is_array($genallowed)) {
  510. $modellist = $genallowed;
  511. } else {
  512. include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  513. $modellist = ModelePDFFactures::liste_modeles($this->db);
  514. }
  515. } elseif ($modulepart == 'contract') {
  516. $showempty = 1; // can have no template active
  517. if (is_array($genallowed)) {
  518. $modellist = $genallowed;
  519. } else {
  520. include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
  521. $modellist = ModelePDFContract::liste_modeles($this->db);
  522. }
  523. } elseif ($modulepart == 'project') {
  524. if (is_array($genallowed)) {
  525. $modellist = $genallowed;
  526. } else {
  527. include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
  528. $modellist = ModelePDFProjects::liste_modeles($this->db);
  529. }
  530. } elseif ($modulepart == 'project_task') {
  531. if (is_array($genallowed)) {
  532. $modellist = $genallowed;
  533. } else {
  534. include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
  535. $modellist = ModelePDFTask::liste_modeles($this->db);
  536. }
  537. } elseif ($modulepart == 'product') {
  538. if (is_array($genallowed)) {
  539. $modellist = $genallowed;
  540. } else {
  541. include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
  542. $modellist = ModelePDFProduct::liste_modeles($this->db);
  543. }
  544. } elseif ($modulepart == 'product_batch') {
  545. if (is_array($genallowed)) {
  546. $modellist = $genallowed;
  547. } else {
  548. include_once DOL_DOCUMENT_ROOT.'/core/modules/product_batch/modules_product_batch.class.php';
  549. $modellist = ModelePDFProductBatch::liste_modeles($this->db);
  550. }
  551. } elseif ($modulepart == 'stock') {
  552. if (is_array($genallowed)) {
  553. $modellist = $genallowed;
  554. } else {
  555. include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_stock.php';
  556. $modellist = ModelePDFStock::liste_modeles($this->db);
  557. }
  558. } elseif ($modulepart == 'movement') {
  559. if (is_array($genallowed)) {
  560. $modellist = $genallowed;
  561. } else {
  562. include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_movement.php';
  563. $modellist = ModelePDFMovement::liste_modeles($this->db);
  564. }
  565. } elseif ($modulepart == 'export') {
  566. if (is_array($genallowed)) {
  567. $modellist = $genallowed;
  568. } else {
  569. include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
  570. $modellist = ModeleExports::liste_modeles($this->db);
  571. }
  572. } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
  573. if (is_array($genallowed)) {
  574. $modellist = $genallowed;
  575. } else {
  576. include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
  577. $modellist = ModelePDFSuppliersOrders::liste_modeles($this->db);
  578. }
  579. } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
  580. $showempty = 1; // can have no template active
  581. if (is_array($genallowed)) {
  582. $modellist = $genallowed;
  583. } else {
  584. include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
  585. $modellist = ModelePDFSuppliersInvoices::liste_modeles($this->db);
  586. }
  587. } elseif ($modulepart == 'supplier_payment') {
  588. if (is_array($genallowed)) {
  589. $modellist = $genallowed;
  590. } else {
  591. include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
  592. $modellist = ModelePDFSuppliersPayments::liste_modeles($this->db);
  593. }
  594. } elseif ($modulepart == 'remisecheque') {
  595. if (is_array($genallowed)) {
  596. $modellist = $genallowed;
  597. } else {
  598. include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
  599. $modellist = ModeleChequeReceipts::liste_modeles($this->db);
  600. }
  601. } elseif ($modulepart == 'donation') {
  602. if (is_array($genallowed)) {
  603. $modellist = $genallowed;
  604. } else {
  605. include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
  606. $modellist = ModeleDon::liste_modeles($this->db);
  607. }
  608. } elseif ($modulepart == 'member') {
  609. if (is_array($genallowed)) {
  610. $modellist = $genallowed;
  611. } else {
  612. include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
  613. $modellist = ModelePDFCards::liste_modeles($this->db);
  614. }
  615. } elseif ($modulepart == 'agenda' || $modulepart == 'actions') {
  616. if (is_array($genallowed)) {
  617. $modellist = $genallowed;
  618. } else {
  619. include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
  620. $modellist = ModeleAction::liste_modeles($this->db);
  621. }
  622. } elseif ($modulepart == 'expensereport') {
  623. if (is_array($genallowed)) {
  624. $modellist = $genallowed;
  625. } else {
  626. include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
  627. $modellist = ModeleExpenseReport::liste_modeles($this->db);
  628. }
  629. } elseif ($modulepart == 'unpaid') {
  630. $modellist = '';
  631. } elseif ($modulepart == 'user') {
  632. if (is_array($genallowed)) {
  633. $modellist = $genallowed;
  634. } else {
  635. include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
  636. $modellist = ModelePDFUser::liste_modeles($this->db);
  637. }
  638. } elseif ($modulepart == 'usergroup') {
  639. if (is_array($genallowed)) {
  640. $modellist = $genallowed;
  641. } else {
  642. include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
  643. $modellist = ModelePDFUserGroup::liste_modeles($this->db);
  644. }
  645. } else {
  646. $submodulepart = $modulepart;
  647. // modulepart = 'nameofmodule' or 'nameofmodule:NameOfObject'
  648. $tmp = explode(':', $modulepart);
  649. if (!empty($tmp[1])) {
  650. $modulepart = $tmp[0];
  651. $submodulepart = $tmp[1];
  652. }
  653. // For normalized standard modules
  654. $file = dol_buildpath('/core/modules/'.$modulepart.'/modules_'.strtolower($submodulepart).'.php', 0);
  655. if (file_exists($file)) {
  656. $res = include_once $file;
  657. } else {
  658. // For normalized external modules.
  659. $file = dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.strtolower($submodulepart).'.php', 0);
  660. $res = include_once $file;
  661. }
  662. $class = 'ModelePDF'.ucfirst($submodulepart);
  663. if (class_exists($class)) {
  664. $modellist = call_user_func($class.'::liste_modeles', $this->db);
  665. } else {
  666. dol_print_error($this->db, "Bad value for modulepart '".$modulepart."' in showdocuments (class ".$class." for Doc generation not found)");
  667. return -1;
  668. }
  669. }
  670. // Set headershown to avoid to have table opened a second time later
  671. $headershown = 1;
  672. if (empty($buttonlabel)) {
  673. $buttonlabel = $langs->trans('Generate');
  674. }
  675. if ($conf->browser->layout == 'phone') {
  676. $urlsource .= '#'.$forname.'_form'; // So we switch to form after a generation
  677. }
  678. if (empty($noform)) {
  679. $out .= '<form action="'.$urlsource.'" id="'.$forname.'_form" method="post">';
  680. }
  681. $out .= '<input type="hidden" name="action" value="builddoc">';
  682. $out .= '<input type="hidden" name="page_y" value="">';
  683. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  684. $out .= load_fiche_titre($titletoshow, '', '');
  685. $out .= '<div class="div-table-responsive-no-min">';
  686. $out .= '<table class="liste formdoc noborder centpercent">';
  687. $out .= '<tr class="liste_titre">';
  688. $addcolumforpicto = ($delallowed || $printer || $morepicto);
  689. $colspan = (4 + ($addcolumforpicto ? 1 : 0));
  690. $colspanmore = 0;
  691. $out .= '<th colspan="'.$colspan.'" class="formdoc liste_titre maxwidthonsmartphone center">';
  692. // Model
  693. if (!empty($modellist)) {
  694. asort($modellist);
  695. $out .= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
  696. if (is_array($modellist) && count($modellist) == 1) { // If there is only one element
  697. $arraykeys = array_keys($modellist);
  698. $modelselected = $arraykeys[0];
  699. }
  700. $morecss = 'minwidth75 maxwidth200';
  701. if ($conf->browser->layout == 'phone') {
  702. $morecss = 'maxwidth100';
  703. }
  704. $out .= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss);
  705. if ($conf->use_javascript_ajax) {
  706. $out .= ajax_combobox('model');
  707. }
  708. $out .= $form->textwithpicto('', $tooltipontemplatecombo, 1, 'help', 'marginrightonly', 0, 3, '', 0);
  709. } else {
  710. $out .= '<div class="float">'.$langs->trans("Files").'</div>';
  711. }
  712. // Language code (if multilang)
  713. if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && !empty($conf->global->MAIN_MULTILANGS) && !$forcenomultilang && (!empty($modellist) || $showempty)) {
  714. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
  715. $formadmin = new FormAdmin($this->db);
  716. $defaultlang = ($codelang && $codelang != 'auto') ? $codelang : $langs->getDefaultLang();
  717. $morecss = 'maxwidth150';
  718. if ($conf->browser->layout == 'phone') {
  719. $morecss = 'maxwidth100';
  720. }
  721. $out .= $formadmin->select_language($defaultlang, 'lang_id', 0, null, 0, 0, 0, $morecss);
  722. } else {
  723. $out .= '&nbsp;';
  724. }
  725. // Button
  726. $genbutton = '<input class="button buttongen reposition nomargintop nomarginbottom" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
  727. $genbutton .= ' type="submit" value="'.$buttonlabel.'"';
  728. if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) {
  729. $genbutton .= ' disabled';
  730. }
  731. $genbutton .= '>';
  732. if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
  733. $langs->load("errors");
  734. $genbutton .= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
  735. }
  736. if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
  737. $genbutton = '';
  738. }
  739. if (empty($modellist) && !$showempty && $modulepart != 'unpaid') {
  740. $genbutton = '';
  741. }
  742. $out .= $genbutton;
  743. $out .= '</th>';
  744. if (!empty($hookmanager->hooks['formfile'])) {
  745. foreach ($hookmanager->hooks['formfile'] as $module) {
  746. if (method_exists($module, 'formBuilddocLineOptions')) {
  747. $colspanmore++;
  748. $out .= '<th></th>';
  749. }
  750. }
  751. }
  752. $out .= '</tr>';
  753. // Execute hooks
  754. $parameters = array('colspan'=>($colspan + $colspanmore), 'socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'modulepart'=>$modulepart);
  755. if (is_object($hookmanager)) {
  756. $reshook = $hookmanager->executeHooks('formBuilddocOptions', $parameters, $GLOBALS['object']);
  757. $out .= $hookmanager->resPrint;
  758. }
  759. }
  760. // Get list of files
  761. if (!empty($filedir)) {
  762. $link_list = array();
  763. if (is_object($object)) {
  764. require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
  765. $link = new Link($this->db);
  766. $sortfield = $sortorder = null;
  767. $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
  768. }
  769. $out .= '<!-- html.formfile::showdocuments -->'."\n";
  770. // Show title of array if not already shown
  771. if ((!empty($file_list) || !empty($link_list) || preg_match('/^massfilesarea/', $modulepart))
  772. && !$headershown) {
  773. $headershown = 1;
  774. $out .= '<div class="titre">'.$titletoshow.'</div>'."\n";
  775. $out .= '<div class="div-table-responsive-no-min">';
  776. $out .= '<table class="noborder centpercent" id="'.$modulepart.'_table">'."\n";
  777. }
  778. // Loop on each file found
  779. if (is_array($file_list)) {
  780. // Defined relative dir to DOL_DATA_ROOT
  781. $relativedir = '';
  782. if ($filedir) {
  783. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $filedir);
  784. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  785. }
  786. // Get list of files stored into database for same relative directory
  787. if ($relativedir) {
  788. completeFileArrayWithDatabaseInfo($file_list, $relativedir);
  789. //var_dump($sortfield.' - '.$sortorder);
  790. if (!empty($sortfield) && !empty($sortorder)) { // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
  791. $file_list = dol_sort_array($file_list, $sortfield, $sortorder);
  792. }
  793. }
  794. foreach ($file_list as $file) {
  795. // Define relative path for download link (depends on module)
  796. $relativepath = $file["name"]; // Cas general
  797. if ($modulesubdir) {
  798. $relativepath = $modulesubdir."/".$file["name"]; // Cas propal, facture...
  799. }
  800. if ($modulepart == 'export') {
  801. $relativepath = $file["name"]; // Other case
  802. }
  803. $out .= '<tr class="oddeven">';
  804. $documenturl = DOL_URL_ROOT.'/document.php';
  805. if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) {
  806. $documenturl = $conf->global->DOL_URL_ROOT_DOCUMENT_PHP; // To use another wrapper
  807. }
  808. // Show file name with link to download
  809. $out .= '<td class="minwidth200 tdoverflowmax300">';
  810. $out .= '<a class="documentdownload paddingright" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param ? '&'.$param : '').'"';
  811. $mime = dol_mimetype($relativepath, '', 0);
  812. if (preg_match('/text/', $mime)) {
  813. $out .= ' target="_blank" rel="noopener noreferrer"';
  814. }
  815. $out .= '>';
  816. $out .= img_mime($file["name"], $langs->trans("File").': '.$file["name"]);
  817. $out .= dol_trunc($file["name"], 150);
  818. $out .= '</a>'."\n";
  819. $out .= $this->showPreview($file, $modulepart, $relativepath, 0, $param);
  820. $out .= '</td>';
  821. // Show file size
  822. $size = (!empty($file['size']) ? $file['size'] : dol_filesize($filedir."/".$file["name"]));
  823. $out .= '<td class="nowraponall right">'.dol_print_size($size, 1, 1).'</td>';
  824. // Show file date
  825. $date = (!empty($file['date']) ? $file['date'] : dol_filemtime($filedir."/".$file["name"]));
  826. $out .= '<td class="nowrap right">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
  827. // Show share link
  828. $out .= '<td class="nowraponall">';
  829. if (!empty($file['share'])) {
  830. // Define $urlwithroot
  831. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  832. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  833. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  834. //print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
  835. $forcedownload = 0;
  836. $paramlink = '';
  837. if (!empty($file['share'])) {
  838. $paramlink .= ($paramlink ? '&' : '').'hashp='.$file['share']; // Hash for public share
  839. }
  840. if ($forcedownload) {
  841. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  842. }
  843. $fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  844. $out .= img_picto($langs->trans("FileSharedViaALink"), 'globe').' ';
  845. $out .= '<input type="text" class="quatrevingtpercentminusx width75 nopadding small" id="downloadlink'.$file['rowid'].'" name="downloadexternallink" title="'.dol_escape_htmltag($langs->trans("FileSharedViaALink")).'" value="'.dol_escape_htmltag($fulllink).'">';
  846. $out .= ajax_autoselect('downloadlink'.$file['rowid']);
  847. } else {
  848. //print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
  849. }
  850. $out .= '</td>';
  851. // Show picto delete, print...
  852. if ($delallowed || $printer || $morepicto) {
  853. $out .= '<td class="right nowraponall">';
  854. if ($delallowed) {
  855. $tmpurlsource = preg_replace('/#[a-zA-Z0-9_]*$/', '', $urlsource);
  856. $out .= '<a class="reposition" href="'.$tmpurlsource.((strpos($tmpurlsource, '?') === false) ? '?' : '&').'action='.urlencode($removeaction).'&token='.newToken().'&file='.urlencode($relativepath);
  857. $out .= ($param ? '&'.$param : '');
  858. //$out.= '&modulepart='.$modulepart; // TODO obsolete ?
  859. //$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ?
  860. $out .= '">'.img_picto($langs->trans("Delete"), 'delete').'</a>';
  861. }
  862. if ($printer) {
  863. $out .= '<a class="marginleftonly reposition" href="'.$urlsource.(strpos($urlsource, '?') ? '&' : '?').'action=print_file&token='.newToken().'&printer='.urlencode($modulepart).'&file='.urlencode($relativepath);
  864. $out .= ($param ? '&'.$param : '');
  865. $out .= '">'.img_picto($langs->trans("PrintFile", $relativepath), 'printer.png').'</a>';
  866. }
  867. if ($morepicto) {
  868. $morepicto = preg_replace('/__FILENAMEURLENCODED__/', urlencode($relativepath), $morepicto);
  869. $out .= $morepicto;
  870. }
  871. $out .= '</td>';
  872. }
  873. if (is_object($hookmanager)) {
  874. $parameters = array('colspan'=>($colspan + $colspanmore), 'socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'modulepart'=>$modulepart, 'relativepath'=>$relativepath);
  875. $res = $hookmanager->executeHooks('formBuilddocLineOptions', $parameters, $file);
  876. if (empty($res)) {
  877. $out .= $hookmanager->resPrint; // Complete line
  878. $out .= '</tr>';
  879. } else {
  880. $out = $hookmanager->resPrint; // Replace all $out
  881. }
  882. }
  883. }
  884. $this->numoffiles++;
  885. }
  886. // Loop on each link found
  887. if (is_array($link_list)) {
  888. $colspan = 2;
  889. foreach ($link_list as $file) {
  890. $out .= '<tr class="oddeven">';
  891. $out .= '<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
  892. $out .= '<a data-ajax="false" href="'.$file->url.'" target="_blank" rel="noopener noreferrer">';
  893. $out .= $file->label;
  894. $out .= '</a>';
  895. $out .= '</td>';
  896. $out .= '<td class="right">';
  897. $out .= dol_print_date($file->datea, 'dayhour');
  898. $out .= '</td>';
  899. if ($delallowed || $printer || $morepicto) {
  900. $out .= '<td></td>';
  901. }
  902. $out .= '</tr>'."\n";
  903. }
  904. $this->numoffiles++;
  905. }
  906. if (count($file_list) == 0 && count($link_list) == 0 && $headershown) {
  907. $out .= '<tr><td colspan="'.(3 + ($addcolumforpicto ? 1 : 0)).'"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>'."\n";
  908. }
  909. }
  910. if ($headershown) {
  911. // Affiche pied du tableau
  912. $out .= "</table>\n";
  913. $out .= "</div>\n";
  914. if ($genallowed) {
  915. if (empty($noform)) {
  916. $out .= '</form>'."\n";
  917. }
  918. }
  919. }
  920. $out .= '<!-- End show_document -->'."\n";
  921. //return ($i?$i:$headershown);
  922. return $out;
  923. }
  924. /**
  925. * Show a Document icon with link(s)
  926. * You may want to call this into a div like this:
  927. * print '<div class="inline-block valignmiddle">'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'</div>';
  928. *
  929. * @param string $modulepart 'propal', 'facture', 'facture_fourn', ...
  930. * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
  931. * @param string $filedir Full path to directory to scan
  932. * @param string $filter Filter filenames on this regex string (Example: '\.pdf$')
  933. * @param string $morecss Add more css to the download picto
  934. * @param string $allfiles 0=Only generated docs, 1=All files
  935. * @return string Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
  936. */
  937. public function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter = '', $morecss = 'valignmiddle', $allfiles = 0)
  938. {
  939. global $conf, $langs;
  940. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  941. $out = '';
  942. $this->infofiles = array('nboffiles'=>0, 'extensions'=>array(), 'files'=>array());
  943. $entity = 1; // Without multicompany
  944. // Get object entity
  945. if (!empty($conf->multicompany->enabled)) {
  946. $regs = array();
  947. preg_match('/\/([0-9]+)\/[^\/]+\/'.preg_quote($modulesubdir, '/').'$/', $filedir, $regs);
  948. $entity = ((!empty($regs[1]) && $regs[1] > 1) ? $regs[1] : 1); // If entity id not found in $filedir this is entity 1 by default
  949. }
  950. // Get list of files starting with name of ref (Note: files with '^ref\.extension' are generated files, files with '^ref-...' are uploaded files)
  951. if ($allfiles || !empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP)) {
  952. $filterforfilesearch = '^'.preg_quote(basename($modulesubdir), '/');
  953. } else {
  954. $filterforfilesearch = '^'.preg_quote(basename($modulesubdir), '/').'\.';
  955. }
  956. $file_list = dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // We also discard .meta and .png preview
  957. //var_dump($file_list);
  958. // For ajax treatment
  959. $out .= '<!-- html.formfile::getDocumentsLink -->'."\n";
  960. if (!empty($file_list)) {
  961. $out = '<dl class="dropdown inline-block">
  962. <dt><a data-ajax="false" href="#" onClick="return false;">'.img_picto('', 'listlight', '', 0, 0, 0, '', $morecss).'</a></dt>
  963. <dd><div class="multichoicedoc" style="position:absolute;left:100px;" ><ul class="ulselectedfields">';
  964. $tmpout = '';
  965. // Loop on each file found
  966. $found = 0;
  967. $i = 0;
  968. foreach ($file_list as $file) {
  969. $i++;
  970. if ($filter && !preg_match('/'.$filter.'/i', $file["name"])) {
  971. continue; // Discard this. It does not match provided filter.
  972. }
  973. $found++;
  974. // Define relative path for download link (depends on module)
  975. $relativepath = $file["name"]; // Cas general
  976. if ($modulesubdir) {
  977. $relativepath = $modulesubdir."/".$file["name"]; // Cas propal, facture...
  978. }
  979. // Autre cas
  980. if ($modulepart == 'donation') {
  981. $relativepath = get_exdir($modulesubdir, 2, 0, 0, null, 'donation').$file["name"];
  982. }
  983. if ($modulepart == 'export') {
  984. $relativepath = $file["name"];
  985. }
  986. $this->infofiles['nboffiles']++;
  987. $this->infofiles['files'][] = $file['fullname'];
  988. $ext = pathinfo($file["name"], PATHINFO_EXTENSION);
  989. if (empty($this->infofiles[$ext])) {
  990. $this->infofiles['extensions'][$ext] = 1;
  991. } else {
  992. $this->infofiles['extensions'][$ext]++;
  993. }
  994. // Preview
  995. if (!empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone')) {
  996. $tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
  997. if ($tmparray && $tmparray['url']) {
  998. $tmpout .= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css'] ? ' class="'.$tmparray['css'].'"' : '').($tmparray['mime'] ? ' mime="'.$tmparray['mime'].'"' : '').($tmparray['target'] ? ' target="'.$tmparray['target'].'"' : '').'>';
  999. //$tmpout.= img_picto('','detail');
  1000. $tmpout .= '<i class="fa fa-search-plus paddingright" style="color: gray"></i>';
  1001. $tmpout .= $langs->trans("Preview").' '.$ext.'</a></li>';
  1002. }
  1003. }
  1004. // Download
  1005. $tmpout .= '<li class="nowrap"><a class="pictopreview nowrap" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&amp;entity='.$entity.'&amp;file='.urlencode($relativepath).'"';
  1006. $mime = dol_mimetype($relativepath, '', 0);
  1007. if (preg_match('/text/', $mime)) {
  1008. $tmpout .= ' target="_blank" rel="noopener noreferrer"';
  1009. }
  1010. $tmpout .= '>';
  1011. $tmpout .= img_mime($relativepath, $file["name"]);
  1012. $tmpout .= $langs->trans("Download").' '.$ext;
  1013. $tmpout .= '</a></li>'."\n";
  1014. }
  1015. $out .= $tmpout;
  1016. $out .= '</ul></div></dd>
  1017. </dl>';
  1018. if (!$found) {
  1019. $out = '';
  1020. }
  1021. } else {
  1022. // TODO Add link to regenerate doc ?
  1023. //$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
  1024. }
  1025. return $out;
  1026. }
  1027. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1028. /**
  1029. * Show list of documents in $filearray (may be they are all in same directory but may not)
  1030. * This also sync database if $upload_dir is defined.
  1031. *
  1032. * @param array $filearray Array of files loaded by dol_dir_list('files') function before calling this.
  1033. * @param Object $object Object on which document is linked to.
  1034. * @param string $modulepart Value for modulepart used by download or viewimage wrapper.
  1035. * @param string $param Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd)
  1036. * @param int $forcedownload Force to open dialog box "Save As" when clicking on file.
  1037. * @param string $relativepath Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT.
  1038. * @param int $permonobject Permission on object (so permission to delete or crop document)
  1039. * @param int $useinecm Change output for use in ecm module:
  1040. * 0 or 6: Add a preview column. Show also a rename button. Show also a crop button for some values of $modulepart (must be supported into hard coded list in this function + photos_resize.php + restrictedArea + checkUserAccessToObject)
  1041. * 1: Add link to edit ECM entry
  1042. * 2: Add rename and crop link
  1043. * 4: Add a preview column
  1044. * 5: Add link to edit ECM entry and Add a preview column
  1045. * @param string $textifempty Text to show if filearray is empty ('NoFileFound' if not defined)
  1046. * @param int $maxlength Maximum length of file name shown.
  1047. * @param string $title Title before list. Use 'none' to disable title.
  1048. * @param string $url Full url to use for click links ('' = autodetect)
  1049. * @param int $showrelpart 0=Show only filename (default), 1=Show first level 1 dir
  1050. * @param int $permtoeditline Permission to edit document line (You must provide a value, -1 is deprecated and must not be used any more)
  1051. * @param string $upload_dir Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this to complete file data with database indexes.
  1052. * @param string $sortfield Sort field ('name', 'size', 'position', ...)
  1053. * @param string $sortorder Sort order ('ASC' or 'DESC')
  1054. * @param int $disablemove 1=Disable move button, 0=Position move is possible.
  1055. * @param int $addfilterfields Add line with filters
  1056. * @param int $disablecrop Disable crop feature on images (-1 = auto, prefer to set it explicitely to 0 or 1)
  1057. * @return int <0 if KO, nb of files shown if OK
  1058. * @see list_of_autoecmfiles()
  1059. */
  1060. public function list_of_documents($filearray, $object, $modulepart, $param = '', $forcedownload = 0, $relativepath = '', $permonobject = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $title = '', $url = '', $showrelpart = 0, $permtoeditline = -1, $upload_dir = '', $sortfield = '', $sortorder = 'ASC', $disablemove = 1, $addfilterfields = 0, $disablecrop = -1)
  1061. {
  1062. // phpcs:enable
  1063. global $user, $conf, $langs, $hookmanager, $form;
  1064. global $sortfield, $sortorder, $maxheightmini;
  1065. global $dolibarr_main_url_root;
  1066. if ($disablecrop == -1) {
  1067. $disablecrop = 1;
  1068. // Values here must be supported by the photo_resize.php page.
  1069. if (in_array($modulepart, array('bank', 'bom', 'expensereport', 'facture', 'facture_fournisseur', 'holiday', 'medias', 'member', 'mrp', 'project', 'product', 'produit', 'propal', 'service', 'societe', 'tax', 'tax-vat', 'ticket', 'user'))) {
  1070. $disablecrop = 0;
  1071. }
  1072. }
  1073. // Define relative path used to store the file
  1074. if (empty($relativepath)) {
  1075. $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/';
  1076. if (!empty($object->element) && $object->element == 'invoice_supplier') {
  1077. $relativepath = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath
  1078. }
  1079. if (!empty($object->element) && $object->element == 'project_task') {
  1080. $relativepath = 'Call_not_supported_._Call_function_using_a_defined_relative_path_.';
  1081. }
  1082. }
  1083. // For backward compatiblity, we detect file stored into an old path
  1084. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos') {
  1085. $relativepath = preg_replace('/^.*\/produit\//', '', $filearray[0]['path']).'/';
  1086. }
  1087. // Defined relative dir to DOL_DATA_ROOT
  1088. $relativedir = '';
  1089. if ($upload_dir) {
  1090. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
  1091. $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
  1092. }
  1093. // For example here $upload_dir = '/pathtodocuments/commande/SO2001-123/'
  1094. // For example here $upload_dir = '/pathtodocuments/tax/vat/1'
  1095. $hookmanager->initHooks(array('formfile'));
  1096. $parameters = array(
  1097. 'filearray' => $filearray,
  1098. 'modulepart'=> $modulepart,
  1099. 'param' => $param,
  1100. 'forcedownload' => $forcedownload,
  1101. 'relativepath' => $relativepath, // relative filename to module dir
  1102. 'relativedir' => $relativedir, // relative dirname to DOL_DATA_ROOT
  1103. 'permtodelete' => $permonobject,
  1104. 'useinecm' => $useinecm,
  1105. 'textifempty' => $textifempty,
  1106. 'maxlength' => $maxlength,
  1107. 'title' => $title,
  1108. 'url' => $url
  1109. );
  1110. $reshook = $hookmanager->executeHooks('showFilesList', $parameters, $object);
  1111. if (!empty($reshook)) { // null or '' for bypass
  1112. return $reshook;
  1113. } else {
  1114. if (!is_object($form)) {
  1115. include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // The compoent may be included into ajax page that does not include the Form class
  1116. $form = new Form($this->db);
  1117. }
  1118. if (!preg_match('/&id=/', $param) && isset($object->id)) {
  1119. $param .= '&id='.$object->id;
  1120. }
  1121. $relativepathwihtoutslashend = preg_replace('/\/$/', '', $relativepath);
  1122. if ($relativepathwihtoutslashend) {
  1123. $param .= '&file='.urlencode($relativepathwihtoutslashend);
  1124. }
  1125. if ($permtoeditline < 0) { // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
  1126. $permtoeditline = 0;
  1127. if (in_array($modulepart, array('product', 'produit', 'service'))) {
  1128. if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) {
  1129. $permtoeditline = 1;
  1130. }
  1131. if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) {
  1132. $permtoeditline = 1;
  1133. }
  1134. }
  1135. }
  1136. if (empty($conf->global->MAIN_UPLOAD_DOC)) {
  1137. $permtoeditline = 0;
  1138. $permonobject = 0;
  1139. }
  1140. // Show list of existing files
  1141. if ((empty($useinecm) || $useinecm == 6) && $title != 'none') {
  1142. print load_fiche_titre($title ? $title : $langs->trans("AttachedFiles"), '', 'file-upload', 0, '', 'table-list-of-attached-files');
  1143. }
  1144. if (empty($url)) {
  1145. $url = $_SERVER["PHP_SELF"];
  1146. }
  1147. print '<!-- html.formfile::list_of_documents -->'."\n";
  1148. if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline) {
  1149. print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
  1150. print '<input type="hidden" name="token" value="'.newToken().'">';
  1151. print '<input type="hidden" name="action" value="renamefile">';
  1152. print '<input type="hidden" name="id" value="'.$object->id.'">';
  1153. print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
  1154. }
  1155. print '<div class="div-table-responsive-no-min">';
  1156. print '<table id="tablelines" class="centpercent liste noborder nobottom">'."\n";
  1157. if (!empty($addfilterfields)) {
  1158. print '<tr class="liste_titre nodrag nodrop">';
  1159. print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref', 'alpha')).'"></td>';
  1160. print '<td></td>';
  1161. print '<td></td>';
  1162. if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) {
  1163. print '<td></td>';
  1164. }
  1165. print '<td></td>';
  1166. print '<td></td>';
  1167. if (empty($disablemove) && count($filearray) > 1) {
  1168. print '<td></td>';
  1169. }
  1170. print "</tr>\n";
  1171. }
  1172. // Get list of files stored into database for same relative directory
  1173. if ($relativedir) {
  1174. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  1175. //var_dump($sortfield.' - '.$sortorder);
  1176. if ($sortfield && $sortorder) { // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
  1177. $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
  1178. }
  1179. }
  1180. print '<tr class="liste_titre nodrag nodrop">';
  1181. //print $url.' sortfield='.$sortfield.' sortorder='.$sortorder;
  1182. print_liste_field_titre('Documents2', $url, "name", "", $param, '', $sortfield, $sortorder, 'left ');
  1183. print_liste_field_titre('Size', $url, "size", "", $param, '', $sortfield, $sortorder, 'right ');
  1184. print_liste_field_titre('Date', $url, "date", "", $param, '', $sortfield, $sortorder, 'center ');
  1185. if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) {
  1186. print_liste_field_titre('', $url, "", "", $param, '', $sortfield, $sortorder, 'center '); // Preview
  1187. }
  1188. // Shared or not - Hash of file
  1189. print_liste_field_titre('');
  1190. // Action button
  1191. print_liste_field_titre('');
  1192. if (empty($disablemove) && count($filearray) > 1) {
  1193. print_liste_field_titre('');
  1194. }
  1195. print "</tr>\n";
  1196. $nboffiles = count($filearray);
  1197. if ($nboffiles > 0) {
  1198. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  1199. }
  1200. $i = 0;
  1201. $nboflines = 0;
  1202. $lastrowid = 0;
  1203. foreach ($filearray as $key => $file) { // filearray must be only files here
  1204. if ($file['name'] != '.'
  1205. && $file['name'] != '..'
  1206. && !preg_match('/\.meta$/i', $file['name'])) {
  1207. if ($filearray[$key]['rowid'] > 0) {
  1208. $lastrowid = $filearray[$key]['rowid'];
  1209. }
  1210. $filepath = $relativepath.$file['name'];
  1211. $editline = 0;
  1212. $nboflines++;
  1213. print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
  1214. // Do we have entry into database ?
  1215. print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
  1216. print '<tr class="oddeven" id="row-'.($filearray[$key]['rowid'] > 0 ? $filearray[$key]['rowid'] : 'AFTER'.$lastrowid.'POS'.($i + 1)).'">';
  1217. // File name
  1218. print '<td class="minwith200 tdoverflowmax500">';
  1219. // Show file name with link to download
  1220. //print "XX".$file['name']; //$file['name'] must be utf8
  1221. print '<a class="paddingright valignmiddle" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
  1222. if ($forcedownload) {
  1223. print '&attachment=1';
  1224. }
  1225. if (!empty($object->entity)) {
  1226. print '&entity='.$object->entity;
  1227. }
  1228. print '&file='.urlencode($filepath);
  1229. print '">';
  1230. print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')', 'inline-block valignmiddle paddingright');
  1231. if ($showrelpart == 1) {
  1232. print $relativepath;
  1233. }
  1234. //print dol_trunc($file['name'],$maxlength,'middle');
  1235. if (GETPOST('action', 'aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile', 'alpha'))) {
  1236. print '</a>';
  1237. $section_dir = dirname(GETPOST('urlfile', 'alpha'));
  1238. if (!preg_match('/\/$/', $section_dir)) {
  1239. $section_dir .= '/';
  1240. }
  1241. print '<input type="hidden" name="section_dir" value="'.$section_dir.'">';
  1242. print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
  1243. print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
  1244. $editline = 1;
  1245. } else {
  1246. $filenametoshow = preg_replace('/\.noexe$/', '', $file['name']);
  1247. print dol_escape_htmltag(dol_trunc($filenametoshow, 200));
  1248. print '</a>';
  1249. }
  1250. // Preview link
  1251. if (!$editline) {
  1252. print $this->showPreview($file, $modulepart, $filepath, 0, 'entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
  1253. }
  1254. print "</td>\n";
  1255. // Size
  1256. $sizetoshow = dol_print_size($file['size'], 1, 1);
  1257. $sizetoshowbytes = dol_print_size($file['size'], 0, 1);
  1258. print '<td class="right nowraponall">';
  1259. if ($sizetoshow == $sizetoshowbytes) {
  1260. print $sizetoshow;
  1261. } else {
  1262. print $form->textwithpicto($sizetoshow, $sizetoshowbytes, -1);
  1263. }
  1264. print '</td>';
  1265. // Date
  1266. print '<td class="center nowraponall">'.dol_print_date($file['date'], "dayhour", "tzuser").'</td>';
  1267. // Preview
  1268. if (empty($useinecm) || $useinecm == 4 || $useinecm == 5 || $useinecm == 6) {
  1269. $fileinfo = pathinfo($file['name']);
  1270. print '<td class="center">';
  1271. if (image_format_supported($file['name']) >= 0) {
  1272. if ($useinecm == 5 || $useinecm == 6) {
  1273. $smallfile = getImageFileNameForSize($file['name'], ''); // There is no thumb for ECM module and Media filemanager, so we use true image. TODO Change this it is slow on image dir.
  1274. } else {
  1275. $smallfile = getImageFileNameForSize($file['name'], '_small'); // For new thumbs using same ext (in lower case however) than original
  1276. }
  1277. if (!dol_is_file($file['path'].'/'.$smallfile)) {
  1278. $smallfile = getImageFileNameForSize($file['name'], '_small', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
  1279. }
  1280. //print $file['path'].'/'.$smallfile.'<br>';
  1281. $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
  1282. if (empty($urlforhref)) {
  1283. $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
  1284. print '<a href="'.$urlforhref.'" class="aphoto" target="_blank" rel="noopener noreferrer">';
  1285. } else {
  1286. print '<a href="'.$urlforhref['url'].'" class="'.$urlforhref['css'].'" target="'.$urlforhref['target'].'" mime="'.$urlforhref['mime'].'">';
  1287. }
  1288. print '<img class="photo maxwidth200 shadow valignmiddle" height="'.(($useinecm == 4 || $useinecm == 5 || $useinecm == 6) ? '20' : $maxheightmini).'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$smallfile).'" title="">';
  1289. print '</a>';
  1290. } else {
  1291. print '&nbsp;';
  1292. }
  1293. print '</td>';
  1294. }
  1295. // Shared or not - Hash of file
  1296. print '<td class="center">';
  1297. if ($relativedir && $filearray[$key]['rowid'] > 0) { // only if we are in a mode where a scan of dir were done and we have id of file in ECM table
  1298. if ($editline) {
  1299. print '<label for="idshareenabled'.$key.'">'.$langs->trans("FileSharedViaALink").'</label> ';
  1300. print '<input class="inline-block" type="checkbox" id="idshareenabled'.$key.'" name="shareenabled"'.($file['share'] ? ' checked="checked"' : '').' /> ';
  1301. } else {
  1302. if ($file['share']) {
  1303. // Define $urlwithroot
  1304. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1305. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1306. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1307. //print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
  1308. $forcedownload = 0;
  1309. $paramlink = '';
  1310. if (!empty($file['share'])) {
  1311. $paramlink .= ($paramlink ? '&' : '').'hashp='.$file['share']; // Hash for public share
  1312. }
  1313. if ($forcedownload) {
  1314. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  1315. }
  1316. $fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  1317. print img_picto($langs->trans("FileSharedViaALink"), 'globe').' ';
  1318. print '<input type="text" class="quatrevingtpercent minwidth200imp nopadding small" id="downloadlink'.$filearray[$key]['rowid'].'" name="downloadexternallink" title="'.dol_escape_htmltag($langs->trans("FileSharedViaALink")).'" value="'.dol_escape_htmltag($fulllink).'">';
  1319. } else {
  1320. //print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
  1321. }
  1322. }
  1323. }
  1324. print '</td>';
  1325. // Actions buttons (1 column or 2 if !disablemove)
  1326. if (!$editline) {
  1327. // Delete or view link
  1328. // ($param must start with &)
  1329. print '<td class="valignmiddle right actionbuttons nowraponall"><!-- action on files -->';
  1330. if ($useinecm == 1 || $useinecm == 5) { // ECM manual tree only
  1331. // $section is inside $param
  1332. $newparam .= preg_replace('/&file=.*$/', '', $param); // We don't need param file=
  1333. $backtopage = DOL_URL_ROOT.'/ecm/index.php?&section_dir='.urlencode($relativepath).$newparam;
  1334. print '<a class="editfielda editfilelink" href="'.DOL_URL_ROOT.'/ecm/file_card.php?urlfile='.urlencode($file['name']).$param.'&backtopage='.urlencode($backtopage).'" rel="'.urlencode($file['name']).'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
  1335. }
  1336. if (empty($useinecm) || $useinecm == 2 || $useinecm == 6) { // 6=Media file manager
  1337. $newmodulepart = $modulepart;
  1338. if (in_array($modulepart, array('product', 'produit', 'service'))) {
  1339. $newmodulepart = 'produit|service';
  1340. }
  1341. if (!$disablecrop && image_format_supported($file['name']) > 0) {
  1342. if ($permtoeditline) {
  1343. // Link to resize
  1344. $moreparaminurl = '';
  1345. if ($object->id > 0) {
  1346. $moreparaminurl = '&id='.$object->id;
  1347. } elseif (GETPOST('website', 'alpha')) {
  1348. $moreparaminurl = '&website='.GETPOST('website', 'alpha');
  1349. }
  1350. print '<a class="editfielda" href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).$moreparaminurl.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("ResizeOrCrop")).'">'.img_picto($langs->trans("ResizeOrCrop"), 'resize', 'class="paddingrightonly"').'</a>';
  1351. }
  1352. }
  1353. if ($permtoeditline) {
  1354. $paramsectiondir = (in_array($modulepart, array('medias', 'ecm')) ? '&section_dir='.urlencode($relativepath) : '');
  1355. print '<a class="editfielda reposition editfilelink" href="'.(($useinecm == 1 || $useinecm == 5) ? '#' : ($url.'?action=editfile&token='.newToken().'&urlfile='.urlencode($filepath).$paramsectiondir.$param)).'" rel="'.$filepath.'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
  1356. }
  1357. }
  1358. if ($permonobject) {
  1359. $useajax = 1;
  1360. if (!empty($conf->dol_use_jmobile)) {
  1361. $useajax = 0;
  1362. }
  1363. if (empty($conf->use_javascript_ajax)) {
  1364. $useajax = 0;
  1365. }
  1366. if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) {
  1367. $useajax = 0;
  1368. }
  1369. print '<a href="'.((($useinecm && $useinecm != 6) && $useajax) ? '#' : ($url.'?action=deletefile&token='.newToken().'&urlfile='.urlencode($filepath).$param)).'" class="reposition deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
  1370. }
  1371. print "</td>";
  1372. if (empty($disablemove) && count($filearray) > 1) {
  1373. if ($nboffiles > 1 && $conf->browser->layout != 'phone') {
  1374. print '<td class="linecolmove tdlineupdown center">';
  1375. if ($i > 0) {
  1376. print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=up&rowid='.$line->id.'">'.img_up('default', 0, 'imgupforline').'</a>';
  1377. }
  1378. if ($i < ($nboffiles - 1)) {
  1379. print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=down&rowid='.$line->id.'">'.img_down('default', 0, 'imgdownforline').'</a>';
  1380. }
  1381. print '</td>';
  1382. } else {
  1383. print '<td'.(($conf->browser->layout != 'phone') ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'>';
  1384. print '</td>';
  1385. }
  1386. }
  1387. } else {
  1388. print '<td class="right">';
  1389. print '<input type="hidden" name="ecmfileid" value="'.$filearray[$key]['rowid'].'">';
  1390. print '<input type="submit" class="button button-save" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
  1391. print '<input type="submit" class="button button-cancel" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
  1392. print '</td>';
  1393. if (empty($disablemove) && count($filearray) > 1) {
  1394. print '<td class="right"></td>';
  1395. }
  1396. }
  1397. print "</tr>\n";
  1398. $i++;
  1399. }
  1400. }
  1401. if ($nboffiles == 0) {
  1402. $colspan = '6';
  1403. if (empty($disablemove) && count($filearray) > 1) {
  1404. $colspan++; // 6 columns or 7
  1405. }
  1406. print '<tr class="oddeven"><td colspan="'.$colspan.'">';
  1407. if (empty($textifempty)) {
  1408. print '<span class="opacitymedium">'.$langs->trans("NoFileFound").'</span>';
  1409. } else {
  1410. print '<span class="opacitymedium">'.$textifempty.'</span>';
  1411. }
  1412. print '</td></tr>';
  1413. }
  1414. print "</table>";
  1415. print '</div>';
  1416. if ($nboflines > 1 && is_object($object)) {
  1417. if (!empty($conf->use_javascript_ajax) && $permtoeditline) {
  1418. $table_element_line = 'ecm_files';
  1419. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  1420. }
  1421. }
  1422. print ajax_autoselect('downloadlink');
  1423. if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline) {
  1424. print '</form>';
  1425. }
  1426. return $nboffiles;
  1427. }
  1428. }
  1429. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1430. /**
  1431. * Show list of documents in a directory of ECM module.
  1432. *
  1433. * @param string $upload_dir Directory that was scanned. This directory will contains files into subdirs REF/files
  1434. * @param array $filearray Array of files loaded by dol_dir_list function before calling this function
  1435. * @param string $modulepart Value for modulepart used by download wrapper. Value can be $object->table_name (that is 'myobject' or 'mymodule_myobject') or $object->element.'-'.$module (for compatibility purpose)
  1436. * @param string $param Parameters on sort links
  1437. * @param int $forcedownload Force to open dialog box "Save As" when clicking on file
  1438. * @param string $relativepath Relative path of docs (autodefined if not provided)
  1439. * @param int $permissiontodelete Permission to delete
  1440. * @param int $useinecm Change output for use in ecm module
  1441. * @param int $textifempty Text to show if filearray is empty
  1442. * @param int $maxlength Maximum length of file name shown
  1443. * @param string $url Full url to use for click links ('' = autodetect)
  1444. * @param int $addfilterfields Add line with filters
  1445. * @return int <0 if KO, nb of files shown if OK
  1446. * @see list_of_documents()
  1447. */
  1448. public function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload = 0, $relativepath = '', $permissiontodelete = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $url = '', $addfilterfields = 0)
  1449. {
  1450. // phpcs:enable
  1451. global $user, $conf, $langs, $hookmanager, $form;
  1452. global $sortfield, $sortorder;
  1453. global $search_doc_ref;
  1454. global $dolibarr_main_url_root;
  1455. dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
  1456. // Show list of documents
  1457. if (empty($useinecm) || $useinecm == 6) {
  1458. print load_fiche_titre($langs->trans("AttachedFiles"));
  1459. }
  1460. if (empty($url)) {
  1461. $url = $_SERVER["PHP_SELF"];
  1462. }
  1463. if (!empty($addfilterfields)) {
  1464. print '<form action="'.$_SERVER['PHP_SELF'].'">';
  1465. print '<input type="hidden" name="token" value="'.newToken().'">';
  1466. print '<input type="hidden" name="module" value="'.$modulepart.'">';
  1467. }
  1468. print '<div class="div-table-responsive-no-min">';
  1469. print '<table width="100%" class="noborder">'."\n";
  1470. if (!empty($addfilterfields)) {
  1471. print '<tr class="liste_titre nodrag nodrop">';
  1472. print '<td class="liste_titre"></td>';
  1473. print '<td class="liste_titre"><input type="text" class="maxwidth100onsmartphone" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
  1474. print '<td class="liste_titre"></td>';
  1475. print '<td class="liste_titre"></td>';
  1476. // Action column
  1477. print '<td class="liste_titre right">';
  1478. $searchpicto = $form->showFilterButtons();
  1479. print $searchpicto;
  1480. print '</td>';
  1481. print "</tr>\n";
  1482. }
  1483. print '<tr class="liste_titre">';
  1484. $sortref = "fullname";
  1485. if ($modulepart == 'invoice_supplier') {
  1486. $sortref = 'level1name';
  1487. }
  1488. print_liste_field_titre("Ref", $url, $sortref, "", $param, '', $sortfield, $sortorder);
  1489. print_liste_field_titre("Documents2", $url, "name", "", $param, '', $sortfield, $sortorder);
  1490. print_liste_field_titre("Size", $url, "size", "", $param, '', $sortfield, $sortorder, 'right ');
  1491. print_liste_field_titre("Date", $url, "date", "", $param, '', $sortfield, $sortorder, 'center ');
  1492. print_liste_field_titre("Shared", $url, 'share', '', $param, '', $sortfield, $sortorder, 'right ');
  1493. print '</tr>'."\n";
  1494. // To show ref or specific information according to view to show (defined by $module)
  1495. $object_instance = null;
  1496. if ($modulepart == 'company') {
  1497. include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1498. $object_instance = new Societe($this->db);
  1499. } elseif ($modulepart == 'invoice') {
  1500. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  1501. $object_instance = new Facture($this->db);
  1502. } elseif ($modulepart == 'invoice_supplier') {
  1503. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  1504. $object_instance = new FactureFournisseur($this->db);
  1505. } elseif ($modulepart == 'propal') {
  1506. include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  1507. $object_instance = new Propal($this->db);
  1508. } elseif ($modulepart == 'supplier_proposal') {
  1509. include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
  1510. $object_instance = new SupplierProposal($this->db);
  1511. } elseif ($modulepart == 'order') {
  1512. include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  1513. $object_instance = new Commande($this->db);
  1514. } elseif ($modulepart == 'order_supplier') {
  1515. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  1516. $object_instance = new CommandeFournisseur($this->db);
  1517. } elseif ($modulepart == 'contract') {
  1518. include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
  1519. $object_instance = new Contrat($this->db);
  1520. } elseif ($modulepart == 'product') {
  1521. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1522. $object_instance = new Product($this->db);
  1523. } elseif ($modulepart == 'tax') {
  1524. include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
  1525. $object_instance = new ChargeSociales($this->db);
  1526. } elseif ($modulepart == 'tax-vat') {
  1527. include_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
  1528. $object_instance = new Tva($this->db);
  1529. } elseif ($modulepart == 'salaries') {
  1530. include_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php';
  1531. $object_instance = new Salary($this->db);
  1532. } elseif ($modulepart == 'project') {
  1533. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1534. $object_instance = new Project($this->db);
  1535. } elseif ($modulepart == 'project_task') {
  1536. include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  1537. $object_instance = new Task($this->db);
  1538. } elseif ($modulepart == 'fichinter') {
  1539. include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
  1540. $object_instance = new Fichinter($this->db);
  1541. } elseif ($modulepart == 'user') {
  1542. include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  1543. $object_instance = new User($this->db);
  1544. } elseif ($modulepart == 'expensereport') {
  1545. include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  1546. $object_instance = new ExpenseReport($this->db);
  1547. } elseif ($modulepart == 'holiday') {
  1548. include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
  1549. $object_instance = new Holiday($this->db);
  1550. } elseif ($modulepart == 'recruitment-recruitmentcandidature') {
  1551. include_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentcandidature.class.php';
  1552. $object_instance = new RecruitmentCandidature($this->db);
  1553. } elseif ($modulepart == 'banque') {
  1554. include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  1555. $object_instance = new Account($this->db);
  1556. } elseif ($modulepart == 'chequereceipt') {
  1557. include_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php';
  1558. $object_instance = new RemiseCheque($this->db);
  1559. } elseif ($modulepart == 'mrp-mo') {
  1560. include_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
  1561. $object_instance = new Mo($this->db);
  1562. } else {
  1563. $parameters = array('modulepart'=>$modulepart);
  1564. $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters);
  1565. if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) {
  1566. if (array_key_exists('classpath', $hookmanager->resArray) && !empty($hookmanager->resArray['classpath'])) {
  1567. dol_include_once($hookmanager->resArray['classpath']);
  1568. if (array_key_exists('classname', $hookmanager->resArray) && !empty($hookmanager->resArray['classname'])) {
  1569. if (class_exists($hookmanager->resArray['classname'])) {
  1570. $tmpclassname = $hookmanager->resArray['classname'];
  1571. $object_instance = new $tmpclassname($this->db);
  1572. }
  1573. }
  1574. }
  1575. }
  1576. }
  1577. //var_dump($filearray);
  1578. //var_dump($object_instance);
  1579. // Get list of files stored into database for same relative directory
  1580. $relativepathfromroot = preg_replace('/'.preg_quote(DOL_DATA_ROOT.'/', '/').'/', '', $upload_dir);
  1581. if ($relativepathfromroot) {
  1582. completeFileArrayWithDatabaseInfo($filearray, $relativepathfromroot.'/%');
  1583. //var_dump($sortfield.' - '.$sortorder);
  1584. if ($sortfield && $sortorder) { // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
  1585. $filearray = dol_sort_array($filearray, $sortfield, $sortorder, 1);
  1586. }
  1587. }
  1588. //var_dump($filearray);
  1589. foreach ($filearray as $key => $file) {
  1590. if (!is_dir($file['name'])
  1591. && $file['name'] != '.'
  1592. && $file['name'] != '..'
  1593. && $file['name'] != 'CVS'
  1594. && !preg_match('/\.meta$/i', $file['name'])) {
  1595. // Define relative path used to store the file
  1596. $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']);
  1597. $id = 0;
  1598. $ref = '';
  1599. // To show ref or specific information according to view to show (defined by $modulepart)
  1600. // $modulepart can be $object->table_name (that is 'mymodule_myobject') or $object->element.'-'.$module (for compatibility purpose)
  1601. $reg = array();
  1602. if ($modulepart == 'company' || $modulepart == 'tax' || $modulepart == 'tax-vat' || $modulepart == 'salaries') {
  1603. preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg);
  1604. $id = (isset($reg[1]) ? $reg[1] : '');
  1605. } elseif ($modulepart == 'invoice_supplier') {
  1606. preg_match('/([^\/]+)\/[^\/]+$/', $relativefile, $reg);
  1607. $ref = (isset($reg[1]) ? $reg[1] : '');
  1608. if (is_numeric($ref)) {
  1609. $id = $ref;
  1610. $ref = '';
  1611. }
  1612. } elseif ($modulepart == 'user') {
  1613. // $ref may be also id with old supplier invoices
  1614. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  1615. $id = (isset($reg[1]) ? $reg[1] : '');
  1616. } elseif ($modulepart == 'project_task') {
  1617. // $ref of task is the sub-directory of the project
  1618. $reg = explode("/", $relativefile);
  1619. $ref = (isset($reg[1]) ? $reg[1] : '');
  1620. } elseif (in_array($modulepart, array(
  1621. 'invoice',
  1622. 'propal',
  1623. 'supplier_proposal',
  1624. 'order',
  1625. 'order_supplier',
  1626. 'contract',
  1627. 'product',
  1628. 'project',
  1629. 'project_task',
  1630. 'fichinter',
  1631. 'expensereport',
  1632. 'recruitment-recruitmentcandidature',
  1633. 'mrp-mo',
  1634. 'banque',
  1635. 'chequereceipt',
  1636. 'holiday'))) {
  1637. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  1638. $ref = (isset($reg[1]) ? $reg[1] : '');
  1639. } else {
  1640. $parameters = array('modulepart'=>$modulepart, 'fileinfo'=>$file);
  1641. $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters);
  1642. if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) {
  1643. if (array_key_exists('ref', $hookmanager->resArray) && !empty($hookmanager->resArray['ref'])) {
  1644. $ref = $hookmanager->resArray['ref'];
  1645. }
  1646. if (array_key_exists('id', $hookmanager->resArray) && !empty($hookmanager->resArray['id'])) {
  1647. $id = $hookmanager->resArray['id'];
  1648. }
  1649. }
  1650. //print 'Error: Value for modulepart = '.$modulepart.' is not yet implemented in function list_of_autoecmfiles'."\n";
  1651. }
  1652. if (!$id && !$ref) {
  1653. continue;
  1654. }
  1655. $found = 0;
  1656. if (!empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
  1657. $found = 1;
  1658. } else {
  1659. //print 'Fetch '.$id." - ".$ref.' class='.get_class($object_instance).'<br>';
  1660. $result = 0;
  1661. if (is_object($object_instance)) {
  1662. if ($id) {
  1663. $result = $object_instance->fetch($id);
  1664. } else {
  1665. if (!($result = $object_instance->fetch('', $ref))) {
  1666. //fetchOneLike looks for objects with wildcards in its reference.
  1667. //It is useful for those masks who get underscores instead of their actual symbols (because the _ had replaced a forbiddn char)
  1668. //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned
  1669. //that's why we look only into fetchOneLike when fetch returns 0
  1670. // TODO Remove this part ?
  1671. $result = $object_instance->fetchOneLike($ref);
  1672. }
  1673. }
  1674. }
  1675. if ($result > 0) { // Save object loaded into a cache
  1676. $found = 1;
  1677. $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
  1678. }
  1679. if ($result == 0) {
  1680. $found = 1;
  1681. $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = 'notfound';
  1682. unset($filearray[$key]);
  1683. }
  1684. }
  1685. if (!$found > 0 || !is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
  1686. continue; // We do not show orphelins files
  1687. }
  1688. print '<!-- Line list_of_autoecmfiles key='.$key.' -->'."\n";
  1689. print '<tr class="oddeven">';
  1690. print '<td>';
  1691. if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
  1692. $tmpobject = $this->cache_objects[$modulepart.'_'.$id.'_'.$ref];
  1693. //if (! in_array($tmpobject->element, array('expensereport'))) {
  1694. print $tmpobject->getNomUrl(1, 'document');
  1695. //} else {
  1696. // print $tmpobject->getNomUrl(1);
  1697. //}
  1698. } else {
  1699. print $langs->trans("ObjectDeleted", ($id ? $id : $ref));
  1700. }
  1701. //$modulesubdir=dol_sanitizeFileName($ref);
  1702. //$modulesubdir = dirname($relativefile);
  1703. //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
  1704. //$filedir = $file['path'];
  1705. //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
  1706. //print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
  1707. print '</td>';
  1708. // File
  1709. // Check if document source has external module part, if it the case use it for module part on document.php
  1710. print '<td>';
  1711. //print "XX".$file['name']; //$file['name'] must be utf8
  1712. print '<a href="'.DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart);
  1713. if ($forcedownload) {
  1714. print '&attachment=1';
  1715. }
  1716. print '&file='.urlencode($relativefile).'">';
  1717. print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')');
  1718. print dol_trunc($file['name'], $maxlength, 'middle');
  1719. print '</a>';
  1720. //print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
  1721. print $this->showPreview($file, $modulepart, $file['relativename']);
  1722. print "</td>\n";
  1723. // Size
  1724. $sizetoshow = dol_print_size($file['size'], 1, 1);
  1725. $sizetoshowbytes = dol_print_size($file['size'], 0, 1);
  1726. print '<td class="right nowraponall">';
  1727. if ($sizetoshow == $sizetoshowbytes) {
  1728. print $sizetoshow;
  1729. } else {
  1730. print $form->textwithpicto($sizetoshow, $sizetoshowbytes, -1);
  1731. }
  1732. print '</td>';
  1733. // Date
  1734. print '<td class="center">'.dol_print_date($file['date'], "dayhour").'</td>';
  1735. // Share link
  1736. print '<td class="right">';
  1737. if (!empty($file['share'])) {
  1738. // Define $urlwithroot
  1739. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1740. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1741. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1742. //print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
  1743. $forcedownload = 0;
  1744. $paramlink = '';
  1745. if (!empty($file['share'])) {
  1746. $paramlink .= ($paramlink ? '&' : '').'hashp='.$file['share']; // Hash for public share
  1747. }
  1748. if ($forcedownload) {
  1749. $paramlink .= ($paramlink ? '&' : '').'attachment=1';
  1750. }
  1751. $fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
  1752. print img_picto($langs->trans("FileSharedViaALink"), 'globe').' ';
  1753. print '<input type="text" class="quatrevingtpercent width100 nopadding nopadding small" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'">';
  1754. }
  1755. //if (! empty($useinecm) && $useinecm != 6) print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
  1756. //if ($forcedownload) print '&attachment=1';
  1757. //print '&file='.urlencode($relativefile).'">';
  1758. //print img_view().'</a> &nbsp; ';
  1759. //if ($permissiontodelete) print '<a href="'.$url.'?id='.$object->id.'&section='.$_REQUEST["section"].'&action=delete&token='.newToken().'&urlfile='.urlencode($file['name']).'">'.img_delete().'</a>';
  1760. //else print '&nbsp;';
  1761. print "</td>";
  1762. print "</tr>\n";
  1763. }
  1764. }
  1765. if (count($filearray) == 0) {
  1766. print '<tr class="oddeven"><td colspan="5">';
  1767. if (empty($textifempty)) {
  1768. print '<span class="opacitymedium">'.$langs->trans("NoFileFound").'</span>';
  1769. } else {
  1770. print '<span class="opacitymedium">'.$textifempty.'</span>';
  1771. }
  1772. print '</td></tr>';
  1773. }
  1774. print "</table>";
  1775. print '</div>';
  1776. if (!empty($addfilterfields)) {
  1777. print '</form>';
  1778. }
  1779. // Fin de zone
  1780. }
  1781. /**
  1782. * Show form to upload a new file with jquery fileupload.
  1783. * This form use the fileupload.php file.
  1784. *
  1785. * @param Object $object Object to use
  1786. * @return void
  1787. */
  1788. private function _formAjaxFileUpload($object)
  1789. {
  1790. global $langs, $conf;
  1791. // PHP post_max_size
  1792. $post_max_size = ini_get('post_max_size');
  1793. $mul_post_max_size = substr($post_max_size, -1);
  1794. $mul_post_max_size = ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1)));
  1795. $post_max_size = $mul_post_max_size * (int) $post_max_size;
  1796. // PHP upload_max_filesize
  1797. $upload_max_filesize = ini_get('upload_max_filesize');
  1798. $mul_upload_max_filesize = substr($upload_max_filesize, -1);
  1799. $mul_upload_max_filesize = ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
  1800. $upload_max_filesize = $mul_upload_max_filesize * (int) $upload_max_filesize;
  1801. // Max file size
  1802. $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
  1803. // Include main
  1804. include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
  1805. // Include template
  1806. include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php';
  1807. }
  1808. /**
  1809. * Show array with linked files
  1810. *
  1811. * @param Object $object Object
  1812. * @param int $permissiontodelete Deletion is allowed
  1813. * @param string $action Action
  1814. * @param string $selected ???
  1815. * @param string $param More param to add into URL
  1816. * @return int Number of links
  1817. */
  1818. public function listOfLinks($object, $permissiontodelete = 1, $action = null, $selected = null, $param = '')
  1819. {
  1820. global $user, $conf, $langs, $user;
  1821. global $sortfield, $sortorder;
  1822. $langs->load("link");
  1823. require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
  1824. $link = new Link($this->db);
  1825. $links = array();
  1826. if ($sortfield == "name") {
  1827. $sortfield = "label";
  1828. } elseif ($sortfield == "date") {
  1829. $sortfield = "datea";
  1830. } else {
  1831. $sortfield = null;
  1832. }
  1833. $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
  1834. $param .= (isset($object->id) ? '&id='.$object->id : '');
  1835. print '<!-- listOfLinks -->'."\n";
  1836. // Show list of associated links
  1837. print load_fiche_titre($langs->trans("LinkedFiles"), '', 'link', 0, '', 'table-list-of-links');
  1838. print '<form action="'.$_SERVER['PHP_SELF'].($param ? '?'.$param : '').'" method="POST">';
  1839. print '<input type="hidden" name="token" value="'.newToken().'">';
  1840. print '<table class="liste noborder nobottom centpercent">';
  1841. print '<tr class="liste_titre">';
  1842. print_liste_field_titre(
  1843. $langs->trans("Links"),
  1844. $_SERVER['PHP_SELF'],
  1845. "name",
  1846. "",
  1847. $param,
  1848. '',
  1849. $sortfield,
  1850. $sortorder,
  1851. ''
  1852. );
  1853. print_liste_field_titre(
  1854. "",
  1855. "",
  1856. "",
  1857. "",
  1858. "",
  1859. '',
  1860. '',
  1861. '',
  1862. 'right '
  1863. );
  1864. print_liste_field_titre(
  1865. $langs->trans("Date"),
  1866. $_SERVER['PHP_SELF'],
  1867. "date",
  1868. "",
  1869. $param,
  1870. '',
  1871. $sortfield,
  1872. $sortorder,
  1873. 'center '
  1874. );
  1875. print_liste_field_titre(
  1876. '',
  1877. $_SERVER['PHP_SELF'],
  1878. "",
  1879. "",
  1880. $param,
  1881. '',
  1882. '',
  1883. '',
  1884. 'center '
  1885. );
  1886. print_liste_field_titre('', '', '');
  1887. print '</tr>';
  1888. $nboflinks = count($links);
  1889. if ($nboflinks > 0) {
  1890. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  1891. }
  1892. foreach ($links as $link) {
  1893. print '<tr class="oddeven">';
  1894. //edit mode
  1895. if ($action == 'update' && $selected === $link->id) {
  1896. print '<td>';
  1897. print '<input type="hidden" name="id" value="'.$object->id.'">';
  1898. print '<input type="hidden" name="linkid" value="'.$link->id.'">';
  1899. print '<input type="hidden" name="action" value="confirm_updateline">';
  1900. print $langs->trans('Link').': <input type="text" name="link" value="'.$link->url.'">';
  1901. print '</td>';
  1902. print '<td>';
  1903. print $langs->trans('Label').': <input type="text" name="label" value="'.dol_escape_htmltag($link->label).'">';
  1904. print '</td>';
  1905. print '<td class="center">'.dol_print_date(dol_now(), "dayhour", "tzuser").'</td>';
  1906. print '<td class="right"></td>';
  1907. print '<td class="right">';
  1908. print '<input type="submit" class="button button-save" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
  1909. print '<input type="submit" class="button button-cancel" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
  1910. print '</td>';
  1911. } else {
  1912. print '<td>';
  1913. print img_picto('', 'globe').' ';
  1914. print '<a data-ajax="false" href="'.$link->url.'" target="_blank" rel="noopener noreferrer">';
  1915. print dol_escape_htmltag($link->label);
  1916. print '</a>';
  1917. print '</td>'."\n";
  1918. print '<td class="right"></td>';
  1919. print '<td class="center">'.dol_print_date($link->datea, "dayhour", "tzuser").'</td>';
  1920. print '<td class="center"></td>';
  1921. print '<td class="right">';
  1922. print '<a href="'.$_SERVER['PHP_SELF'].'?action=update&linkid='.$link->id.$param.'&token='.newToken().'" class="editfilelink editfielda reposition" >'.img_edit().'</a>'; // id= is included into $param
  1923. if ($permissiontodelete) {
  1924. print ' &nbsp; <a class="deletefilelink reposition" href="'.$_SERVER['PHP_SELF'].'?action=deletelink&token='.newToken().'&linkid='.((int) $link->id).$param.'">'.img_delete().'</a>'; // id= is included into $param
  1925. } else {
  1926. print '&nbsp;';
  1927. }
  1928. print '</td>';
  1929. }
  1930. print "</tr>\n";
  1931. }
  1932. if ($nboflinks == 0) {
  1933. print '<tr class="oddeven"><td colspan="5">';
  1934. print '<span class="opacitymedium">'.$langs->trans("NoLinkFound").'</span>';
  1935. print '</td></tr>';
  1936. }
  1937. print "</table>";
  1938. print '</form>';
  1939. return $nboflinks;
  1940. }
  1941. /**
  1942. * Show detail icon with link for preview
  1943. *
  1944. * @param array $file Array with data of file. Example: array('name'=>...)
  1945. * @param string $modulepart propal, facture, facture_fourn, ...
  1946. * @param string $relativepath Relative path of docs
  1947. * @param integer $ruleforpicto Rule for picto: 0=Use the generic preview picto, 1=Use the picto of mime type of file). Use a negative value to show a generic picto even if preview not available.
  1948. * @param string $param More param on http links
  1949. * @return string $out Output string with HTML
  1950. */
  1951. public function showPreview($file, $modulepart, $relativepath, $ruleforpicto = 0, $param = '')
  1952. {
  1953. global $langs, $conf;
  1954. $out = '';
  1955. if ($conf->browser->layout != 'phone' && !empty($conf->use_javascript_ajax)) {
  1956. $urladvancedpreview = getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview.
  1957. if (count($urladvancedpreview)) {
  1958. $out .= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime']) ? '' : ' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target']) ? '' : ' target="'.$urladvancedpreview['target'].'"').'>';
  1959. //$out.= '<a class="pictopreview">';
  1960. if (empty($ruleforpicto)) {
  1961. //$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
  1962. $out .= '<span class="fa fa-search-plus pictofixedwidth" style="color: gray"></span>';
  1963. } else {
  1964. $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name'], 'pictofixedwidth');
  1965. }
  1966. $out .= '</a>';
  1967. } else {
  1968. if ($ruleforpicto < 0) {
  1969. $out .= img_picto('', 'generic', '', false, 0, 0, '', 'paddingright pictofixedwidth');
  1970. }
  1971. }
  1972. }
  1973. return $out;
  1974. }
  1975. }