actions_massactions.inc.php 64 KB

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