actions_massactions.inc.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  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->projet->dir_output."/";)
  31. // $toselect may be defined
  32. // $diroutputmassaction may be defined
  33. // Protection
  34. if (empty($objectclass) || empty($uploaddir)) {
  35. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
  36. exit;
  37. }
  38. // For backward compatibility
  39. if (!empty($permtoread) && empty($permissiontoread)) {
  40. $permissiontoread = $permtoread;
  41. }
  42. if (!empty($permtocreate) && empty($permissiontoadd)) {
  43. $permissiontoadd = $permtocreate;
  44. }
  45. if (!empty($permtodelete) && empty($permissiontodelete)) {
  46. $permissiontodelete = $permtodelete;
  47. }
  48. // Mass actions. Controls on number of lines checked.
  49. $maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
  50. if (!empty($massaction) && is_array($toselect) && count($toselect) < 1) {
  51. $error++;
  52. setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
  53. }
  54. if (!$error && is_array($toselect) && count($toselect) > $maxformassaction) {
  55. setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
  56. $error++;
  57. }
  58. 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
  59. $massaction = 'presend';
  60. }
  61. if (!$error && $massaction == 'confirm_presend') {
  62. $resaction = '';
  63. $nbsent = 0;
  64. $nbignored = 0;
  65. $langs->load("mails");
  66. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  67. $listofobjectid = array();
  68. $listofobjectthirdparties = array();
  69. $listofobjectcontacts = array();
  70. $listofobjectref = array();
  71. $contactidtosend = array();
  72. $attachedfilesThirdpartyObj = array();
  73. $oneemailperrecipient = (GETPOST('oneemailperrecipient', 'int') ? 1 : 0);
  74. if (!$error) {
  75. $thirdparty = new Societe($db);
  76. $objecttmp = new $objectclass($db);
  77. if ($objecttmp->element == 'expensereport') {
  78. $thirdparty = new User($db);
  79. }
  80. if ($objecttmp->element == 'partnership' && $conf->global->PARTNERSHIP_IS_MANAGED_FOR == 'member') {
  81. $thirdparty = new Adherent($db);
  82. }
  83. if ($objecttmp->element == 'holiday') {
  84. $thirdparty = new User($db);
  85. }
  86. foreach ($toselect as $toselectid) {
  87. $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
  88. $result = $objecttmp->fetch($toselectid);
  89. if ($result > 0) {
  90. $listofobjectid[$toselectid] = $toselectid;
  91. $thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
  92. if ($objecttmp->element == 'societe') {
  93. $thirdpartyid = $objecttmp->id;
  94. }
  95. if ($objecttmp->element == 'expensereport') {
  96. $thirdpartyid = $objecttmp->fk_user_author;
  97. }
  98. if ($objecttmp->element == 'partnership' && $conf->global->PARTNERSHIP_IS_MANAGED_FOR == 'member') {
  99. $thirdpartyid = $objecttmp->fk_member;
  100. }
  101. if ($objecttmp->element == 'holiday') {
  102. $thirdpartyid = $objecttmp->fk_user;
  103. }
  104. if (empty($thirdpartyid)) {
  105. $thirdpartyid = 0;
  106. }
  107. if ($objectclass == 'Facture') {
  108. $tmparraycontact = array();
  109. $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
  110. if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
  111. foreach ($tmparraycontact as $data_email) {
  112. $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
  113. }
  114. }
  115. }
  116. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  117. $listofobjectref[$thirdpartyid][$toselectid] = $objecttmp;
  118. }
  119. }
  120. }
  121. // Check mandatory parameters
  122. if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
  123. $error++;
  124. setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
  125. $massaction = 'presend';
  126. }
  127. $receiver = $_POST['receiver'];
  128. if (!is_array($receiver)) {
  129. if (empty($receiver) || $receiver == '-1') {
  130. $receiver = array();
  131. } else {
  132. $receiver = array($receiver);
  133. }
  134. }
  135. if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
  136. $error++;
  137. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
  138. $massaction = 'presend';
  139. }
  140. if (!GETPOST('subject', 'restricthtml')) {
  141. $error++;
  142. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
  143. $massaction = 'presend';
  144. }
  145. // Loop on each recipient/thirdparty
  146. if (!$error) {
  147. foreach ($listofobjectthirdparties as $thirdpartyid) {
  148. $result = $thirdparty->fetch($thirdpartyid);
  149. if ($result < 0) {
  150. dol_print_error($db);
  151. exit;
  152. }
  153. $sendto = '';
  154. $sendtocc = '';
  155. $sendtobcc = '';
  156. $sendtoid = array();
  157. // Define $sendto
  158. $tmparray = array();
  159. if (trim($_POST['sendto'])) {
  160. // Recipients are provided into free text
  161. $tmparray[] = trim($_POST['sendto']);
  162. }
  163. if (count($receiver) > 0) {
  164. foreach ($receiver as $key => $val) {
  165. // Recipient was provided from combo list
  166. if ($val == 'thirdparty') { // Id of third party or user
  167. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  168. } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
  169. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  170. $sendtoid[] = $val;
  171. }
  172. }
  173. }
  174. $sendto = implode(',', $tmparray);
  175. // Define $sendtocc
  176. $receivercc = $_POST['receivercc'];
  177. if (!is_array($receivercc)) {
  178. if ($receivercc == '-1') {
  179. $receivercc = array();
  180. } else {
  181. $receivercc = array($receivercc);
  182. }
  183. }
  184. $tmparray = array();
  185. if (trim($_POST['sendtocc'])) {
  186. $tmparray[] = trim($_POST['sendtocc']);
  187. }
  188. if (count($receivercc) > 0) {
  189. foreach ($receivercc as $key => $val) {
  190. // Recipient was provided from combo list
  191. if ($val == 'thirdparty') { // Id of third party
  192. $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
  193. } elseif ($val) { // Id du contact
  194. $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
  195. //$sendtoid[] = $val; TODO Add also id of contact in CC ?
  196. }
  197. }
  198. }
  199. $sendtocc = implode(',', $tmparray);
  200. //var_dump($listofobjectref);exit;
  201. $listofqualifiedobj = array();
  202. $listofqualifiedref = array();
  203. $thirdpartywithoutemail = array();
  204. foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
  205. //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
  206. if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) {
  207. $langs->load("errors");
  208. $nbignored++;
  209. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  210. continue; // Payment done or started or canceled
  211. }
  212. if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) {
  213. $langs->load("errors");
  214. $nbignored++;
  215. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  216. continue;
  217. }
  218. if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) {
  219. $langs->load("errors");
  220. $nbignored++;
  221. $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
  222. continue; // Payment done or started or canceled
  223. }
  224. // Test recipient
  225. if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
  226. if ($objectobj->element == 'societe') {
  227. $sendto = $objectobj->email;
  228. } elseif ($objectobj->element == 'expensereport') {
  229. $fuser = new User($db);
  230. $fuser->fetch($objectobj->fk_user_author);
  231. $sendto = $fuser->email;
  232. } elseif ($objectobj->element == 'partnership' && $conf->global->PARTNERSHIP_IS_MANAGED_FOR == 'member') {
  233. $fadherent = new Adherent($db);
  234. $fadherent->fetch($objectobj->fk_member);
  235. $sendto = $fadherent->email;
  236. } elseif ($objectobj->element == 'holiday') {
  237. $fuser = new User($db);
  238. $fuser->fetch($objectobj->fk_user);
  239. $sendto = $fuser->email;
  240. } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
  241. $emails_to_sends = array();
  242. $objectobj->fetch_thirdparty();
  243. $contactidtosend = array();
  244. foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
  245. $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
  246. if (!in_array($contactemailid, $contactidtosend)) {
  247. $contactidtosend[] = $contactemailid;
  248. }
  249. }
  250. if (count($emails_to_sends) > 0) {
  251. $sendto = implode(',', $emails_to_sends);
  252. }
  253. } else {
  254. $objectobj->fetch_thirdparty();
  255. $sendto = $objectobj->thirdparty->email;
  256. }
  257. }
  258. if (empty($sendto)) {
  259. if ($objectobj->element == 'societe') {
  260. $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty
  261. }
  262. //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
  263. $nbignored++;
  264. if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
  265. $resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
  266. }
  267. dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
  268. $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
  269. continue;
  270. }
  271. if ($_POST['addmaindocfile']) {
  272. // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
  273. // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc.
  274. $filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
  275. $subdir = '';
  276. // TODO Set subdir to be compatible with multi levels dir trees
  277. // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
  278. $filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
  279. $file = $filedir.'/'.$filename;
  280. // For supplier invoices, we use the file provided by supplier, not the one we generate
  281. if ($objectobj->element == 'invoice_supplier') {
  282. $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
  283. $file = $fileparams['fullname'];
  284. }
  285. $mime = dol_mimetype($file);
  286. if (dol_is_file($file)) {
  287. // Create form object
  288. $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
  289. 'paths'=>array($file),
  290. 'names'=>array($filename),
  291. 'mimes'=>array($mime)
  292. );
  293. } else {
  294. $nbignored++;
  295. $langs->load("errors");
  296. $resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file).'</div><br>';
  297. dol_syslog('Failed to read file: '.$file, LOG_WARNING);
  298. continue;
  299. }
  300. }
  301. // Object of thirdparty qualified, we add it
  302. $listofqualifiedobj[$objectid] = $objectobj;
  303. $listofqualifiedref[$objectid] = $objectobj->ref;
  304. //var_dump($listofqualifiedref);
  305. }
  306. // Send email if there is at least one qualified object for current thirdparty
  307. if (count($listofqualifiedobj) > 0) {
  308. $langs->load("commercial");
  309. $reg = array();
  310. $fromtype = GETPOST('fromtype');
  311. if ($fromtype === 'user') {
  312. $from = $user->getFullName($langs).' <'.$user->email.'>';
  313. } elseif ($fromtype === 'company') {
  314. $from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  315. } elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
  316. $tmp = explode(',', $user->email_aliases);
  317. $from = trim($tmp[($reg[1] - 1)]);
  318. } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
  319. $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
  320. $from = trim($tmp[($reg[1] - 1)]);
  321. } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
  322. $sql = "SELECT rowid, label, email FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".(int) $reg[1];
  323. $resql = $db->query($sql);
  324. $obj = $db->fetch_object($resql);
  325. if ($obj) {
  326. $from = $obj->label.' <'.$obj->email.'>';
  327. }
  328. } else {
  329. $from = $_POST['fromname'].' <'.$_POST['frommail'].'>';
  330. }
  331. $replyto = $from;
  332. $subject = GETPOST('subject', 'restricthtml');
  333. $message = GETPOST('message', 'restricthtml');
  334. $sendtobcc = GETPOST('sendtoccc');
  335. if ($objectclass == 'Propal') {
  336. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
  337. }
  338. if ($objectclass == 'Commande') {
  339. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
  340. }
  341. if ($objectclass == 'Facture') {
  342. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
  343. }
  344. if ($objectclass == 'Supplier_Proposal') {
  345. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
  346. }
  347. if ($objectclass == 'CommandeFournisseur') {
  348. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
  349. }
  350. if ($objectclass == 'FactureFournisseur') {
  351. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
  352. }
  353. if ($objectclass == 'Project') {
  354. $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO));
  355. }
  356. // $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)
  357. // $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)
  358. $looparray = array();
  359. if (!$oneemailperrecipient) {
  360. $looparray = $listofqualifiedobj;
  361. foreach ($looparray as $key => $objecttmp) {
  362. $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
  363. }
  364. } else {
  365. $objectforloop = new $objectclass($db);
  366. $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
  367. $looparray[0] = $objectforloop;
  368. }
  369. //var_dump($looparray);exit;
  370. dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
  371. //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
  372. 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
  373. // Make substitution in email content
  374. if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) {
  375. $objecttmp->fetch_projet();
  376. }
  377. $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
  378. $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
  379. $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
  380. $substitutionarray['__EMAIL__'] = $thirdparty->email;
  381. $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"/>';
  382. $parameters = array('mode'=>'formemail');
  383. if (!empty($listofobjectthirdparties)) {
  384. $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
  385. }
  386. if (!empty($listofobjectref)) {
  387. $parameters['listofobjectref'] = $listofobjectref;
  388. }
  389. complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
  390. $subjectreplaced = make_substitutions($subject, $substitutionarray);
  391. $messagereplaced = make_substitutions($message, $substitutionarray);
  392. $attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
  393. if ($oneemailperrecipient) {
  394. // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
  395. if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) {
  396. foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
  397. // Create form object
  398. $attachedfiles = array(
  399. 'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
  400. 'names'=>array_merge($attachedfiles['names'], $objAttachedFiles['names']),
  401. 'mimes'=>array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
  402. );
  403. }
  404. }
  405. } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
  406. // Create form object
  407. // if "one email per recipient" isn't check we must separate $attachedfiles by object
  408. $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
  409. }
  410. $filepath = $attachedfiles['paths'];
  411. $filename = $attachedfiles['names'];
  412. $mimetype = $attachedfiles['mimes'];
  413. // Define the trackid when emails sent from the mass action
  414. if ($oneemailperrecipient) {
  415. $trackid = 'thi'.$thirdparty->id;
  416. if ($objecttmp->element == 'expensereport') {
  417. $trackid = 'use'.$thirdparty->id;
  418. }
  419. if ($objecttmp->element == 'holiday') {
  420. $trackid = 'use'.$thirdparty->id;
  421. }
  422. } else {
  423. $trackid = strtolower(get_class($objecttmp));
  424. if (get_class($objecttmp) == 'Contrat') {
  425. $trackid = 'con';
  426. }
  427. if (get_class($objecttmp) == 'Propal') {
  428. $trackid = 'pro';
  429. }
  430. if (get_class($objecttmp) == 'Commande') {
  431. $trackid = 'ord';
  432. }
  433. if (get_class($objecttmp) == 'Facture') {
  434. $trackid = 'inv';
  435. }
  436. if (get_class($objecttmp) == 'Supplier_Proposal') {
  437. $trackid = 'spr';
  438. }
  439. if (get_class($objecttmp) == 'CommandeFournisseur') {
  440. $trackid = 'sor';
  441. }
  442. if (get_class($objecttmp) == 'FactureFournisseur') {
  443. $trackid = 'sin';
  444. }
  445. $trackid .= $objecttmp->id;
  446. }
  447. //var_dump($filepath);
  448. //var_dump($trackid);exit;
  449. //var_dump($subjectreplaced);
  450. if (empty($sendcontext)) {
  451. $sendcontext = 'standard';
  452. }
  453. // Send mail (substitutionarray must be done just before this)
  454. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  455. $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext);
  456. if ($mailfile->error) {
  457. $resaction .= '<div class="error">'.$mailfile->error.'</div>';
  458. } else {
  459. $result = $mailfile->sendfile();
  460. if ($result) {
  461. $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'<br>'; // Must not contain "
  462. $error = 0;
  463. // Insert logs into agenda
  464. foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
  465. if ((!$oneemailperrecipient) && $objid2 != $objectid) {
  466. continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
  467. }
  468. dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
  469. /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
  470. if ($objectclass == 'Commande') $actiontypecode='AC_COM';
  471. if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
  472. if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
  473. if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
  474. if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
  475. $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
  476. if ($message) {
  477. if ($sendtocc) {
  478. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
  479. }
  480. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
  481. $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
  482. $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
  483. }
  484. $actionmsg2 = '';
  485. // Initialisation donnees
  486. $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
  487. $objectobj2->actionmsg = $actionmsg; // Long text
  488. $objectobj2->actionmsg2 = $actionmsg2; // Short text
  489. $objectobj2->fk_element = $objid2;
  490. $objectobj2->elementtype = $objectobj2->element;
  491. $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
  492. if ($triggername == 'SOCIETE_SENTBYMAIL') {
  493. $triggername = 'COMPANY_SENTBYMAIL';
  494. }
  495. if ($triggername == 'CONTRAT_SENTBYMAIL') {
  496. $triggername = 'CONTRACT_SENTBYMAIL';
  497. }
  498. if ($triggername == 'COMMANDE_SENTBYMAIL') {
  499. $triggername = 'ORDER_SENTBYMAIL';
  500. }
  501. if ($triggername == 'FACTURE_SENTBYMAIL') {
  502. $triggername = 'BILL_SENTBYMAIL';
  503. }
  504. if ($triggername == 'EXPEDITION_SENTBYMAIL') {
  505. $triggername = 'SHIPPING_SENTBYMAIL';
  506. }
  507. if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
  508. $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
  509. }
  510. if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
  511. $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
  512. }
  513. if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
  514. $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
  515. }
  516. if (!empty($triggername)) {
  517. // Call trigger
  518. $result = $objectobj2->call_trigger($triggername, $user);
  519. if ($result < 0) {
  520. $error++;
  521. }
  522. // End call triggers
  523. if ($error) {
  524. setEventMessages($db->lasterror(), $errors, 'errors');
  525. dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
  526. }
  527. }
  528. $nbsent++; // Nb of object sent
  529. }
  530. } else {
  531. $langs->load("other");
  532. if ($mailfile->error) {
  533. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
  534. $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
  535. } elseif (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
  536. $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
  537. } else {
  538. $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto) . '<br><div class="error">(unhandled error)</div>';
  539. }
  540. }
  541. }
  542. }
  543. }
  544. }
  545. $resaction .= ($resaction ? '<br>' : $resaction);
  546. $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
  547. $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
  548. $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
  549. $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
  550. if ($nbsent) {
  551. $action = ''; // Do not show form post if there was at least one successfull sent
  552. //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
  553. setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
  554. setEventMessages($resaction, null, 'mesgs');
  555. } else {
  556. //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
  557. setEventMessages($resaction, null, 'warnings');
  558. }
  559. $action = 'list';
  560. $massaction = '';
  561. }
  562. }
  563. // TODO Move this action into commande/list.php if called only by this page.
  564. if ($massaction == 'confirm_createbills') { // Create bills from orders.
  565. $orders = GETPOST('toselect', 'array');
  566. $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
  567. $validate_invoices = GETPOST('validate_invoices', 'int');
  568. $errors = array();
  569. $TFact = array();
  570. $TFactThird = array();
  571. $nb_bills_created = 0;
  572. $lastid= 0;
  573. $lastref = '';
  574. $db->begin();
  575. foreach ($orders as $id_order) {
  576. $cmd = new Commande($db);
  577. if ($cmd->fetch($id_order) <= 0) {
  578. continue;
  579. }
  580. $cmd->fetch_thirdparty();
  581. $objecttmp = new Facture($db);
  582. if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) {
  583. // If option "one bill per third" is set, and an invoice for this thirdparty was already created, we re-use it.
  584. $objecttmp = $TFactThird[$cmd->socid];
  585. } else {
  586. // If we want one invoice per order or if there is no first invoice yet for this thirdparty.
  587. $objecttmp->socid = $cmd->socid;
  588. $objecttmp->type = $objecttmp::TYPE_STANDARD;
  589. $objecttmp->cond_reglement_id = !empty($cmd->cond_reglement_id) ? $cmd->cond_reglement_id : $cmd->thirdparty->cond_reglement_id;
  590. $objecttmp->mode_reglement_id = !empty($cmd->mode_reglement_id) ? $cmd->mode_reglement_id : $cmd->thirdparty->mode_reglement_id;
  591. $objecttmp->fk_project = $cmd->fk_project;
  592. $objecttmp->multicurrency_code = $cmd->multicurrency_code;
  593. if (empty($createbills_onebythird)) {
  594. $objecttmp->ref_client = $cmd->ref_client;
  595. }
  596. $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  597. if (empty($datefacture)) {
  598. $datefacture = dol_now();
  599. }
  600. $objecttmp->date = $datefacture;
  601. $objecttmp->origin = 'commande';
  602. $objecttmp->origin_id = $id_order;
  603. $objecttmp->array_options = $cmd->array_options; // Copy extrafields
  604. $res = $objecttmp->create($user);
  605. if ($res > 0) {
  606. $nb_bills_created++;
  607. $lastref = $objecttmp->ref;
  608. $lastid = $objecttmp->id;
  609. $TFactThird[$cmd->socid] = $objecttmp;
  610. } else {
  611. $langs->load("errors");
  612. $errors[] = $cmd->ref.' : '.$langs->trans($objecttmp->error);
  613. $error++;
  614. }
  615. }
  616. if ($objecttmp->id > 0) {
  617. $res = $objecttmp->add_object_linked($objecttmp->origin, $id_order);
  618. if ($res == 0) {
  619. $errors[] = $objecttmp->error;
  620. $error++;
  621. }
  622. if (!$error) {
  623. $lines = $cmd->lines;
  624. if (empty($lines) && method_exists($cmd, 'fetch_lines')) {
  625. $cmd->fetch_lines();
  626. $lines = $cmd->lines;
  627. }
  628. $fk_parent_line = 0;
  629. $num = count($lines);
  630. for ($i = 0; $i < $num; $i++) {
  631. $desc = ($lines[$i]->desc ? $lines[$i]->desc : '');
  632. // If we build one invoice for several orders, we must put the ref of order on the invoice line
  633. if (!empty($createbills_onebythird)) {
  634. $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day'));
  635. }
  636. if ($lines[$i]->subprice < 0) {
  637. // Negative line, we create a discount line
  638. $discount = new DiscountAbsolute($db);
  639. $discount->fk_soc = $objecttmp->socid;
  640. $discount->amount_ht = abs($lines[$i]->total_ht);
  641. $discount->amount_tva = abs($lines[$i]->total_tva);
  642. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  643. $discount->tva_tx = $lines[$i]->tva_tx;
  644. $discount->fk_user = $user->id;
  645. $discount->description = $desc;
  646. $discountid = $discount->create($user);
  647. if ($discountid > 0) {
  648. $result = $objecttmp->insert_discount($discountid);
  649. //$result=$discount->link_to_invoice($lineid,$id);
  650. } else {
  651. setEventMessages($discount->error, $discount->errors, 'errors');
  652. $error++;
  653. break;
  654. }
  655. } else {
  656. // Positive line
  657. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  658. // Date start
  659. $date_start = false;
  660. if ($lines[$i]->date_debut_prevue) {
  661. $date_start = $lines[$i]->date_debut_prevue;
  662. }
  663. if ($lines[$i]->date_debut_reel) {
  664. $date_start = $lines[$i]->date_debut_reel;
  665. }
  666. if ($lines[$i]->date_start) {
  667. $date_start = $lines[$i]->date_start;
  668. }
  669. //Date end
  670. $date_end = false;
  671. if ($lines[$i]->date_fin_prevue) {
  672. $date_end = $lines[$i]->date_fin_prevue;
  673. }
  674. if ($lines[$i]->date_fin_reel) {
  675. $date_end = $lines[$i]->date_fin_reel;
  676. }
  677. if ($lines[$i]->date_end) {
  678. $date_end = $lines[$i]->date_end;
  679. }
  680. // Reset fk_parent_line for no child products and special product
  681. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  682. $fk_parent_line = 0;
  683. }
  684. // Extrafields
  685. if (method_exists($lines[$i], 'fetch_optionals')) {
  686. $lines[$i]->fetch_optionals();
  687. $array_options = $lines[$i]->array_options;
  688. }
  689. $objecttmp->context['createfromclone'];
  690. $result = $objecttmp->addline(
  691. $desc,
  692. $lines[$i]->subprice,
  693. $lines[$i]->qty,
  694. $lines[$i]->tva_tx,
  695. $lines[$i]->localtax1_tx,
  696. $lines[$i]->localtax2_tx,
  697. $lines[$i]->fk_product,
  698. $lines[$i]->remise_percent,
  699. $date_start,
  700. $date_end,
  701. 0,
  702. $lines[$i]->info_bits,
  703. $lines[$i]->fk_remise_except,
  704. 'HT',
  705. 0,
  706. $product_type,
  707. $lines[$i]->rang,
  708. $lines[$i]->special_code,
  709. $objecttmp->origin,
  710. $lines[$i]->rowid,
  711. $fk_parent_line,
  712. $lines[$i]->fk_fournprice,
  713. $lines[$i]->pa_ht,
  714. $lines[$i]->label,
  715. $array_options,
  716. 100,
  717. 0,
  718. $lines[$i]->fk_unit
  719. );
  720. if ($result > 0) {
  721. $lineid = $result;
  722. } else {
  723. $lineid = 0;
  724. $error++;
  725. break;
  726. }
  727. // Defined the new fk_parent_line
  728. if ($result > 0 && $lines[$i]->product_type == 9) {
  729. $fk_parent_line = $result;
  730. }
  731. }
  732. }
  733. }
  734. }
  735. //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module.
  736. if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) {
  737. $TFactThird[$cmd->socid] = $objecttmp;
  738. } else {
  739. $TFact[$objecttmp->id] = $objecttmp;
  740. }
  741. }
  742. // Build doc with all invoices
  743. $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
  744. $toselect = array();
  745. if (!$error && $validate_invoices) {
  746. $massaction = $action = 'builddoc';
  747. foreach ($TAllFact as &$objecttmp) {
  748. $result = $objecttmp->validate($user);
  749. if ($result <= 0) {
  750. $error++;
  751. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  752. break;
  753. }
  754. $id = $objecttmp->id; // For builddoc action
  755. // Builddoc
  756. $donotredirect = 1;
  757. $upload_dir = $conf->facture->dir_output;
  758. $permissiontoadd = $user->rights->facture->creer;
  759. // Call action to build doc
  760. $savobject = $object;
  761. $object = $objecttmp;
  762. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  763. $object = $savobject;
  764. }
  765. $massaction = $action = 'confirm_createbills';
  766. }
  767. if (!$error) {
  768. $db->commit();
  769. if ($nb_bills_created == 1) {
  770. $texttoshow = $langs->trans('BillXCreated', '{s1}');
  771. $texttoshow = str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?id='.urlencode($lastid).'">'.$lastref.'</a>', $texttoshow);
  772. setEventMessages($texttoshow, null, 'mesgs');
  773. } else {
  774. setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
  775. }
  776. // Make a redirect to avoid to bill twice if we make a refresh or back
  777. $param = '';
  778. if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
  779. $param .= '&contextpage='.urlencode($contextpage);
  780. }
  781. if ($limit > 0 && $limit != $conf->liste_limit) {
  782. $param .= '&limit='.urlencode($limit);
  783. }
  784. if ($sall) {
  785. $param .= '&sall='.urlencode($sall);
  786. }
  787. if ($socid > 0) {
  788. $param .= '&socid='.urlencode($socid);
  789. }
  790. if ($search_status != '') {
  791. $param .= '&search_status='.urlencode($search_status);
  792. }
  793. if ($search_orderday) {
  794. $param .= '&search_orderday='.urlencode($search_orderday);
  795. }
  796. if ($search_ordermonth) {
  797. $param .= '&search_ordermonth='.urlencode($search_ordermonth);
  798. }
  799. if ($search_orderyear) {
  800. $param .= '&search_orderyear='.urlencode($search_orderyear);
  801. }
  802. if ($search_deliveryday) {
  803. $param .= '&search_deliveryday='.urlencode($search_deliveryday);
  804. }
  805. if ($search_deliverymonth) {
  806. $param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
  807. }
  808. if ($search_deliveryyear) {
  809. $param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
  810. }
  811. if ($search_ref) {
  812. $param .= '&search_ref='.urlencode($search_ref);
  813. }
  814. if ($search_company) {
  815. $param .= '&search_company='.urlencode($search_company);
  816. }
  817. if ($search_ref_customer) {
  818. $param .= '&search_ref_customer='.urlencode($search_ref_customer);
  819. }
  820. if ($search_user > 0) {
  821. $param .= '&search_user='.urlencode($search_user);
  822. }
  823. if ($search_sale > 0) {
  824. $param .= '&search_sale='.urlencode($search_sale);
  825. }
  826. if ($search_total_ht != '') {
  827. $param .= '&search_total_ht='.urlencode($search_total_ht);
  828. }
  829. if ($search_total_vat != '') {
  830. $param .= '&search_total_vat='.urlencode($search_total_vat);
  831. }
  832. if ($search_total_ttc != '') {
  833. $param .= '&search_total_ttc='.urlencode($search_total_ttc);
  834. }
  835. if ($search_project_ref >= 0) {
  836. $param .= "&search_project_ref=".urlencode($search_project_ref);
  837. }
  838. if ($show_files) {
  839. $param .= '&show_files='.urlencode($show_files);
  840. }
  841. if ($optioncss != '') {
  842. $param .= '&optioncss='.urlencode($optioncss);
  843. }
  844. if ($billed != '') {
  845. $param .= '&billed='.urlencode($billed);
  846. }
  847. header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
  848. exit;
  849. } else {
  850. $db->rollback();
  851. $action = 'create';
  852. $_GET["origin"] = $_POST["origin"];
  853. $_GET["originid"] = $_POST["originid"];
  854. setEventMessages("Error", null, 'errors');
  855. $error++;
  856. }
  857. }
  858. if (!$error && $massaction == 'cancelorders') {
  859. $db->begin();
  860. $nbok = 0;
  861. $orders = GETPOST('toselect', 'array');
  862. foreach ($orders as $id_order) {
  863. $cmd = new Commande($db);
  864. if ($cmd->fetch($id_order) <= 0) {
  865. continue;
  866. }
  867. if ($cmd->statut != Commande::STATUS_VALIDATED) {
  868. $langs->load('errors');
  869. setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
  870. $error++;
  871. break;
  872. } else {
  873. // TODO We do not provide warehouse so no stock change here for the moment.
  874. $result = $cmd->cancel();
  875. }
  876. if ($result < 0) {
  877. setEventMessages($cmd->error, $cmd->errors, 'errors');
  878. $error++;
  879. break;
  880. } else {
  881. $nbok++;
  882. }
  883. }
  884. if (!$error) {
  885. if ($nbok > 1) {
  886. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  887. } else {
  888. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  889. }
  890. $db->commit();
  891. } else {
  892. $db->rollback();
  893. }
  894. }
  895. if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
  896. if (empty($diroutputmassaction)) {
  897. dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
  898. exit;
  899. }
  900. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  901. require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
  902. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  903. $objecttmp = new $objectclass($db);
  904. $listofobjectid = array();
  905. $listofobjectthirdparties = array();
  906. $listofobjectref = array();
  907. foreach ($toselect as $toselectid) {
  908. $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
  909. $result = $objecttmp->fetch($toselectid);
  910. if ($result > 0) {
  911. $listofobjectid[$toselectid] = $toselectid;
  912. $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
  913. $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
  914. $listofobjectref[$toselectid] = $objecttmp->ref;
  915. }
  916. }
  917. $arrayofinclusion = array();
  918. foreach ($listofobjectref as $tmppdf) {
  919. $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
  920. }
  921. foreach ($listofobjectref as $tmppdf) {
  922. $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files
  923. }
  924. $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
  925. // build list of files with full path
  926. $files = array();
  927. foreach ($listofobjectref as $basename) {
  928. $basename = dol_sanitizeFileName($basename);
  929. foreach ($listoffiles as $filefound) {
  930. if (strstr($filefound["name"], $basename)) {
  931. $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
  932. break;
  933. }
  934. }
  935. }
  936. // Define output language (Here it is not used because we do only merging existing PDF)
  937. $outputlangs = $langs;
  938. $newlang = '';
  939. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  940. $newlang = GETPOST('lang_id', 'aZ09');
  941. }
  942. //elseif ($conf->global->MAIN_MULTILANGS && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
  943. // $newlang = $objecttmp->thirdparty->default_lang;
  944. //}
  945. if (!empty($newlang)) {
  946. $outputlangs = new Translate("", $conf);
  947. $outputlangs->setDefaultLang($newlang);
  948. }
  949. if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
  950. // Create output dir if not exists
  951. dol_mkdir($diroutputmassaction);
  952. // Defined name of merged file
  953. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  954. $filename = preg_replace('/\s/', '_', $filename);
  955. // Save merged file
  956. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  957. if ($option == 'late') {
  958. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  959. } else {
  960. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  961. }
  962. }
  963. if ($year) {
  964. $filename .= '_'.$year;
  965. }
  966. if ($month) {
  967. $filename .= '_'.$month;
  968. }
  969. if (count($files) > 0) {
  970. $now = dol_now();
  971. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  972. $input_files = '';
  973. foreach ($files as $f) {
  974. $input_files .= ' '.escapeshellarg($f);
  975. }
  976. $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
  977. exec($cmd);
  978. // check if pdftk is installed
  979. if (file_exists($file)) {
  980. if (!empty($conf->global->MAIN_UMASK)) {
  981. @chmod($file, octdec($conf->global->MAIN_UMASK));
  982. }
  983. $langs->load("exports");
  984. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  985. } else {
  986. setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
  987. }
  988. } else {
  989. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  990. }
  991. } else {
  992. // Create empty PDF
  993. $formatarray = pdf_getFormat();
  994. $page_largeur = $formatarray['width'];
  995. $page_hauteur = $formatarray['height'];
  996. $format = array($page_largeur, $page_hauteur);
  997. $pdf = pdf_getInstance($format);
  998. if (class_exists('TCPDF')) {
  999. $pdf->setPrintHeader(false);
  1000. $pdf->setPrintFooter(false);
  1001. }
  1002. $pdf->SetFont(pdf_getPDFFont($outputlangs));
  1003. if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
  1004. $pdf->SetCompression(false);
  1005. }
  1006. // Add all others
  1007. foreach ($files as $file) {
  1008. // Charge un document PDF depuis un fichier.
  1009. $pagecount = $pdf->setSourceFile($file);
  1010. for ($i = 1; $i <= $pagecount; $i++) {
  1011. $tplidx = $pdf->importPage($i);
  1012. $s = $pdf->getTemplatesize($tplidx);
  1013. $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
  1014. $pdf->useTemplate($tplidx);
  1015. }
  1016. }
  1017. // Create output dir if not exists
  1018. dol_mkdir($diroutputmassaction);
  1019. // Defined name of merged file
  1020. $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
  1021. $filename = preg_replace('/\s/', '_', $filename);
  1022. // Save merged file
  1023. if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
  1024. if ($option == 'late') {
  1025. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
  1026. } else {
  1027. $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
  1028. }
  1029. }
  1030. if ($year) {
  1031. $filename .= '_'.$year;
  1032. }
  1033. if ($month) {
  1034. $filename .= '_'.$month;
  1035. }
  1036. if ($pagecount) {
  1037. $now = dol_now();
  1038. $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
  1039. $pdf->Output($file, 'F');
  1040. if (!empty($conf->global->MAIN_UMASK)) {
  1041. @chmod($file, octdec($conf->global->MAIN_UMASK));
  1042. }
  1043. $langs->load("exports");
  1044. setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
  1045. } else {
  1046. setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
  1047. }
  1048. }
  1049. }
  1050. // Remove a file from massaction area
  1051. if ($action == 'remove_file') {
  1052. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1053. $langs->load("other");
  1054. $upload_dir = $diroutputmassaction;
  1055. $file = $upload_dir.'/'.GETPOST('file');
  1056. $ret = dol_delete_file($file);
  1057. if ($ret) {
  1058. setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
  1059. } else {
  1060. setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
  1061. }
  1062. $action = '';
  1063. }
  1064. // Validate records
  1065. if (!$error && $massaction == 'validate' && $permissiontoadd) {
  1066. $objecttmp = new $objectclass($db);
  1067. if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  1068. $langs->load("errors");
  1069. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  1070. $error++;
  1071. }
  1072. if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  1073. $langs->load("errors");
  1074. setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
  1075. $error++;
  1076. }
  1077. if (!$error) {
  1078. $db->begin();
  1079. $nbok = 0;
  1080. foreach ($toselect as $toselectid) {
  1081. $result = $objecttmp->fetch($toselectid);
  1082. if ($result > 0) {
  1083. $result = $objecttmp->validate($user);
  1084. if ($result == 0) {
  1085. $langs->load("errors");
  1086. setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
  1087. $error++;
  1088. break;
  1089. } elseif ($result < 0) {
  1090. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1091. $error++;
  1092. break;
  1093. } else {
  1094. // validate() rename pdf but do not regenerate
  1095. // Define output language
  1096. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1097. $outputlangs = $langs;
  1098. $newlang = '';
  1099. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1100. $newlang = GETPOST('lang_id', 'aZ09');
  1101. }
  1102. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1103. $newlang = $objecttmp->thirdparty->default_lang;
  1104. }
  1105. if (!empty($newlang)) {
  1106. $outputlangs = new Translate("", $conf);
  1107. $outputlangs->setDefaultLang($newlang);
  1108. $outputlangs->load('products');
  1109. }
  1110. $model = $objecttmp->model_pdf;
  1111. $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
  1112. // To be sure vars is defined
  1113. $hidedetails = !empty($hidedetails) ? $hidedetails : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  1114. $hidedesc = !empty($hidedesc) ? $hidedesc : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  1115. $hideref = !empty($hideref) ? $hideref : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  1116. $moreparams = !empty($moreparams) ? $moreparams : null;
  1117. $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1118. if ($result < 0) {
  1119. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1120. }
  1121. }
  1122. $nbok++;
  1123. }
  1124. } else {
  1125. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1126. $error++;
  1127. break;
  1128. }
  1129. }
  1130. if (!$error) {
  1131. if ($nbok > 1) {
  1132. setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
  1133. } else {
  1134. setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
  1135. }
  1136. $db->commit();
  1137. } else {
  1138. $db->rollback();
  1139. }
  1140. //var_dump($listofobjectthirdparties);exit;
  1141. }
  1142. }
  1143. //var_dump($_POST);var_dump($massaction);exit;
  1144. // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
  1145. if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
  1146. $db->begin();
  1147. $objecttmp = new $objectclass($db);
  1148. $nbok = 0;
  1149. $TMsg = array();
  1150. foreach ($toselect as $toselectid) {
  1151. $result = $objecttmp->fetch($toselectid);
  1152. if ($result > 0) {
  1153. // Refuse deletion for some objects/status
  1154. if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
  1155. $langs->load("errors");
  1156. $nbignored++;
  1157. $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
  1158. continue;
  1159. }
  1160. if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
  1161. $langs->load("errors");
  1162. $nbignored++;
  1163. $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
  1164. continue;
  1165. }
  1166. if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
  1167. $nbignored++;
  1168. $resaction .= '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
  1169. continue;
  1170. }
  1171. if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
  1172. $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
  1173. $res = $db->query($sql);
  1174. if (!$res) {
  1175. setEventMessage('ErrorRecordParentingNotModified', 'errors');
  1176. $error++;
  1177. }
  1178. }
  1179. if (in_array($objecttmp->element, array('societe', 'member'))) {
  1180. $result = $objecttmp->delete($objecttmp->id, $user, 1);
  1181. } else {
  1182. $result = $objecttmp->delete($user);
  1183. }
  1184. if (empty($result)) { // if delete returns 0, there is at least one object linked
  1185. $TMsg = array_merge($objecttmp->errors, $TMsg);
  1186. } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
  1187. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1188. $error++;
  1189. break;
  1190. } else {
  1191. $nbok++;
  1192. }
  1193. } else {
  1194. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1195. $error++;
  1196. break;
  1197. }
  1198. }
  1199. if (empty($error)) {
  1200. // Message for elements well deleted
  1201. if ($nbok > 1) {
  1202. setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
  1203. } elseif ($nbok > 0) {
  1204. setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
  1205. } else {
  1206. setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
  1207. }
  1208. // Message for elements which can't be deleted
  1209. if (!empty($TMsg)) {
  1210. sort($TMsg);
  1211. setEventMessages('', array_unique($TMsg), 'warnings');
  1212. }
  1213. $db->commit();
  1214. } else {
  1215. $db->rollback();
  1216. }
  1217. //var_dump($listofobjectthirdparties);exit;
  1218. }
  1219. // Generate document foreach object according to model linked to object
  1220. // @todo : propose model selection
  1221. if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
  1222. $db->begin();
  1223. $objecttmp = new $objectclass($db);
  1224. $nbok = 0;
  1225. foreach ($toselect as $toselectid) {
  1226. $result = $objecttmp->fetch($toselectid);
  1227. if ($result > 0) {
  1228. $outputlangs = $langs;
  1229. $newlang = '';
  1230. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1231. $newlang = GETPOST('lang_id', 'aZ09');
  1232. }
  1233. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
  1234. $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
  1235. }
  1236. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) {
  1237. $newlang = $objecttmp->default_lang; // for thirdparty
  1238. }
  1239. if (!empty($newlang)) {
  1240. $outputlangs = new Translate("", $conf);
  1241. $outputlangs->setDefaultLang($newlang);
  1242. }
  1243. // To be sure vars is defined
  1244. if (empty($hidedetails)) {
  1245. $hidedetails = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0);
  1246. }
  1247. if (empty($hidedesc)) {
  1248. $hidedesc = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0);
  1249. }
  1250. if (empty($hideref)) {
  1251. $hideref = (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0);
  1252. }
  1253. if (empty($moreparams)) {
  1254. $moreparams = null;
  1255. }
  1256. $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1257. if ($result <= 0) {
  1258. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1259. $error++;
  1260. break;
  1261. } else {
  1262. $nbok++;
  1263. }
  1264. } else {
  1265. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1266. $error++;
  1267. break;
  1268. }
  1269. }
  1270. if (!$error) {
  1271. if ($nbok > 1) {
  1272. setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
  1273. } else {
  1274. setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
  1275. }
  1276. $db->commit();
  1277. } else {
  1278. $db->rollback();
  1279. }
  1280. }
  1281. if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
  1282. $db->begin();
  1283. $affecttag_type=GETPOST('affecttag_type', 'alpha');
  1284. if (!empty($affecttag_type)) {
  1285. $affecttag_type_array=explode(',', $affecttag_type);
  1286. } else {
  1287. setEventMessage('CategTypeNotFound', 'errors');
  1288. }
  1289. if (!empty($affecttag_type_array)) {
  1290. //check if tag type submited exists into Tag Map categorie class
  1291. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1292. $categ = new Categorie($db);
  1293. $to_affecttag_type_array=array();
  1294. $categ_type_array=$categ->getMapList();
  1295. foreach ($categ_type_array as $categdef) {
  1296. if (in_array($categdef['code'], $affecttag_type_array)) {
  1297. $to_affecttag_type_array[] = $categdef['code'];
  1298. }
  1299. }
  1300. //For each valid categ type set common categ
  1301. $nbok = 0;
  1302. if (!empty($to_affecttag_type_array)) {
  1303. foreach ($to_affecttag_type_array as $categ_type) {
  1304. $contcats = GETPOST('contcats_' . $categ_type, 'array');
  1305. //var_dump($toselect);exit;
  1306. foreach ($toselect as $toselectid) {
  1307. $result = $object->fetch($toselectid);
  1308. //var_dump($contcats);exit;
  1309. if ($result > 0) {
  1310. $result = $object->setCategoriesCommon($contcats, $categ_type, false);
  1311. if ($result > 0) {
  1312. $nbok++;
  1313. } else {
  1314. setEventMessages($object->error, $object->errors, 'errors');
  1315. }
  1316. } else {
  1317. setEventMessages($object->error, $object->errors, 'errors');
  1318. $error++;
  1319. break;
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }
  1325. if (!$error) {
  1326. if ($nbok > 1) {
  1327. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1328. } else {
  1329. setEventMessages($langs->trans("RecordsModified", $nbok), null);
  1330. }
  1331. $db->commit();
  1332. $toselect=array();
  1333. } else {
  1334. $db->rollback();
  1335. }
  1336. }
  1337. if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
  1338. $db->begin();
  1339. $objecttmp = new $objectclass($db);
  1340. $nbok = 0;
  1341. foreach ($toselect as $toselectid) {
  1342. $result = $objecttmp->fetch($toselectid);
  1343. if ($result>0) {
  1344. if (in_array($objecttmp->element, array('societe'))) {
  1345. $result =$objecttmp->setStatut(1);
  1346. }
  1347. if ($result <= 0) {
  1348. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1349. $error++;
  1350. break;
  1351. } else {
  1352. $nbok++;
  1353. }
  1354. } else {
  1355. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1356. $error++;
  1357. break;
  1358. }
  1359. }
  1360. if (!$error) {
  1361. if ($nbok > 1) {
  1362. setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
  1363. } else {
  1364. setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
  1365. }
  1366. $db->commit();
  1367. } else {
  1368. $db->rollback();
  1369. }
  1370. }
  1371. if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
  1372. $db->begin();
  1373. $objecttmp = new $objectclass($db);
  1374. $nbok = 0;
  1375. foreach ($toselect as $toselectid) {
  1376. $result = $objecttmp->fetch($toselectid);
  1377. if ($result>0) {
  1378. if (in_array($objecttmp->element, array('societe'))) {
  1379. $result =$objecttmp->setStatut(0);
  1380. }
  1381. if ($result <= 0) {
  1382. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1383. $error++;
  1384. break;
  1385. } else {
  1386. $nbok++;
  1387. }
  1388. } else {
  1389. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1390. $error++;
  1391. break;
  1392. }
  1393. }
  1394. if (!$error) {
  1395. if ($nbok > 1) {
  1396. setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
  1397. } else {
  1398. setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
  1399. }
  1400. $db->commit();
  1401. } else {
  1402. $db->rollback();
  1403. }
  1404. }
  1405. // Approve for leave only
  1406. if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
  1407. $db->begin();
  1408. $objecttmp = new $objectclass($db);
  1409. $nbok = 0;
  1410. foreach ($toselect as $toselectid) {
  1411. $result = $objecttmp->fetch($toselectid);
  1412. if ($result > 0) {
  1413. if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
  1414. setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
  1415. continue;
  1416. }
  1417. if ($user->id == $objecttmp->fk_validator) {
  1418. $objecttmp->oldcopy = dol_clone($objecttmp);
  1419. $objecttmp->date_valid = dol_now();
  1420. $objecttmp->fk_user_valid = $user->id;
  1421. $objecttmp->statut = Holiday::STATUS_APPROVED;
  1422. $verif = $objecttmp->approve($user);
  1423. if ($verif <= 0) {
  1424. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1425. $error++;
  1426. }
  1427. // If no SQL error, we redirect to the request form
  1428. if (!$error) {
  1429. // Calculcate number of days consummed
  1430. $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
  1431. $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
  1432. $newSolde = ($soldeActuel - $nbopenedday);
  1433. // The modification is added to the LOG
  1434. $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
  1435. if ($result < 0) {
  1436. $error++;
  1437. setEventMessages(null, $objecttmp->errors, 'errors');
  1438. }
  1439. // Update balance
  1440. $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
  1441. if ($result < 0) {
  1442. $error++;
  1443. setEventMessages(null, $objecttmp->errors, 'errors');
  1444. }
  1445. }
  1446. if (!$error) {
  1447. // To
  1448. $destinataire = new User($db);
  1449. $destinataire->fetch($objecttmp->fk_user);
  1450. $emailTo = $destinataire->email;
  1451. if (!$emailTo) {
  1452. dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
  1453. } else {
  1454. // From
  1455. $expediteur = new User($db);
  1456. $expediteur->fetch($objecttmp->fk_validator);
  1457. //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
  1458. $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
  1459. // Subject
  1460. $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
  1461. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  1462. $societeName = $conf->global->MAIN_APPLICATION_TITLE;
  1463. }
  1464. $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
  1465. // Content
  1466. $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
  1467. $message .= "\n";
  1468. $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
  1469. $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
  1470. $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
  1471. $message .= "\n";
  1472. $trackid = 'leav'.$objecttmp->id;
  1473. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1474. $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
  1475. // Sending email
  1476. $result = $mail->sendfile();
  1477. if (!$result) {
  1478. setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
  1479. $action = '';
  1480. }
  1481. }
  1482. }
  1483. } else {
  1484. $langs->load("errors");
  1485. setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
  1486. }
  1487. } else {
  1488. setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
  1489. $error++;
  1490. break;
  1491. }
  1492. }
  1493. if (!$error) {
  1494. if ($nbok > 1) {
  1495. setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
  1496. } elseif ($nbok == 1) {
  1497. setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
  1498. }
  1499. $db->commit();
  1500. } else {
  1501. $db->rollback();
  1502. }
  1503. }
  1504. $parameters['toselect'] = $toselect;
  1505. $parameters['uploaddir'] = $uploaddir;
  1506. $parameters['massaction'] = $massaction;
  1507. $parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
  1508. $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1509. if ($reshook < 0) {
  1510. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1511. }