actions_massactions.inc.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. <?php
  2. /* Copyright (C) 2015-2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
  4. * Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
  6. * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. * or see https://www.gnu.org/
  21. */
  22. /**
  23. * \file htdocs/core/actions_massactions.inc.php
  24. * \brief Code for actions done with massaction button (send by email, merge pdf, delete, ...)
  25. */
  26. // $massaction must be defined
  27. // $objectclass and $objectlabel must be defined
  28. // $parameters, $object, $action must be defined for the hook.
  29. // $permissiontoread, $permissiontoadd, $permissiontodelete, $permissiontoclose may be defined
  30. // $uploaddir may be defined (example to $conf->project->dir_output."/";)
  31. // $toselect may be defined
  32. // $diroutputmassaction may be defined
  33. $statusesrowidAndlabel = $stasusesObj->getStatusidsAndRowids();
  34. // Protection
  35. if (empty($objectclass) || empty($uploaddir)) {
  36. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
  37. exit;
  38. }
  39. if (empty($massaction)) {
  40. $massaction = '';
  41. }
  42. $error = 0;
  43. // For backward compatibility
  44. if (!empty($permtoread) && empty($permissiontoread)) {
  45. $permissiontoread = $permtoread;
  46. }
  47. if (!empty($permtocreate) && empty($permissiontoadd)) {
  48. $permissiontoadd = $permtocreate;
  49. }
  50. if (!empty($permtodelete) && empty($permissiontodelete)) {
  51. $permissiontodelete = $permtodelete;
  52. }
  53. // Mass actions. Controls on number of lines checked.
  54. $maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
  55. if ($massaction && is_array($toselect) && count($toselect) < 1) {
  56. $error++;
  57. setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
  58. }
  59. if (!$error && isset($toselect) && is_array($toselect) && count($toselect) > $maxformassaction) {
  60. setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
  61. $error++;
  62. }
  63. if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) { // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
  64. $massaction = 'presend';
  65. }
  66. if (!$error && $massaction == 'confirm_presend') {
  67. $resaction = '';
  68. $nbsent = 0;
  69. $nbignored = 0;
  70. $langs->load("mails");
  71. include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  72. include_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php';
  73. $listofobjectid = array();
  74. $listofobjectthirdparties = array();
  75. $listofobjectcontacts = array();
  76. $listofobjectref = array();
  77. $contactidtosend = array();
  78. $attachedfilesThirdpartyObj = array();
  79. $oneemailperrecipient = (GETPOST('oneemailperrecipient', 'int') ? 1 : 0);
  80. if (!$error) {
  81. $thirdparty = new Societe($db);
  82. $objecttmp = new $objectclass($db);
  83. if ($objecttmp->element == 'expensereport') {
  84. $thirdparty = new User($db);
  85. }
  86. if ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
  87. $thirdparty = new Adherent($db);
  88. }
  89. if ($objecttmp->element == 'holiday') {
  90. $thirdparty = new User($db);
  91. }
  92. foreach ($toselect as $toselectid) {
  93. $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
  94. $result = $objecttmp->fetch($toselectid);
  95. if ($result > 0) {
  96. $listofobjectid[$toselectid] = $toselectid;
  97. $thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
  98. if ($objecttmp->element == 'societe') {
  99. $thirdpartyid = $objecttmp->id;
  100. }
  101. if ($objecttmp->element == 'expensereport') {
  102. $thirdpartyid = $objecttmp->fk_user_author;
  103. }
  104. if ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
  105. $thirdpartyid = $objecttmp->fk_member;
  106. }
  107. if ($objecttmp->element == 'holiday') {
  108. $thirdpartyid = $objecttmp->fk_user;
  109. }
  110. if (empty($thirdpartyid)) {
  111. $thirdpartyid = 0;
  112. }
  113. if ($objectclass == 'Facture') {
  114. $tmparraycontact = array();
  115. $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
  116. if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
  117. foreach ($tmparraycontact as $data_email) {
  118. $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
  119. }
  120. }
  121. } elseif ($objectclass == 'CommandeFournisseur') {
  122. $tmparraycontact = array();
  123. $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'CUSTOMER');
  124. if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
  125. foreach ($tmparraycontact as $data_email) {
  126. $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
  127. }
  128. }
  129. }
  130. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  131. $listofobjectref[$thirdpartyid][$toselectid] = $objecttmp;
  132. }
  133. }
  134. }
  135. // Check mandatory parameters
  136. if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
  137. $error++;
  138. setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
  139. $massaction = 'presend';
  140. }
  141. $receiver = GETPOST('receiver', 'alphawithlgt');
  142. if (!is_array($receiver)) {
  143. if (empty($receiver) || $receiver == '-1') {
  144. $receiver = array();
  145. } else {
  146. $receiver = array($receiver);
  147. }
  148. }
  149. if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
  150. $error++;
  151. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
  152. $massaction = 'presend';
  153. }
  154. if (!GETPOST('subject', 'restricthtml')) {
  155. $error++;
  156. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
  157. $massaction = 'presend';
  158. }
  159. // Loop on each recipient/thirdparty
  160. if (!$error) {
  161. foreach ($listofobjectthirdparties as $thirdpartyid) {
  162. $result = $thirdparty->fetch($thirdpartyid);
  163. if ($result < 0) {
  164. dol_print_error($db);
  165. exit;
  166. }
  167. $sendto = '';
  168. $sendtocc = '';
  169. $sendtobcc = '';
  170. $sendtoid = array();
  171. // Define $sendto
  172. $tmparray = array();
  173. if (trim($_POST['sendto'])) {
  174. // Recipients are provided into free text
  175. $tmparray[] = trim(GETPOST('sendto', 'alphawithlgt'));
  176. }
  177. if (count($receiver) > 0) {
  178. foreach ($receiver as $key => $val) {
  179. // Recipient was provided from combo list
  180. if ($val == 'thirdparty') { // Id of third party or user
  181. $tmparray[] = $thirdparty->name . ' <' . $thirdparty->email . '>';
  182. } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
  183. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  184. $sendtoid[] = $val;
  185. }
  186. }
  187. }
  188. $sendto = implode(',', $tmparray);
  189. // Define $sendtocc
  190. $receivercc = GETPOST('receivercc', 'alphawithlgt');
  191. if (!is_array($receivercc)) {
  192. if ($receivercc == '-1') {
  193. $receivercc = array();
  194. } else {
  195. $receivercc = array($receivercc);
  196. }
  197. }
  198. $tmparray = array();
  199. if (trim($_POST['sendtocc'])) {
  200. $tmparray[] = trim(GETPOST('sendtocc', 'alphawithlgt'));
  201. }
  202. if (count($receivercc) > 0) {
  203. foreach ($receivercc as $key => $val) {
  204. // Recipient was provided from combo list
  205. if ($val == 'thirdparty') { // Id of third party
  206. $tmparray[] = $thirdparty->name . ' <' . $thirdparty->email . '>';
  207. } elseif ($val) { // Id du contact
  208. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  209. //$sendtoid[] = $val; TODO Add also id of contact in CC ?
  210. }
  211. }
  212. }
  213. $sendtocc = implode(',', $tmparray);
  214. //var_dump($listofobjectref);exit;
  215. $listofqualifiedobj = array();
  216. $listofqualifiedref = array();
  217. $thirdpartywithoutemail = array();
  218. foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
  219. //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
  220. if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) {
  221. $langs->load("errors");
  222. $nbignored++;
  223. $resaction .= '<div class="error">' . $langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref) . '</div><br>';
  224. continue; // Payment done or started or canceled
  225. }
  226. if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) {
  227. $langs->load("errors");
  228. $nbignored++;
  229. $resaction .= '<div class="error">' . $langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref) . '</div><br>';
  230. continue;
  231. }
  232. if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) {
  233. $langs->load("errors");
  234. $nbignored++;
  235. $resaction .= '<div class="error">' . $langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref) . '</div><br>';
  236. continue; // Payment done or started or canceled
  237. }
  238. // Test recipient
  239. if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
  240. if ($objectobj->element == 'societe') {
  241. $sendto = $objectobj->email;
  242. } elseif ($objectobj->element == 'expensereport') {
  243. $fuser = new User($db);
  244. $fuser->fetch($objectobj->fk_user_author);
  245. $sendto = $fuser->email;
  246. } elseif ($objectobj->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
  247. $fadherent = new Adherent($db);
  248. $fadherent->fetch($objectobj->fk_member);
  249. $sendto = $fadherent->email;
  250. } elseif ($objectobj->element == 'holiday') {
  251. $fuser = new User($db);
  252. $fuser->fetch($objectobj->fk_user);
  253. $sendto = $fuser->email;
  254. } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
  255. $emails_to_sends = array();
  256. $objectobj->fetch_thirdparty();
  257. $contactidtosend = array();
  258. foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
  259. $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
  260. if (!in_array($contactemailid, $contactidtosend)) {
  261. $contactidtosend[] = $contactemailid;
  262. }
  263. }
  264. if (count($emails_to_sends) > 0) {
  265. $sendto = implode(',', $emails_to_sends);
  266. }
  267. } elseif ($objectobj->element == 'order_supplier' && !empty($listofobjectcontacts[$objectid])) {
  268. $emails_to_sends = array();
  269. $objectobj->fetch_thirdparty();
  270. $contactidtosend = array();
  271. foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
  272. $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
  273. if (!in_array($contactemailid, $contactidtosend)) {
  274. $contactidtosend[] = $contactemailid;
  275. }
  276. }
  277. if (count($emails_to_sends) > 0) {
  278. $sendto = implode(',', $emails_to_sends);
  279. }
  280. } else {
  281. $objectobj->fetch_thirdparty();
  282. $sendto = $objectobj->thirdparty->email;
  283. }
  284. }
  285. if (empty($sendto)) {
  286. if ($objectobj->element == 'societe') {
  287. $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty
  288. }
  289. //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
  290. $nbignored++;
  291. if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
  292. $resaction .= '<div class="error">' . $langs->trans('NoRecipientEmail', $objectobj->thirdparty->name) . '</div><br>';
  293. }
  294. dol_syslog('No recipient for thirdparty: ' . $objectobj->thirdparty->name, LOG_WARNING);
  295. $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
  296. continue;
  297. }
  298. if (GETPOST('addmaindocfile')) {
  299. // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
  300. // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc.
  301. $filename = dol_sanitizeFileName($objectobj->ref) . '.pdf';
  302. $subdir = '';
  303. // TODO Set subdir to be compatible with multi levels dir trees
  304. // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
  305. $filedir = $uploaddir . '/' . $subdir . dol_sanitizeFileName($objectobj->ref);
  306. $filepath = $filedir . '/' . $filename;
  307. // For supplier invoices, we use the file provided by supplier, not the one we generate
  308. if ($objectobj->element == 'invoice_supplier') {
  309. $fileparams = dol_most_recent_file($uploaddir . '/' . get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element) . $objectobj->ref, preg_quote($objectobj->ref, '/') . '([^\-])+');
  310. $filepath = $fileparams['fullname'];
  311. }
  312. // try to find other files generated for this object (last_main_doc)
  313. $filename_found = '';
  314. $filepath_found = '';
  315. $file_check_list = array();
  316. $file_check_list[] = array(
  317. 'name' => $filename,
  318. 'path' => $filepath,
  319. );
  320. if (!empty($conf->global->MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND) && !empty($objectobj->last_main_doc)) {
  321. $file_check_list[] = array(
  322. 'name' => basename($objectobj->last_main_doc),
  323. 'path' => DOL_DATA_ROOT . '/' . $objectobj->last_main_doc,
  324. );
  325. }
  326. foreach ($file_check_list as $file_check_arr) {
  327. if (dol_is_file($file_check_arr['path'])) {
  328. $filename_found = $file_check_arr['name'];
  329. $filepath_found = $file_check_arr['path'];
  330. break;
  331. }
  332. }
  333. if ($filepath_found) {
  334. // Create form object
  335. $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
  336. 'paths' => array($filepath_found),
  337. 'names' => array($filename_found),
  338. 'mimes' => array(dol_mimetype($filepath_found))
  339. );
  340. } else {
  341. $nbignored++;
  342. $langs->load("errors");
  343. foreach ($file_check_list as $file_check_arr) {
  344. $resaction .= '<div class="error">' . $langs->trans('ErrorCantReadFile', $file_check_arr['path']) . '</div><br>';
  345. dol_syslog('Failed to read file: ' . $file_check_arr['path'], LOG_WARNING);
  346. }
  347. continue;
  348. }
  349. }
  350. // Object of thirdparty qualified, we add it
  351. $listofqualifiedobj[$objectid] = $objectobj;
  352. $listofqualifiedref[$objectid] = $objectobj->ref;
  353. //var_dump($listofqualifiedref);
  354. }
  355. // Send email if there is at least one qualified object for current thirdparty
  356. if (count($listofqualifiedobj) > 0) {
  357. $langs->load("commercial");
  358. $reg = array();
  359. $fromtype = GETPOST('fromtype');
  360. if ($fromtype === 'user') {
  361. $from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")) . ' <' . $user->email . '>';
  362. } elseif ($fromtype === 'company') {
  363. $from = $conf->global->MAIN_INFO_SOCIETE_NOM . ' <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>';
  364. } elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
  365. $tmp = explode(',', $user->email_aliases);
  366. $from = trim($tmp[($reg[1] - 1)]);
  367. } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
  368. $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
  369. $from = trim($tmp[($reg[1] - 1)]);
  370. } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
  371. $sql = "SELECT rowid, label, email FROM " . MAIN_DB_PREFIX . "c_email_senderprofile WHERE rowid = " . (int) $reg[1];
  372. $resql = $db->query($sql);
  373. $obj = $db->fetch_object($resql);
  374. if ($obj) {
  375. $from = dol_string_nospecial($obj->label, ' ', array(",")) . ' <' . $obj->email . '>';
  376. }
  377. } else {
  378. $from = GETPOST('fromname') . ' <' . GETPOST('frommail') . '>';
  379. }
  380. $replyto = $from;
  381. $subject = GETPOST('subject', 'restricthtml');
  382. $message = GETPOST('message', 'restricthtml');
  383. $sendtobcc = GETPOST('sendtoccc');
  384. if ($objectclass == 'Propal') {
  385. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
  386. }
  387. if ($objectclass == 'Commande') {
  388. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
  389. }
  390. if ($objectclass == 'Facture') {
  391. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
  392. }
  393. if ($objectclass == 'Supplier_Proposal') {
  394. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
  395. }
  396. if ($objectclass == 'CommandeFournisseur') {
  397. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
  398. }
  399. if ($objectclass == 'FactureFournisseur') {
  400. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
  401. }
  402. if ($objectclass == 'Project') {
  403. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "") . $conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO));
  404. }
  405. // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
  406. // $looparray will be an array with number of email to send for the current thirdparty (so 1 or n if n object for same thirdparty)
  407. $looparray = array();
  408. if (!$oneemailperrecipient) {
  409. $looparray = $listofqualifiedobj;
  410. foreach ($looparray as $key => $objecttmp) {
  411. $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
  412. }
  413. } else {
  414. $objectforloop = new $objectclass($db);
  415. $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
  416. $looparray[0] = $objectforloop;
  417. }
  418. //var_dump($looparray);exit;
  419. dol_syslog("We have set an array of " . count($looparray) . " emails to send. oneemailperrecipient=" . $oneemailperrecipient);
  420. //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
  421. foreach ($looparray as $objectid => $objecttmp) { // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object
  422. // Make substitution in email content
  423. if (isModEnabled('project') && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) {
  424. $objecttmp->fetch_projet();
  425. }
  426. $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
  427. $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
  428. $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
  429. $substitutionarray['__EMAIL__'] = $thirdparty->email;
  430. $substitutionarray['__CHECK_READ__'] = '<img src="' . DOL_MAIN_URL_ROOT . '/public/emailing/mailing-read.php?tag=' . urlencode($thirdparty->tag) . '&securitykey=' . urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) . '" width="1" height="1" style="width:1px;height:1px" border="0"/>';
  431. $parameters = array('mode' => 'formemail');
  432. if (!empty($listofobjectthirdparties)) {
  433. $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
  434. }
  435. if (!empty($listofobjectref)) {
  436. $parameters['listofobjectref'] = $listofobjectref;
  437. }
  438. complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
  439. $subjectreplaced = make_substitutions($subject, $substitutionarray);
  440. $messagereplaced = make_substitutions($message, $substitutionarray);
  441. $attachedfiles = array('paths' => array(), 'names' => array(), 'mimes' => array());
  442. if ($oneemailperrecipient) {
  443. // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
  444. if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) {
  445. foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
  446. // Create form object
  447. $attachedfiles = array(
  448. 'paths' => array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
  449. 'names' => array_merge($attachedfiles['names'], $objAttachedFiles['names']),
  450. 'mimes' => array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
  451. );
  452. }
  453. }
  454. } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
  455. // Create form object
  456. // if "one email per recipient" isn't check we must separate $attachedfiles by object
  457. $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
  458. }
  459. $filepath = $attachedfiles['paths'];
  460. $filename = $attachedfiles['names'];
  461. $mimetype = $attachedfiles['mimes'];
  462. // Define the trackid when emails sent from the mass action
  463. if ($oneemailperrecipient) {
  464. $trackid = 'thi' . $thirdparty->id;
  465. if ($objecttmp->element == 'expensereport') {
  466. $trackid = 'use' . $thirdparty->id;
  467. }
  468. if ($objecttmp->element == 'holiday') {
  469. $trackid = 'use' . $thirdparty->id;
  470. }
  471. } else {
  472. $trackid = strtolower(get_class($objecttmp));
  473. if (get_class($objecttmp) == 'Contrat') {
  474. $trackid = 'con';
  475. }
  476. if (get_class($objecttmp) == 'Propal') {
  477. $trackid = 'pro';
  478. }
  479. if (get_class($objecttmp) == 'Commande') {
  480. $trackid = 'ord';
  481. }
  482. if (get_class($objecttmp) == 'Facture') {
  483. $trackid = 'inv';
  484. }
  485. if (get_class($objecttmp) == 'Supplier_Proposal') {
  486. $trackid = 'spr';
  487. }
  488. if (get_class($objecttmp) == 'CommandeFournisseur') {
  489. $trackid = 'sor';
  490. }
  491. if (get_class($objecttmp) == 'FactureFournisseur') {
  492. $trackid = 'sin';
  493. }
  494. $trackid .= $objecttmp->id;
  495. }
  496. //var_dump($filepath);
  497. //var_dump($trackid);exit;
  498. //var_dump($subjectreplaced);
  499. if (empty($sendcontext)) {
  500. $sendcontext = 'standard';
  501. }
  502. // Send mail (substitutionarray must be done just before this)
  503. require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
  504. $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext);
  505. if ($mailfile->error) {
  506. $resaction .= '<div class="error">' . $mailfile->error . '</div>';
  507. } else {
  508. $result = $mailfile->sendfile();
  509. if ($result) {
  510. $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)) . '<br>'; // Must not contain "
  511. $error = 0;
  512. // Insert logs into agenda
  513. foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
  514. if ((!$oneemailperrecipient) && $objid2 != $objectid) {
  515. continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
  516. }
  517. dol_syslog("Try to insert email event into agenda for objid=" . $objid2 . " => objectobj=" . get_class($objectobj2));
  518. /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
  519. if ($objectclass == 'Commande') $actiontypecode='AC_COM';
  520. if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
  521. if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
  522. if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
  523. if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
  524. $actionmsg = $langs->transnoentities('MailSentBy') . ' ' . $from . ' ' . $langs->transnoentities('To') . ' ' . $sendto;
  525. if ($message) {
  526. if ($sendtocc) {
  527. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
  528. }
  529. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subjectreplaced);
  530. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
  531. $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
  532. }
  533. $actionmsg2 = '';
  534. // Initialisation donnees
  535. $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
  536. $objectobj2->actionmsg = $actionmsg; // Long text
  537. $objectobj2->actionmsg2 = $actionmsg2; // Short text
  538. $objectobj2->fk_element = $objid2;
  539. $objectobj2->elementtype = $objectobj2->element;
  540. if (!empty($conf->global->MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT)) {
  541. $objectobj2->actionmsg2 = $subjectreplaced; // Short text
  542. }
  543. $triggername = strtoupper(get_class($objectobj2)) . '_SENTBYMAIL';
  544. if ($triggername == 'SOCIETE_SENTBYMAIL') {
  545. $triggername = 'COMPANY_SENTBYMAIL';
  546. }
  547. if ($triggername == 'CONTRAT_SENTBYMAIL') {
  548. $triggername = 'CONTRACT_SENTBYMAIL';
  549. }
  550. if ($triggername == 'COMMANDE_SENTBYMAIL') {
  551. $triggername = 'ORDER_SENTBYMAIL';
  552. }
  553. if ($triggername == 'FACTURE_SENTBYMAIL') {
  554. $triggername = 'BILL_SENTBYMAIL';
  555. }
  556. if ($triggername == 'EXPEDITION_SENTBYMAIL') {
  557. $triggername = 'SHIPPING_SENTBYMAIL';
  558. }
  559. if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
  560. $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
  561. }
  562. if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
  563. $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
  564. }
  565. if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
  566. $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
  567. }
  568. if ($triggername == 'PROJET_SENTBYMAIL') {
  569. $triggername = 'PROJECT_SENTBYMAIL';
  570. }
  571. if (!empty($triggername)) {
  572. // Call trigger
  573. $result = $objectobj2->call_trigger($triggername, $user);
  574. if ($result < 0) {
  575. $error++;
  576. }
  577. // End call triggers
  578. if ($error) {
  579. setEventMessages($db->lasterror(), $errors, 'errors');
  580. dol_syslog("Error in trigger " . $triggername . ' ' . $db->lasterror(), LOG_ERR);
  581. }
  582. }
  583. $nbsent++; // Nb of object sent
  584. }
  585. } else {
  586. $langs->load("other");
  587. if ($mailfile->error) {
  588. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
  589. $resaction .= '<br><div class="error">' . $mailfile->error . '</div>';
  590. } elseif (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
  591. $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
  592. } else {
  593. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto) . '<br><div class="error">(unhandled error)</div>';
  594. }
  595. }
  596. }
  597. }
  598. }
  599. }
  600. $resaction .= ($resaction ? '<br>' : $resaction);
  601. $resaction .= '<strong>' . $langs->trans("ResultOfMailSending") . ':</strong><br>' . "\n";
  602. $resaction .= $langs->trans("NbSelected") . ': ' . count($toselect) . "\n<br>";
  603. $resaction .= $langs->trans("NbIgnored") . ': ' . ($nbignored ? $nbignored : 0) . "\n<br>";
  604. $resaction .= $langs->trans("NbSent") . ': ' . ($nbsent ? $nbsent : 0) . "\n<br>";
  605. if ($nbsent) {
  606. $action = ''; // Do not show form post if there was at least one successfull sent
  607. //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
  608. setEventMessages($langs->trans("EMailSentForNElements", $nbsent . '/' . count($toselect)), null, 'mesgs');
  609. setEventMessages($resaction, null, 'mesgs');
  610. } else {
  611. //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
  612. setEventMessages($resaction, null, 'warnings');
  613. }
  614. $action = 'list';
  615. $massaction = '';
  616. }
  617. }
  618. if (!$error && $massaction == 'cancelorders') {
  619. $db->begin();
  620. $nbok = 0;
  621. $orders = GETPOST('toselect', 'array');
  622. foreach ($orders as $id_order) {
  623. $cmd = new Commande($db);
  624. if ($cmd->fetch($id_order) <= 0) {
  625. continue;
  626. }
  627. if ($cmd->statut != Commande::STATUS_VALIDATED) {
  628. $langs->load('errors');
  629. setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
  630. $error++;
  631. break;
  632. } else {
  633. // TODO We do not provide warehouse so no stock change here for the moment.
  634. $result = $cmd->cancel();
  635. }
  636. if ($result < 0) {
  637. setEventMessages($cmd->error, $cmd->errors, 'errors');
  638. $error++;
  639. break;
  640. } else {
  641. $nbok++;
  642. }
  643. }
  644. if (!$error) {
  645. if ($nbok > 1) {
  646. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  647. } else {
  648. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  649. }
  650. $db->commit();
  651. } else {
  652. $db->rollback();
  653. }
  654. }
  655. if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
  656. if (empty($diroutputmassaction)) {
  657. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
  658. exit;
  659. }
  660. require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  661. require_once DOL_DOCUMENT_ROOT . '/core/lib/pdf.lib.php';
  662. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  663. $objecttmp = new $objectclass($db);
  664. $listofobjectid = array();
  665. $listofobjectthirdparties = array();
  666. $listofobjectref = array();
  667. foreach ($toselect as $toselectid) {
  668. $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
  669. $result = $objecttmp->fetch($toselectid);
  670. if ($result > 0) {
  671. $listofobjectid[$toselectid] = $toselectid;
  672. $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
  673. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  674. $listofobjectref[$toselectid] = $objecttmp->ref;
  675. }
  676. }
  677. $arrayofinclusion = array();
  678. foreach ($listofobjectref as $tmppdf) {
  679. $arrayofinclusion[] = '^' . preg_quote(dol_sanitizeFileName($tmppdf), '/') . '\.pdf$';
  680. }
  681. foreach ($listofobjectref as $tmppdf) {
  682. $arrayofinclusion[] = '^' . preg_quote(dol_sanitizeFileName($tmppdf), '/') . '_[a-zA-Z0-9\-\_\']+\.pdf$'; // To include PDF generated from ODX files
  683. }
  684. $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
  685. // build list of files with full path
  686. $files = array();
  687. foreach ($listofobjectref as $basename) {
  688. $basename = dol_sanitizeFileName($basename);
  689. foreach ($listoffiles as $filefound) {
  690. if (strstr($filefound["name"], $basename)) {
  691. $files[] = $uploaddir . '/' . $basename . '/' . $filefound["name"];
  692. break;
  693. }
  694. }
  695. }
  696. // Define output language (Here it is not used because we do only merging existing PDF)
  697. $outputlangs = $langs;
  698. $newlang = '';
  699. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  700. $newlang = GETPOST('lang_id', 'aZ09');
  701. }
  702. //elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
  703. // $newlang = $objecttmp->thirdparty->default_lang;
  704. //}
  705. if (!empty($newlang)) {
  706. $outputlangs = new Translate("", $conf);
  707. $outputlangs->setDefaultLang($newlang);
  708. }
  709. if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
  710. // Create output dir if not exists
  711. dol_mkdir($diroutputmassaction);
  712. // Defined name of merged file
  713. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  714. $filename = preg_replace('/\s/', '_', $filename);
  715. // Save merged file
  716. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  717. if ($option == 'late') {
  718. $filename .= '_' . strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))) . '_' . strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  719. } else {
  720. $filename .= '_' . strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  721. }
  722. }
  723. if ($year) {
  724. $filename .= '_' . $year;
  725. }
  726. if ($month) {
  727. $filename .= '_' . $month;
  728. }
  729. if (count($files) > 0) {
  730. $now = dol_now();
  731. $file = $diroutputmassaction . '/' . $filename . '_' . dol_print_date($now, 'dayhourlog') . '.pdf';
  732. $input_files = '';
  733. foreach ($files as $f) {
  734. $input_files .= ' ' . escapeshellarg($f);
  735. }
  736. $cmd = 'pdftk ' . $input_files . ' cat output ' . escapeshellarg($file);
  737. exec($cmd);
  738. // check if pdftk is installed
  739. if (file_exists($file)) {
  740. if (!empty($conf->global->MAIN_UMASK)) {
  741. @chmod($file, octdec($conf->global->MAIN_UMASK));
  742. }
  743. $langs->load("exports");
  744. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename . '_' . dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  745. } else {
  746. setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
  747. }
  748. } else {
  749. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  750. }
  751. } else {
  752. // Create empty PDF
  753. $formatarray = pdf_getFormat();
  754. $page_largeur = $formatarray['width'];
  755. $page_hauteur = $formatarray['height'];
  756. $format = array($page_largeur, $page_hauteur);
  757. $pdf = pdf_getInstance($format);
  758. if (class_exists('TCPDF')) {
  759. $pdf->setPrintHeader(false);
  760. $pdf->setPrintFooter(false);
  761. }
  762. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  763. if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
  764. $pdf->SetCompression(false);
  765. }
  766. // Add all others
  767. foreach ($files as $file) {
  768. // Charge un document PDF depuis un fichier.
  769. $pagecount = $pdf->setSourceFile($file);
  770. for ($i = 1; $i <= $pagecount; $i++) {
  771. $tplidx = $pdf->importPage($i);
  772. $s = $pdf->getTemplatesize($tplidx);
  773. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  774. $pdf->useTemplate($tplidx);
  775. }
  776. }
  777. // Create output dir if not exists
  778. dol_mkdir($diroutputmassaction);
  779. // Defined name of merged file
  780. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  781. $filename = preg_replace('/\s/', '_', $filename);
  782. // Save merged file
  783. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  784. if ($option == 'late') {
  785. $filename .= '_' . strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))) . '_' . strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  786. } else {
  787. $filename .= '_' . strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  788. }
  789. }
  790. if ($year) {
  791. $filename .= '_' . $year;
  792. }
  793. if ($month) {
  794. $filename .= '_' . $month;
  795. }
  796. if ($pagecount) {
  797. $now = dol_now();
  798. $file = $diroutputmassaction . '/' . $filename . '_' . dol_print_date($now, 'dayhourlog') . '.pdf';
  799. $pdf->Output($file, 'F');
  800. if (!empty($conf->global->MAIN_UMASK)) {
  801. @chmod($file, octdec($conf->global->MAIN_UMASK));
  802. }
  803. $langs->load("exports");
  804. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename . '_' . dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  805. } else {
  806. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  807. }
  808. }
  809. }
  810. // Remove a file from massaction area
  811. if ($action == 'remove_file') {
  812. require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  813. $langs->load("other");
  814. $upload_dir = $diroutputmassaction;
  815. $file = $upload_dir . '/' . GETPOST('file');
  816. $ret = dol_delete_file($file);
  817. if ($ret) {
  818. setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
  819. } else {
  820. setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
  821. }
  822. $action = '';
  823. }
  824. // Validate records
  825. if (!$error && $massaction == 'validate' && $permissiontoadd) {
  826. $objecttmp = new $objectclass($db);
  827. if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  828. $langs->load("errors");
  829. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  830. $error++;
  831. }
  832. if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  833. $langs->load("errors");
  834. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  835. $error++;
  836. }
  837. if ($objecttmp->element == 'facture') {
  838. if (!empty($toselect) && !empty($conf->global->INVOICE_CHECK_POSTERIOR_DATE)) {
  839. // order $toselect by date
  840. $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "facture";
  841. $sql .= " WHERE rowid IN (" . $db->sanitize(implode(",", $toselect)) . ")";
  842. $sql .= " ORDER BY datef";
  843. $resql = $db->query($sql);
  844. if ($resql) {
  845. $toselectnew = [];
  846. while (!empty($arr = $db->fetch_row($resql))) {
  847. $toselectnew[] = $arr[0];
  848. }
  849. $toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
  850. } else {
  851. dol_print_error($db);
  852. $error++;
  853. }
  854. }
  855. }
  856. if (!$error) {
  857. $db->begin();
  858. $nbok = 0;
  859. foreach ($toselect as $toselectid) {
  860. $result = $objecttmp->fetch($toselectid);
  861. if ($result > 0) {
  862. if (method_exists($objecttmp, 'validate')) {
  863. $result = $objecttmp->validate($user);
  864. } elseif (method_exists($objecttmp, 'setValid')) {
  865. $result = $objecttmp->setValid($user);
  866. } else {
  867. $objecttmp->error = 'No method validate or setValid on this object';
  868. $result = -1;
  869. }
  870. if ($result == 0) {
  871. $langs->load("errors");
  872. setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
  873. $error++;
  874. break;
  875. } elseif ($result < 0) {
  876. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  877. $error++;
  878. break;
  879. } else {
  880. // validate() rename pdf but do not regenerate
  881. // Define output language
  882. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  883. $outputlangs = $langs;
  884. $newlang = '';
  885. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  886. $newlang = GETPOST('lang_id', 'aZ09');
  887. }
  888. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
  889. if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
  890. $objecttmp->fetch_thirdparty();
  891. }
  892. if (!empty($objecttmp->thirdparty)) {
  893. $newlang = $objecttmp->thirdparty->default_lang;
  894. }
  895. }
  896. if (!empty($newlang)) {
  897. $outputlangs = new Translate("", $conf);
  898. $outputlangs->setDefaultLang($newlang);
  899. $outputlangs->load('products');
  900. }
  901. $model = $objecttmp->model_pdf;
  902. $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
  903. // To be sure vars is defined
  904. $hidedetails = !empty($hidedetails) ? $hidedetails : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  905. $hidedesc = !empty($hidedesc) ? $hidedesc : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  906. $hideref = !empty($hideref) ? $hideref : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  907. $moreparams = !empty($moreparams) ? $moreparams : null;
  908. $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  909. if ($result < 0) {
  910. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  911. }
  912. }
  913. $nbok++;
  914. }
  915. } else {
  916. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  917. $error++;
  918. break;
  919. }
  920. }
  921. if (!$error) {
  922. if ($nbok > 1) {
  923. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  924. } else {
  925. setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
  926. }
  927. $db->commit();
  928. } else {
  929. $db->rollback();
  930. }
  931. //var_dump($listofobjectthirdparties);exit;
  932. }
  933. }
  934. function getInventoryIdFromMassaction($massaction){
  935. $resultInventory = explode('_', $massaction);
  936. return $resultInventory[1];
  937. }
  938. function createRollerHistoryObj($obj, $selectedIdFromInventory, $inventory_from, $inventory_to, $status_from, $status_id){
  939. $obj->id = $selectedIdFromInventory;
  940. $obj->egyebAdatok['warehouse_from'] = $inventory_from;
  941. $obj->fk_warehouse = $inventory_to;
  942. $obj->egyebAdatok['status_from'] = $status_from;
  943. $obj->status = $status_id;
  944. return $obj;
  945. }
  946. if (!$error && strpos($massaction, 'towarehouse_') !== false && $permissiontoadd) {
  947. $objForHistory = new stdClass();
  948. $status_id = '113';
  949. $inventory_from = $inventory_id;
  950. $inventory_to = getInventoryIdFromMassaction($massaction);
  951. $db->begin();
  952. if (!is_array($toselect) || empty($toselect)) {
  953. setEventMessages($langs->trans("RecordsModified", 0), null);
  954. $db->rollback();
  955. }
  956. foreach ($toselect as $toselectid) {
  957. $selectedArray = explode('_', $toselectid);
  958. $selectedStatusFromInventory = $selectedArray[0];
  959. $selectedIdFromInventory = $selectedArray[1];
  960. if ($selectedStatusFromSelector !== $status_id) {
  961. $result = $object->fetch($selectedArray[0]);
  962. if ($result > 0) {
  963. $objForHistory = createRollerHistoryObj($objForHistory, $selectedIdFromInventory, $inventory_from, $inventory_to, $statusesrowidAndlabel[$selectedStatusFromInventory], $status_id);
  964. $res = $modRollerstorage->updateStatusAndWarehouse($db, $object, $selectedIdFromInventory, $objForHistory);
  965. if ($res > 0) {
  966. $nbok++;
  967. } else {
  968. setEventMessages($object->error, $object->errors, 'errors');
  969. }
  970. } else {
  971. setEventMessages($object->error, $object->errors, 'errors');
  972. $error++;
  973. break;
  974. }
  975. }
  976. }
  977. if (!$error) {
  978. if ($nbok > 0) {
  979. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  980. }
  981. $db->commit();
  982. $toselect = array();
  983. } else {
  984. $db->rollback();
  985. }
  986. }
  987. if (!$error && strpos($massaction, "preout") !== false && $permissiontoadd) {
  988. $objForHistory = new stdClass();
  989. $status_id = '112';
  990. $inventory_from = $inventory_to = getInventoryIdFromMassaction($massaction);
  991. $db->begin();
  992. if (!is_array($toselect) || empty($toselect)) {
  993. setEventMessages($langs->trans("RecordsModified", 0), null);
  994. $db->rollback();
  995. }
  996. foreach ($toselect as $toselectid) {
  997. $selectedArray = explode('_', $toselectid);
  998. $selectedStatusFromInventory = $selectedArray[0];
  999. $selectedIdFromInventory = $selectedArray[1];
  1000. if ($selectedStatusFromSelector !== $status_id) {
  1001. $result = $object->fetch($selectedArray[0]);
  1002. if ($result > 0) {
  1003. $objForHistory = createRollerHistoryObj($objForHistory, $selectedIdFromInventory, $inventory_from, $inventory_to, $statusesrowidAndlabel[$selectedStatusFromInventory], $status_id);
  1004. $res = $modRollerstorage->updateStatus($db, $object, $selectedIdFromInventory, $objForHistory);
  1005. if ($res > 0) {
  1006. $nbok++;
  1007. } else {
  1008. setEventMessages($object->error, $object->errors, 'errors');
  1009. }
  1010. } else {
  1011. setEventMessages($object->error, $object->errors, 'errors');
  1012. $error++;
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. if (!$error) {
  1018. if ($nbok > 0) {
  1019. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1020. }
  1021. $db->commit();
  1022. $toselect = array();
  1023. } else {
  1024. $db->rollback();
  1025. }
  1026. }
  1027. if (!$error && strpos($massaction, "prewarehouse") !== false && $permissiontoadd) {
  1028. $objForHistory = new stdClass();
  1029. $status_id = '110';
  1030. $inventory_from = $inventory_to = getInventoryIdFromMassaction($massaction);
  1031. $db->begin();
  1032. if (!is_array($toselect) || empty($toselect)) {
  1033. setEventMessages($langs->trans("RecordsModified", 0), null);
  1034. $db->rollback();
  1035. }
  1036. foreach ($toselect as $toselectid) {
  1037. $selectedArray = explode('_', $toselectid);
  1038. $selectedStatusFromInventory = $selectedArray[0];
  1039. $selectedIdFromInventory = $selectedArray[1];
  1040. if ($selectedStatusFromSelector !== $status_id) {
  1041. $result = $object->fetch($selectedArray[0]);
  1042. if ($result > 0) {
  1043. $objForHistory = createRollerHistoryObj($objForHistory, $selectedIdFromInventory, $inventory_from, $inventory_to, $statusesrowidAndlabel[$selectedStatusFromInventory], $status_id);
  1044. $res = $modRollerstorage->updateStatus($db, $object, $selectedIdFromInventory, $objForHistory);
  1045. if ($res > 0) {
  1046. $nbok++;
  1047. } else {
  1048. setEventMessages($object->error, $object->errors, 'errors');
  1049. }
  1050. } else {
  1051. setEventMessages($object->error, $object->errors, 'errors');
  1052. $error++;
  1053. break;
  1054. }
  1055. }
  1056. }
  1057. if (!$error) {
  1058. if ($nbok > 0) {
  1059. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1060. }
  1061. $db->commit();
  1062. $toselect = array();
  1063. } else {
  1064. $db->rollback();
  1065. }
  1066. }
  1067. if (!$error && strpos($massaction, "prefaulty") !== false && $permissiontoadd) {
  1068. $objForHistory = new stdClass();
  1069. $status_id = '114';
  1070. $inventory_from = $inventory_to = getInventoryIdFromMassaction($massaction);
  1071. $db->begin();
  1072. if (!is_array($toselect) || empty($toselect)) {
  1073. setEventMessages($langs->trans("RecordsModified", 0), null);
  1074. $db->rollback();
  1075. }
  1076. foreach ($toselect as $toselectid) {
  1077. $selectedArray = explode('_', $toselectid);
  1078. $selectedStatusFromInventory = $selectedArray[0];
  1079. $selectedIdFromInventory = $selectedArray[1];
  1080. if ($selectedStatusFromSelector !== $status_id) {
  1081. $result = $object->fetch($selectedArray[0]);
  1082. if ($result > 0) {
  1083. $objForHistory = createRollerHistoryObj($objForHistory, $selectedIdFromInventory, $inventory_from, $inventory_to, $statusesrowidAndlabel[$selectedStatusFromInventory], $status_id);
  1084. $res = $modRollerstorage->updateStatus($db, $object, $selectedIdFromInventory, $objForHistory);
  1085. if ($res > 0) {
  1086. $nbok++;
  1087. } else {
  1088. setEventMessages($object->error, $object->errors, 'errors');
  1089. }
  1090. } else {
  1091. setEventMessages($object->error, $object->errors, 'errors');
  1092. $error++;
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. if (!$error) {
  1098. if ($nbok > 0) {
  1099. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1100. }
  1101. $db->commit();
  1102. $toselect = array();
  1103. } else {
  1104. $db->rollback();
  1105. }
  1106. }
  1107. if (!$error && strpos($massaction, "preservice") !== false && $permissiontoadd) {
  1108. $objForHistory = new stdClass();
  1109. $status_id = '111';
  1110. $inventory_from = $inventory_to = getInventoryIdFromMassaction($massaction);
  1111. $db->begin();
  1112. if (!is_array($toselect) || empty($toselect)) {
  1113. setEventMessages($langs->trans("RecordsModified", 0), null);
  1114. $db->rollback();
  1115. }
  1116. foreach ($toselect as $toselectid) {
  1117. $selectedArray = explode('_', $toselectid);
  1118. $selectedStatusFromInventory = $selectedArray[0];
  1119. $selectedIdFromInventory = $selectedArray[1];
  1120. if ($selectedStatusFromSelector !== $status_id) {
  1121. $result = $object->fetch($selectedArray[0]);
  1122. if ($result > 0) {
  1123. $objForHistory = createRollerHistoryObj($objForHistory, $selectedIdFromInventory, $inventory_from, $inventory_to, $statusesrowidAndlabel[$selectedStatusFromInventory], $status_id);
  1124. $res = $modRollerstorage->updateStatus($db, $object, $selectedIdFromInventory, $objForHistory);
  1125. if ($res > 0) {
  1126. $nbok++;
  1127. } else {
  1128. setEventMessages($object->error, $object->errors, 'errors');
  1129. }
  1130. } else {
  1131. setEventMessages($object->error, $object->errors, 'errors');
  1132. $error++;
  1133. break;
  1134. }
  1135. }
  1136. }
  1137. if (!$error) {
  1138. if ($nbok > 0) {
  1139. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1140. }
  1141. $db->commit();
  1142. $toselect = array();
  1143. } else {
  1144. $db->rollback();
  1145. }
  1146. }
  1147. // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
  1148. if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
  1149. $db->begin();
  1150. $objecttmp = new $objectclass($db);
  1151. $nbok = 0;
  1152. $TMsg = array();
  1153. foreach ($toselect as $toselectid) {
  1154. $result = $objecttmp->fetch($toselectid);
  1155. if ($result > 0) {
  1156. // Refuse deletion for some objects/status
  1157. if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
  1158. $langs->load("errors");
  1159. $nbignored++;
  1160. $TMsg[] = '<div class="error">' . $langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref) . '</div><br>';
  1161. continue;
  1162. }
  1163. if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
  1164. $langs->load("errors");
  1165. $nbignored++;
  1166. $TMsg[] = '<div class="error">' . $langs->trans('ErrorRecordHasChildren') . ' ' . $objecttmp->ref . '</div><br>';
  1167. continue;
  1168. }
  1169. if ($objectclass == 'Holiday' && !in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
  1170. $langs->load("errors");
  1171. $nbignored++;
  1172. $TMsg[] = '<div class="error">' . $langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref) . '</div><br>';
  1173. continue;
  1174. }
  1175. if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
  1176. $sql = "UPDATE " . MAIN_DB_PREFIX . "projet_task SET fk_task_parent = 0 WHERE fk_task_parent = " . ((int) $objecttmp->id);
  1177. $res = $db->query($sql);
  1178. if (!$res) {
  1179. setEventMessage('ErrorRecordParentingNotModified', 'errors');
  1180. $error++;
  1181. }
  1182. }
  1183. if (in_array($objecttmp->element, array('societe', 'member'))) {
  1184. $result = $objecttmp->delete($objecttmp->id, $user, 1);
  1185. } elseif (in_array($objecttmp->element, array('action'))) {
  1186. $result = $objecttmp->delete();
  1187. } else {
  1188. $result = $objecttmp->delete($user);
  1189. }
  1190. if (empty($result)) { // if delete returns 0, there is at least one object linked
  1191. $TMsg = array_merge($objecttmp->errors, $TMsg);
  1192. } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
  1193. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1194. $error++;
  1195. break;
  1196. } else {
  1197. $nbok++;
  1198. }
  1199. } else {
  1200. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1201. $error++;
  1202. break;
  1203. }
  1204. }
  1205. if (empty($error)) {
  1206. // Message for elements well deleted
  1207. if ($nbok > 1) {
  1208. setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
  1209. } elseif ($nbok > 0) {
  1210. setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
  1211. } else {
  1212. setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
  1213. }
  1214. // Message for elements which can't be deleted
  1215. if (!empty($TMsg)) {
  1216. sort($TMsg);
  1217. setEventMessages('', array_unique($TMsg), 'warnings');
  1218. }
  1219. $db->commit();
  1220. } else {
  1221. $db->rollback();
  1222. }
  1223. //var_dump($listofobjectthirdparties);exit;
  1224. }
  1225. // Generate document foreach object according to model linked to object
  1226. // @todo : propose model selection
  1227. if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
  1228. $db->begin();
  1229. $objecttmp = new $objectclass($db);
  1230. $nbok = 0;
  1231. foreach ($toselect as $toselectid) {
  1232. $result = $objecttmp->fetch($toselectid);
  1233. if ($result > 0) {
  1234. $outputlangs = $langs;
  1235. $newlang = '';
  1236. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1237. $newlang = GETPOST('lang_id', 'aZ09');
  1238. }
  1239. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
  1240. $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1241. }
  1242. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
  1243. $newlang = $objecttmp->default_lang; // for thirdparty
  1244. }
  1245. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
  1246. $objecttmp->fetch_thirdparty();
  1247. $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1248. }
  1249. if (!empty($newlang)) {
  1250. $outputlangs = new Translate("", $conf);
  1251. $outputlangs->setDefaultLang($newlang);
  1252. }
  1253. // To be sure vars is defined
  1254. if (empty($hidedetails)) {
  1255. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  1256. }
  1257. if (empty($hidedesc)) {
  1258. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  1259. }
  1260. if (empty($hideref)) {
  1261. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  1262. }
  1263. if (empty($moreparams)) {
  1264. $moreparams = null;
  1265. }
  1266. $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1267. if ($result <= 0) {
  1268. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1269. $error++;
  1270. break;
  1271. } else {
  1272. $nbok++;
  1273. }
  1274. } else {
  1275. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1276. $error++;
  1277. break;
  1278. }
  1279. }
  1280. if (!$error) {
  1281. if ($nbok > 1) {
  1282. setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
  1283. } else {
  1284. setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
  1285. }
  1286. $db->commit();
  1287. } else {
  1288. $db->rollback();
  1289. }
  1290. }
  1291. if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
  1292. $db->begin();
  1293. $affecttag_type = GETPOST('affecttag_type', 'alpha');
  1294. if (!empty($affecttag_type)) {
  1295. $affecttag_type_array = explode(',', $affecttag_type);
  1296. } else {
  1297. setEventMessage('CategTypeNotFound', 'errors');
  1298. }
  1299. if (!empty($affecttag_type_array)) {
  1300. //check if tag type submited exists into Tag Map categorie class
  1301. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  1302. $categ = new Categorie($db);
  1303. $to_affecttag_type_array = array();
  1304. $categ_type_array = $categ->getMapList();
  1305. foreach ($categ_type_array as $categdef) {
  1306. if (in_array($categdef['code'], $affecttag_type_array)) {
  1307. $to_affecttag_type_array[] = $categdef['code'];
  1308. }
  1309. }
  1310. //For each valid categ type set common categ
  1311. $nbok = 0;
  1312. if (!empty($to_affecttag_type_array)) {
  1313. foreach ($to_affecttag_type_array as $categ_type) {
  1314. $contcats = GETPOST('contcats_' . $categ_type, 'array');
  1315. //var_dump($toselect);exit;
  1316. foreach ($toselect as $toselectid) {
  1317. $result = $object->fetch($toselectid);
  1318. //var_dump($contcats);exit;
  1319. if ($result > 0) {
  1320. $result = $object->setCategoriesCommon($contcats, $categ_type, false);
  1321. if ($result > 0) {
  1322. $nbok++;
  1323. } else {
  1324. setEventMessages($object->error, $object->errors, 'errors');
  1325. }
  1326. } else {
  1327. setEventMessages($object->error, $object->errors, 'errors');
  1328. $error++;
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. }
  1335. if (!$error) {
  1336. if ($nbok > 1) {
  1337. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1338. } else {
  1339. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1340. }
  1341. $db->commit();
  1342. $toselect = array();
  1343. } else {
  1344. $db->rollback();
  1345. }
  1346. }
  1347. if (!$error && ($action == 'updateprice' && $confirm == 'yes') && $permissiontoadd) {
  1348. $db->begin();
  1349. if (GETPOSTISSET('pricerate')) {
  1350. $pricepercentage = GETPOST('pricerate', 'int');
  1351. if ($pricepercentage == 0) {
  1352. setEventMessages($langs->trans("RecordsModified", 0), null);
  1353. } else {
  1354. foreach ($toselect as $toselectid) {
  1355. $result = $object->fetch($toselectid);
  1356. //var_dump($contcats);exit;
  1357. if ($result > 0) {
  1358. if ($obj->price_base_type == 'TTC') {
  1359. $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
  1360. $minprice = $object->price_min_ttc;
  1361. } else {
  1362. $newprice = $object->price * (100 + $pricepercentage) / 100;
  1363. $minprice = $object->price_min;
  1364. }
  1365. $res = $object->updatePrice($newprice, $obj->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
  1366. if ($res > 0) {
  1367. $nbok++;
  1368. } else {
  1369. setEventMessages($object->error, $object->errors, 'errors');
  1370. }
  1371. } else {
  1372. setEventMessages($object->error, $object->errors, 'errors');
  1373. $error++;
  1374. break;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. if (!$error) {
  1380. if ($nbok > 0) {
  1381. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1382. }
  1383. $db->commit();
  1384. $toselect = array();
  1385. } else {
  1386. $db->rollback();
  1387. }
  1388. }
  1389. if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
  1390. $db->begin();
  1391. $supervisortoset = GETPOST('supervisortoset');
  1392. if (!empty($supervisortoset)) {
  1393. foreach ($toselect as $toselectid) {
  1394. $result = $object->fetch($toselectid);
  1395. //var_dump($contcats);exit;
  1396. if ($result > 0) {
  1397. $object->fk_user = $supervisortoset;
  1398. $res = $object->update($user);
  1399. if ($res > 0) {
  1400. $nbok++;
  1401. } else {
  1402. setEventMessages($object->error, $object->errors, 'errors');
  1403. }
  1404. } else {
  1405. setEventMessages($object->error, $object->errors, 'errors');
  1406. $error++;
  1407. break;
  1408. }
  1409. }
  1410. } else {
  1411. setEventMessage('UserNotFound', 'errors');
  1412. $error++;
  1413. }
  1414. if (!$error) {
  1415. if ($nbok > 1) {
  1416. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1417. } else {
  1418. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1419. }
  1420. $db->commit();
  1421. $toselect = array();
  1422. } else {
  1423. $db->rollback();
  1424. }
  1425. }
  1426. if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
  1427. $db->begin();
  1428. $usertoaffect = GETPOST('usertoaffect');
  1429. $projectrole = GETPOST('projectrole');
  1430. $tasksrole = GETPOST('tasksrole');
  1431. if (!empty($usertoaffect)) {
  1432. foreach ($toselect as $toselectid) {
  1433. $result = $object->fetch($toselectid);
  1434. //var_dump($contcats);exit;
  1435. if ($result > 0) {
  1436. $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
  1437. if ($res >= 0) {
  1438. $taskstatic = new Task($db);
  1439. $task_array = $taskstatic->getTasksArray(0, 0, $object->id, 0, 0);
  1440. foreach ($task_array as $task) {
  1441. $tasksToAffect = new Task($db);
  1442. $result = $tasksToAffect->fetch($task->id);
  1443. if ($result > 0) {
  1444. $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
  1445. if ($res < 0) {
  1446. setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
  1447. }
  1448. }
  1449. }
  1450. $nbok++;
  1451. } else {
  1452. setEventMessages($object->error, $object->errors, 'errors');
  1453. }
  1454. } else {
  1455. setEventMessages($object->error, $object->errors, 'errors');
  1456. $error++;
  1457. break;
  1458. }
  1459. }
  1460. } else {
  1461. setEventMessage('UserNotFound', 'errors');
  1462. $error++;
  1463. }
  1464. if (!$error) {
  1465. if ($nbok > 1) {
  1466. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1467. } else {
  1468. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1469. }
  1470. $db->commit();
  1471. $toselect = array();
  1472. } else {
  1473. $db->rollback();
  1474. }
  1475. }
  1476. if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
  1477. $db->begin();
  1478. $objecttmp = new $objectclass($db);
  1479. $nbok = 0;
  1480. foreach ($toselect as $toselectid) {
  1481. $result = $objecttmp->fetch($toselectid);
  1482. if ($result > 0) {
  1483. if (in_array($objecttmp->element, array('societe'))) {
  1484. $result = $objecttmp->setStatut(1);
  1485. }
  1486. if ($result <= 0) {
  1487. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1488. $error++;
  1489. break;
  1490. } else {
  1491. $nbok++;
  1492. }
  1493. } else {
  1494. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1495. $error++;
  1496. break;
  1497. }
  1498. }
  1499. if (!$error) {
  1500. if ($nbok > 1) {
  1501. setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
  1502. } else {
  1503. setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
  1504. }
  1505. $db->commit();
  1506. } else {
  1507. $db->rollback();
  1508. }
  1509. }
  1510. if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
  1511. $db->begin();
  1512. $objecttmp = new $objectclass($db);
  1513. $nbok = 0;
  1514. foreach ($toselect as $toselectid) {
  1515. $result = $objecttmp->fetch($toselectid);
  1516. if ($result > 0) {
  1517. if (in_array($objecttmp->element, array('societe'))) {
  1518. $result = $objecttmp->setStatut(0);
  1519. }
  1520. if ($result <= 0) {
  1521. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1522. $error++;
  1523. break;
  1524. } else {
  1525. $nbok++;
  1526. }
  1527. } else {
  1528. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1529. $error++;
  1530. break;
  1531. }
  1532. }
  1533. if (!$error) {
  1534. if ($nbok > 1) {
  1535. setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
  1536. } else {
  1537. setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
  1538. }
  1539. $db->commit();
  1540. } else {
  1541. $db->rollback();
  1542. }
  1543. }
  1544. if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
  1545. $db->begin();
  1546. $objecttmp = new $objectclass($db);
  1547. $e = new ExtraFields($db); // fetch optionals attributes and labels
  1548. $e->fetch_name_optionals_label($objecttmp->table_element);
  1549. $nbok = 0;
  1550. $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
  1551. foreach ($toselect as $toselectid) {
  1552. /** @var CommonObject $objecttmp */
  1553. $objecttmp = new $objectclass($db); // to avoid ghost data
  1554. $result = $objecttmp->fetch($toselectid);
  1555. if ($result > 0) {
  1556. // Fill array 'array_options' with data from add form
  1557. $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
  1558. if ($ret > 0) {
  1559. $objecttmp->insertExtraFields();
  1560. } else {
  1561. $error++;
  1562. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1563. }
  1564. } else {
  1565. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1566. $error++;
  1567. break;
  1568. }
  1569. }
  1570. if (!$error) {
  1571. if ($nbok > 1) {
  1572. setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
  1573. } else {
  1574. setEventMessages($langs->trans("save"), null, 'mesgs');
  1575. }
  1576. $db->commit();
  1577. } else {
  1578. $db->rollback();
  1579. }
  1580. }
  1581. if (!$error && ($massaction == 'affectcommercial' || ($action == 'affectcommercial' && $confirm == 'yes')) && $permissiontoadd) {
  1582. $db->begin();
  1583. $objecttmp = new $objectclass($db);
  1584. $nbok = 0;
  1585. foreach ($toselect as $toselectid) {
  1586. $result = $objecttmp->fetch($toselectid);
  1587. if ($result > 0) {
  1588. if (in_array($objecttmp->element, array('societe'))) {
  1589. $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
  1590. }
  1591. if ($result <= 0) {
  1592. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1593. $error++;
  1594. break;
  1595. } else {
  1596. $nbok++;
  1597. }
  1598. } else {
  1599. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1600. $error++;
  1601. break;
  1602. }
  1603. }
  1604. if (!$error) {
  1605. if ($nbok > 1) {
  1606. setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
  1607. } else {
  1608. setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
  1609. }
  1610. $db->commit();
  1611. } else {
  1612. $db->rollback();
  1613. }
  1614. }
  1615. // Approve for leave only
  1616. if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
  1617. $db->begin();
  1618. $objecttmp = new $objectclass($db);
  1619. $nbok = 0;
  1620. foreach ($toselect as $toselectid) {
  1621. $result = $objecttmp->fetch($toselectid);
  1622. if ($result > 0) {
  1623. if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
  1624. setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
  1625. continue;
  1626. }
  1627. if ($user->id == $objecttmp->fk_validator) {
  1628. $objecttmp->oldcopy = dol_clone($objecttmp);
  1629. $objecttmp->date_valid = dol_now();
  1630. $objecttmp->fk_user_valid = $user->id;
  1631. $objecttmp->statut = Holiday::STATUS_APPROVED;
  1632. $verif = $objecttmp->approve($user);
  1633. if ($verif <= 0) {
  1634. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1635. $error++;
  1636. }
  1637. // If no SQL error, we redirect to the request form
  1638. if (!$error) {
  1639. // Calculcate number of days consumed
  1640. $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
  1641. $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
  1642. $newSolde = ($soldeActuel - $nbopenedday);
  1643. // The modification is added to the LOG
  1644. $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
  1645. if ($result < 0) {
  1646. $error++;
  1647. setEventMessages(null, $objecttmp->errors, 'errors');
  1648. }
  1649. // Update balance
  1650. $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
  1651. if ($result < 0) {
  1652. $error++;
  1653. setEventMessages(null, $objecttmp->errors, 'errors');
  1654. }
  1655. }
  1656. if (!$error) {
  1657. // To
  1658. $destinataire = new User($db);
  1659. $destinataire->fetch($objecttmp->fk_user);
  1660. $emailTo = $destinataire->email;
  1661. if (!$emailTo) {
  1662. dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
  1663. } else {
  1664. // From
  1665. $expediteur = new User($db);
  1666. $expediteur->fetch($objecttmp->fk_validator);
  1667. //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
  1668. $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
  1669. // Subject
  1670. $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
  1671. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  1672. $societeName = $conf->global->MAIN_APPLICATION_TITLE;
  1673. }
  1674. $subject = $societeName . " - " . $langs->transnoentitiesnoconv("HolidaysValidated");
  1675. // Content
  1676. $message = $langs->transnoentitiesnoconv("Hello") . " " . $destinataire->firstname . ",\n";
  1677. $message .= "\n";
  1678. $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day')) . "\n";
  1679. $message .= "- " . $langs->transnoentitiesnoconv("ValidatedBy") . " : " . dolGetFirstLastname($expediteur->firstname, $expediteur->lastname) . "\n";
  1680. $message .= "- " . $langs->transnoentitiesnoconv("Link") . " : " . $dolibarr_main_url_root . "/holiday/card.php?id=" . $objecttmp->id . "\n\n";
  1681. $message .= "\n";
  1682. $trackid = 'leav' . $objecttmp->id;
  1683. require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
  1684. $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
  1685. // Sending email
  1686. $result = $mail->sendfile();
  1687. if (!$result) {
  1688. setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
  1689. $action = '';
  1690. }
  1691. }
  1692. }
  1693. } else {
  1694. $langs->load("errors");
  1695. setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
  1696. }
  1697. } else {
  1698. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1699. $error++;
  1700. break;
  1701. }
  1702. }
  1703. if (!$error) {
  1704. if ($nbok > 1) {
  1705. setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
  1706. } elseif ($nbok == 1) {
  1707. setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
  1708. }
  1709. $db->commit();
  1710. } else {
  1711. $db->rollback();
  1712. }
  1713. }
  1714. if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove) {
  1715. $db->begin();
  1716. $objecttmp = new $objectclass($db);
  1717. $nbok = 0;
  1718. $typeholiday = GETPOST('typeholiday', 'alpha');
  1719. $nbdaysholidays = GETPOST('nbdaysholidays', 'double');
  1720. if ($nbdaysholidays <= 0) {
  1721. setEventMessages($langs->trans("WrongAmount"), "", 'errors');
  1722. $error++;
  1723. }
  1724. if (!$error) {
  1725. foreach ($toselect as $toselectid) {
  1726. $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
  1727. if (!empty($balancecpuser)) {
  1728. $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
  1729. } else {
  1730. $newnbdaysholidays = $nbdaysholidays;
  1731. }
  1732. $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
  1733. if ($result <= 0) {
  1734. setEventMessages($holiday->error, $holiday->errors, 'errors');
  1735. $error++;
  1736. break;
  1737. }
  1738. $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
  1739. if ($result > 0) {
  1740. $nbok++;
  1741. } else {
  1742. setEventMessages("", $langs->trans("ErrorUpdatingUsersCP"), 'errors');
  1743. $error++;
  1744. break;
  1745. }
  1746. }
  1747. }
  1748. if (!$error) {
  1749. if ($nbok > 1) {
  1750. setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
  1751. } elseif ($nbok == 1) {
  1752. setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
  1753. }
  1754. $db->commit();
  1755. $toselect = array();
  1756. } else {
  1757. $db->rollback();
  1758. }
  1759. }
  1760. $parameters['toselect'] = (empty($toselect) ? array() : $toselect);
  1761. $parameters['uploaddir'] = $uploaddir;
  1762. $parameters['massaction'] = $massaction;
  1763. $parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
  1764. $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1765. if ($reshook < 0) {
  1766. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1767. }