emailcollector.class.php 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file htdocs/emailcollector/class/emailcollector.class.php
  19. * \ingroup emailcollector
  20. * \brief This file is a CRUD class file for EmailCollector (Create/Read/Update/Delete)
  21. */
  22. // Put here all includes required by your class file
  23. include_once DOL_DOCUMENT_ROOT .'/emailcollector/lib/emailcollector.lib.php';
  24. require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
  25. require_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
  26. require_once DOL_DOCUMENT_ROOT .'/comm/propal/class/propal.class.php'; // Customer Proposal
  27. require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php'; // Sale Order
  28. require_once DOL_DOCUMENT_ROOT .'/compta/facture/class/facture.class.php'; // Customer Invoice
  29. require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; // Contact / Address
  30. require_once DOL_DOCUMENT_ROOT .'/expedition/class/expedition.class.php'; // Shipping / Delivery
  31. require_once DOL_DOCUMENT_ROOT .'/fourn/class/fournisseur.commande.class.php'; // Purchase Order
  32. require_once DOL_DOCUMENT_ROOT .'/fourn/class/fournisseur.facture.class.php'; // Purchase Invoice
  33. require_once DOL_DOCUMENT_ROOT .'/projet/class/project.class.php'; // Project
  34. require_once DOL_DOCUMENT_ROOT .'/reception/class/reception.class.php'; // Reception
  35. require_once DOL_DOCUMENT_ROOT .'/recruitment/class/recruitmentcandidature.class.php'; // Recruiting
  36. require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; // Third-Party
  37. require_once DOL_DOCUMENT_ROOT .'/supplier_proposal/class/supplier_proposal.class.php'; // Supplier Proposal
  38. require_once DOL_DOCUMENT_ROOT .'/ticket/class/ticket.class.php'; // Ticket
  39. //require_once DOL_DOCUMENT_ROOT .'/expensereport/class/expensereport.class.php'; // Expense Report
  40. //require_once DOL_DOCUMENT_ROOT .'/holiday/class/holiday.class.php'; // Holidays (leave request)
  41. use Webklex\PHPIMAP\ClientManager;
  42. use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
  43. use Webklex\PHPIMAP\Exceptions\InvalidWhereQueryCriteriaException;
  44. use Webklex\PHPIMAP\Exceptions\GetMessagesFailedException;
  45. use OAuth\Common\Storage\DoliStorage;
  46. use OAuth\Common\Consumer\Credentials;
  47. /**
  48. * Class for EmailCollector
  49. */
  50. class EmailCollector extends CommonObject
  51. {
  52. /**
  53. * @var string ID to identify managed object
  54. */
  55. public $element = 'emailcollector';
  56. /**
  57. * @var string Name of table without prefix where object is stored
  58. */
  59. public $table_element = 'emailcollector_emailcollector';
  60. /**
  61. * @var int Does emailcollector support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  62. */
  63. public $ismultientitymanaged = 1;
  64. /**
  65. * @var int Does emailcollector support extrafields ? 0=No, 1=Yes
  66. */
  67. public $isextrafieldmanaged = 0;
  68. /**
  69. * @var string String with name of icon for emailcollector. Must be the part after the 'object_' into object_emailcollector.png
  70. */
  71. public $picto = 'email';
  72. /**
  73. * @var string Field with ID of parent key if this field has a parent
  74. */
  75. public $fk_element = 'fk_emailcollector';
  76. /**
  77. * @var array List of child tables. To test if we can delete object.
  78. */
  79. protected $childtables = array();
  80. /**
  81. * @var array List of child tables. To know object to delete on cascade.
  82. */
  83. protected $childtablesoncascade = array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction');
  84. /**
  85. * 'type' if the field format.
  86. * 'label' the translation key.
  87. * 'enabled' is a condition when the field must be managed.
  88. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing)
  89. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  90. * 'default' is a default value for creation (can still be replaced by the global setup of default values)
  91. * 'index' if we want an index in database.
  92. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  93. * 'position' is the sort order of field.
  94. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  95. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  96. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  97. * 'help' is a string visible as a tooltip on field
  98. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  99. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  100. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  101. */
  102. // BEGIN MODULEBUILDER PROPERTIES
  103. /**
  104. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  105. */
  106. public $fields = array(
  107. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1),
  108. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
  109. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'help'=>'Example: MyCollector1', 'csslist'=>'tdoverflowmax200'),
  110. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>'Example: My Email collector', 'csslist'=>'tdoverflowmax150'),
  111. 'description' => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>60, 'notnull'=>-1, 'cssview'=>'small', 'csslist'=>'small tdoverflowmax200'),
  112. 'host' => array('type'=>'varchar(255)', 'label'=>'EMailHost', 'visible'=>1, 'enabled'=>1, 'position'=>90, 'notnull'=>1, 'searchall'=>1, 'comment'=>"IMAP server", 'help'=>'Example: imap.gmail.com', 'csslist'=>'tdoverflowmax125'),
  113. 'port' => array('type'=>'varchar(10)', 'label'=>'EMailHostPort', 'visible'=>1, 'enabled'=>1, 'position'=>91, 'notnull'=>1, 'searchall'=>0, 'comment'=>"IMAP server port", 'help'=>'Example: 993', 'csslist'=>'tdoverflowmax50', 'default'=>'993'),
  114. 'hostcharset' => array('type'=>'varchar(16)', 'label'=>'HostCharset', 'visible'=>-1, 'enabled'=>1, 'position'=>92, 'notnull'=>0, 'searchall'=>0, 'comment'=>"IMAP server charset", 'help'=>'Example: "UTF-8" (May be "US-ASCII" with some Office365)', 'default'=>'UTF-8'),
  115. 'imap_encryption' => array('type'=>'varchar(16)', 'label'=>'ImapEncryption', 'visible'=>-1, 'enabled'=>1, 'position'=>93, 'searchall'=>0, 'comment'=>"IMAP encryption", 'help'=>'ImapEncryptionHelp', 'arrayofkeyval'=> array('ssl'=>'SSL', 'tls' => 'TLS', 'notls' => 'NOTLS'), 'default'=>'ssl'),
  116. 'norsh' => array('type'=>'integer', 'label'=>'NoRSH', 'visible'=>-1, 'enabled'=>"!getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position'=>94, 'searchall'=>0, 'help'=>'NoRSHHelp', 'arrayofkeyval'=> array(0 =>'No', 1 => 'Yes'), 'default'=> 0),
  117. 'acces_type' => array('type'=>'integer', 'label'=>'accessType', 'visible'=>-1, 'enabled'=>"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position'=>101, 'notnull'=>1, 'index'=>1, 'comment'=>"IMAP login type", 'arrayofkeyval'=>array('0'=>'loginPassword', '1'=>'oauthToken'), 'default'=>'0', 'help'=>''),
  118. 'login' => array('type'=>'varchar(128)', 'label'=>'Login', 'visible'=>-1, 'enabled'=>1, 'position'=>102, 'notnull'=>-1, 'index'=>1, 'comment'=>"IMAP login", 'help'=>'Example: myaccount@gmail.com'),
  119. 'password' => array('type'=>'password', 'label'=>'Password', 'visible'=>-1, 'enabled'=>"1", 'position'=>103, 'notnull'=>-1, 'comment'=>"IMAP password", 'help'=>'WithGMailYouCanCreateADedicatedPassword'),
  120. 'oauth_service' => array('type'=>'varchar(128)', 'label'=>'oauthService', 'visible'=>-1, 'enabled'=>"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position'=>104, 'notnull'=>0, 'index'=>1, 'comment'=>"IMAP login oauthService", 'arrayofkeyval'=>array(), 'help'=>'TokenMustHaveBeenCreated'),
  121. 'source_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxSourceDirectory', 'visible'=>-1, 'enabled'=>1, 'position'=>104, 'notnull'=>1, 'default' => 'Inbox', 'help'=>'Example: INBOX'),
  122. 'target_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxTargetDirectory', 'visible'=>1, 'enabled'=>1, 'position'=>110, 'notnull'=>0, 'help'=>"EmailCollectorTargetDir"),
  123. 'maxemailpercollect' => array('type'=>'integer', 'label'=>'MaxEmailCollectPerCollect', 'visible'=>-1, 'enabled'=>1, 'position'=>111, 'default'=>100),
  124. 'datelastresult' => array('type'=>'datetime', 'label'=>'DateLastCollectResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>121, 'notnull'=>-1, 'csslist'=>'nowraponall'),
  125. 'codelastresult' => array('type'=>'varchar(16)', 'label'=>'CodeLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>122, 'notnull'=>-1,),
  126. 'lastresult' => array('type'=>'varchar(255)', 'label'=>'LastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>123, 'notnull'=>-1, 'cssview'=>'small', 'csslist'=>'small tdoverflowmax200'),
  127. 'datelastok' => array('type'=>'datetime', 'label'=>'DateLastcollectResultOk', 'visible'=>1, 'enabled'=>'$action != "create"', 'position'=>125, 'notnull'=>-1, 'csslist'=>'nowraponall'),
  128. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'visible'=>0, 'enabled'=>1, 'position'=>61, 'notnull'=>-1,),
  129. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'visible'=>0, 'enabled'=>1, 'position'=>62, 'notnull'=>-1,),
  130. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
  131. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1,),
  132. //'date_validation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
  133. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>510, 'notnull'=>1,),
  134. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>511, 'notnull'=>-1,),
  135. //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
  136. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1,),
  137. 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Inactive', '1'=>'Active'))
  138. );
  139. /**
  140. * @var int ID
  141. */
  142. public $rowid;
  143. /**
  144. * @var string Ref
  145. */
  146. public $ref;
  147. /**
  148. * @var int Entity
  149. */
  150. public $entity;
  151. /**
  152. * @var string label
  153. */
  154. public $label;
  155. /**
  156. * @var int Status
  157. */
  158. public $status;
  159. /**
  160. * @var integer|string date_creation
  161. */
  162. public $date_creation;
  163. /**
  164. * @var int timestamp
  165. */
  166. public $tms;
  167. /**
  168. * @var int ID
  169. */
  170. public $fk_user_creat;
  171. /**
  172. * @var int ID
  173. */
  174. public $fk_user_modif;
  175. /**
  176. * @var string import key
  177. */
  178. public $import_key;
  179. public $host;
  180. public $port;
  181. public $hostcharset;
  182. public $login;
  183. public $password;
  184. public $acces_type;
  185. public $oauth_service;
  186. public $imap_encryption;
  187. public $norsh;
  188. public $source_directory;
  189. public $target_directory;
  190. public $maxemailpercollect;
  191. /**
  192. * @var integer|string $datelastresult
  193. */
  194. public $datelastresult;
  195. public $codelastresult;
  196. public $lastresult;
  197. public $datelastok;
  198. // END MODULEBUILDER PROPERTIES
  199. public $filters;
  200. public $actions;
  201. public $debuginfo;
  202. const STATUS_DISABLED = 0;
  203. const STATUS_ENABLED = 1;
  204. /**
  205. * Constructor
  206. *
  207. * @param DoliDb $db Database handler
  208. */
  209. public function __construct(DoliDB $db)
  210. {
  211. global $conf, $langs;
  212. $this->db = $db;
  213. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  214. $this->fields['rowid']['visible'] = 0;
  215. }
  216. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  217. $this->fields['entity']['enabled'] = 0;
  218. }
  219. // List of oauth services
  220. $oauthservices = array();
  221. foreach ($conf->global as $key => $val) {
  222. if (!empty($val) && preg_match('/^OAUTH_.*_ID$/', $key)) {
  223. $key = preg_replace('/^OAUTH_/', '', $key);
  224. $key = preg_replace('/_ID$/', '', $key);
  225. if (preg_match('/^.*-/', $key)) {
  226. $name = preg_replace('/^.*-/', '', $key);
  227. } else {
  228. $name = $langs->trans("NoName");
  229. }
  230. $provider = preg_replace('/-.*$/', '', $key);
  231. $provider = ucfirst(strtolower($provider));
  232. $oauthservices[$key] = $name." (".$provider.")";
  233. }
  234. }
  235. $this->fields['oauth_service']['arrayofkeyval'] = $oauthservices;
  236. // Unset fields that are disabled
  237. foreach ($this->fields as $key => $val) {
  238. if (isset($val['enabled']) && empty($val['enabled'])) {
  239. unset($this->fields[$key]);
  240. }
  241. }
  242. // Translate some data of arrayofkeyval
  243. foreach ($this->fields as $key => $val) {
  244. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  245. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  246. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  247. }
  248. }
  249. }
  250. }
  251. /**
  252. * Create object into database
  253. *
  254. * @param User $user User that creates
  255. * @param bool $notrigger false=launch triggers after, true=disable triggers
  256. * @return int <0 if KO, Id of created object if OK
  257. */
  258. public function create(User $user, $notrigger = false)
  259. {
  260. global $langs;
  261. // Check parameters
  262. if ($this->host && preg_match('/^http:/i', trim($this->host))) {
  263. $langs->load("errors");
  264. $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host);
  265. return -1;
  266. }
  267. include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
  268. $this->password = dolEncrypt($this->password);
  269. $id = $this->createCommon($user, $notrigger);
  270. $this->password = dolDecrypt($this->password);
  271. if (is_array($this->filters) && count($this->filters)) {
  272. $emailcollectorfilter = new EmailCollectorFilter($this->db);
  273. foreach ($this->filters as $filter) {
  274. $emailcollectorfilter->type = $filter['type'];
  275. $emailcollectorfilter->rulevalue = $filter['rulevalue'];
  276. $emailcollectorfilter->fk_emailcollector = $this->id;
  277. $emailcollectorfilter->status = $filter['status'];
  278. $emailcollectorfilter->create($user);
  279. }
  280. }
  281. if (is_array($this->actions) && count($this->actions)) {
  282. $emailcollectoroperation = new EmailCollectorAction($this->db);
  283. foreach ($this->actions as $operation) {
  284. $emailcollectoroperation->type = $operation['type'];
  285. $emailcollectoroperation->actionparam = $operation['actionparam'];
  286. $emailcollectoroperation->fk_emailcollector = $this->id;
  287. $emailcollectoroperation->status = $operation['status'];
  288. $emailcollectoroperation->position = $operation['position'];
  289. $emailcollectoroperation->create($user);
  290. }
  291. }
  292. return $id;
  293. }
  294. /**
  295. * Clone and object into another one
  296. *
  297. * @param User $user User that creates
  298. * @param int $fromid Id of object to clone
  299. * @return mixed New object created, <0 if KO
  300. */
  301. public function createFromClone(User $user, $fromid)
  302. {
  303. global $langs, $extrafields;
  304. $error = 0;
  305. dol_syslog(__METHOD__, LOG_DEBUG);
  306. $object = new self($this->db);
  307. $this->db->begin();
  308. // Load source object
  309. $object->fetchCommon($fromid);
  310. $object->fetchFilters(); // Rules
  311. $object->fetchActions(); // Operations
  312. // Reset some properties
  313. unset($object->id);
  314. unset($object->fk_user_creat);
  315. unset($object->import_key);
  316. unset($object->password);
  317. // Clear fields
  318. $object->ref = "copy_of_".$object->ref;
  319. $object->label = $langs->trans("CopyOf")." ".$object->label;
  320. if (empty($object->host)) {
  321. $object->host = 'imap.example.com';
  322. }
  323. // Clear extrafields that are unique
  324. if (is_array($object->array_options) && count($object->array_options) > 0) {
  325. $extrafields->fetch_name_optionals_label($this->table_element);
  326. foreach ($object->array_options as $key => $option) {
  327. $shortkey = preg_replace('/options_/', '', $key);
  328. if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
  329. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  330. unset($object->array_options[$key]);
  331. }
  332. }
  333. }
  334. // Create clone
  335. $object->context['createfromclone'] = 'createfromclone';
  336. $result = $object->create($user);
  337. if ($result < 0) {
  338. $error++;
  339. $this->error = $object->error;
  340. $this->errors = $object->errors;
  341. }
  342. unset($object->context['createfromclone']);
  343. // End
  344. if (!$error) {
  345. $this->db->commit();
  346. return $object;
  347. } else {
  348. $this->db->rollback();
  349. return -1;
  350. }
  351. }
  352. /**
  353. * Load object in memory from the database
  354. *
  355. * @param int $id Id object
  356. * @param string $ref Ref
  357. * @return int <0 if KO, 0 if not found, >0 if OK
  358. */
  359. public function fetch($id, $ref = null)
  360. {
  361. $result = $this->fetchCommon($id, $ref);
  362. include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
  363. $this->password = dolDecrypt($this->password);
  364. //if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
  365. return $result;
  366. }
  367. /**
  368. * Load object lines in memory from the database
  369. *
  370. * @return int <0 if KO, 0 if not found, >0 if OK
  371. */
  372. /*
  373. public function fetchLines()
  374. {
  375. $this->lines=array();
  376. // Load lines with object EmailCollectorLine
  377. return count($this->lines)?1:0;
  378. }
  379. */
  380. /**
  381. * Fetch all account and load objects into an array
  382. *
  383. * @param User $user User
  384. * @param int $activeOnly filter if active
  385. * @param string $sortfield field for sorting
  386. * @param string $sortorder sorting order
  387. * @param int $limit sort limit
  388. * @param int $page page to start on
  389. * @return array Array with key => EmailCollector object
  390. */
  391. public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0)
  392. {
  393. global $langs;
  394. $obj_ret = array();
  395. $sql = "SELECT s.rowid";
  396. $sql .= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s";
  397. $sql .= ' WHERE s.entity IN ('.getEntity('emailcollector').')';
  398. if ($activeOnly) {
  399. $sql .= " AND s.status = 1";
  400. }
  401. $sql .= $this->db->order($sortfield, $sortorder);
  402. if ($limit) {
  403. if ($page < 0) {
  404. $page = 0;
  405. }
  406. $offset = $limit * $page;
  407. $sql .= $this->db->plimit($limit + 1, $offset);
  408. }
  409. $result = $this->db->query($sql);
  410. if ($result) {
  411. $num = $this->db->num_rows($result);
  412. $i = 0;
  413. while ($i < $num) {
  414. $obj = $this->db->fetch_object($result);
  415. $emailcollector_static = new EmailCollector($this->db);
  416. if ($emailcollector_static->fetch($obj->rowid)) {
  417. $obj_ret[] = $emailcollector_static;
  418. }
  419. $i++;
  420. }
  421. } else {
  422. $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list';
  423. dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
  424. $ret = -1;
  425. }
  426. if (!count($obj_ret)) {
  427. dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
  428. }
  429. return $obj_ret;
  430. }
  431. /**
  432. * Update object into database
  433. *
  434. * @param User $user User that modifies
  435. * @param bool $notrigger false=launch triggers after, true=disable triggers
  436. * @return int <0 if KO, >0 if OK
  437. */
  438. public function update(User $user, $notrigger = false)
  439. {
  440. global $langs;
  441. // Check parameters
  442. if ($this->host && preg_match('/^http:/i', trim($this->host))) {
  443. $langs->load("errors");
  444. $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host);
  445. return -1;
  446. }
  447. include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
  448. $this->password = dolEncrypt($this->password);
  449. $result = $this->updateCommon($user, $notrigger);
  450. $this->password = dolDecrypt($this->password);
  451. return $result;
  452. }
  453. /**
  454. * Delete object in database
  455. *
  456. * @param User $user User that deletes
  457. * @param bool $notrigger false=launch triggers after, true=disable triggers
  458. * @return int <0 if KO, >0 if OK
  459. */
  460. public function delete(User $user, $notrigger = false)
  461. {
  462. return $this->deleteCommon($user, $notrigger, 1);
  463. }
  464. /**
  465. * Return a link to the object card (with optionaly the picto)
  466. *
  467. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  468. * @param string $option On what the link point to ('nolink', ...)
  469. * @param int $notooltip 1=Disable tooltip
  470. * @param string $morecss Add more css on link
  471. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  472. * @return string String with URL
  473. */
  474. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  475. {
  476. global $conf, $langs, $action, $hookmanager;
  477. if (!empty($conf->dol_no_mouse_hover)) {
  478. $notooltip = 1; // Force disable tooltips
  479. }
  480. $result = '';
  481. $label = '<u>'.$langs->trans("EmailCollector").'</u>';
  482. $label .= '<br>';
  483. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  484. $url = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.$this->id;
  485. if ($option != 'nolink') {
  486. // Add param to save lastsearch_values or not
  487. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  488. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  489. $add_save_lastsearch_values = 1;
  490. }
  491. if ($add_save_lastsearch_values) {
  492. $url .= '&save_lastsearch_values=1';
  493. }
  494. }
  495. $linkclose = '';
  496. if (empty($notooltip)) {
  497. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  498. $label = $langs->trans("ShowEmailCollector");
  499. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  500. }
  501. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  502. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  503. } else {
  504. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  505. }
  506. $linkstart = '<a href="'.$url.'"';
  507. $linkstart .= $linkclose.'>';
  508. $linkend = '</a>';
  509. $result .= $linkstart;
  510. if ($withpicto) {
  511. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  512. }
  513. if ($withpicto != 2) {
  514. $result .= $this->ref;
  515. }
  516. $result .= $linkend;
  517. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  518. $hookmanager->initHooks(array('emailcollectordao'));
  519. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  520. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  521. if ($reshook > 0) {
  522. $result = $hookmanager->resPrint;
  523. } else {
  524. $result .= $hookmanager->resPrint;
  525. }
  526. return $result;
  527. }
  528. /**
  529. * Return label of the status
  530. *
  531. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  532. * @return string Label of status
  533. */
  534. public function getLibStatut($mode = 0)
  535. {
  536. return $this->LibStatut($this->status, $mode);
  537. }
  538. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  539. /**
  540. * Return the status
  541. *
  542. * @param int $status Id status
  543. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  544. * @return string Label of status
  545. */
  546. public function LibStatut($status, $mode = 0)
  547. {
  548. // phpcs:enable
  549. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  550. global $langs;
  551. //$langs->load("mymodule");
  552. $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
  553. $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
  554. $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
  555. $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
  556. }
  557. $statusType = 'status5';
  558. if ($status == self::STATUS_ENABLED) {
  559. $statusType = 'status4';
  560. }
  561. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  562. }
  563. /**
  564. * Charge les informations d'ordre info dans l'objet commande
  565. *
  566. * @param int $id Id of order
  567. * @return void
  568. */
  569. public function info($id)
  570. {
  571. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  572. $sql .= ' fk_user_creat, fk_user_modif';
  573. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  574. $sql .= ' WHERE t.rowid = '.((int) $id);
  575. $result = $this->db->query($sql);
  576. if ($result) {
  577. if ($this->db->num_rows($result)) {
  578. $obj = $this->db->fetch_object($result);
  579. $this->id = $obj->rowid;
  580. $this->user_creation_id = $obj->fk_user_creat;
  581. $this->user_modification_id = $obj->fk_user_modif;
  582. $this->date_creation = $this->db->jdate($obj->datec);
  583. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  584. }
  585. $this->db->free($result);
  586. } else {
  587. dol_print_error($this->db);
  588. }
  589. }
  590. /**
  591. * Initialise object with example values
  592. * Id must be 0 if object instance is a specimen
  593. *
  594. * @return void
  595. */
  596. public function initAsSpecimen()
  597. {
  598. $this->host = 'localhost';
  599. $this->login = 'alogin';
  600. $this->initAsSpecimenCommon();
  601. }
  602. /**
  603. * Fetch filters
  604. *
  605. * @return int <0 if KO, >0 if OK
  606. * @see fetchActions()
  607. */
  608. public function fetchFilters()
  609. {
  610. $this->filters = array();
  611. $sql = 'SELECT rowid, type, rulevalue, status';
  612. $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter';
  613. $sql .= ' WHERE fk_emailcollector = '.((int) $this->id);
  614. //$sql.= ' ORDER BY position';
  615. $resql = $this->db->query($sql);
  616. if ($resql) {
  617. $num = $this->db->num_rows($resql);
  618. $i = 0;
  619. while ($i < $num) {
  620. $obj = $this->db->fetch_object($resql);
  621. $this->filters[$obj->rowid] = array('id'=>$obj->rowid, 'type'=>$obj->type, 'rulevalue'=>$obj->rulevalue, 'status'=>$obj->status);
  622. $i++;
  623. }
  624. $this->db->free($resql);
  625. } else {
  626. dol_print_error($this->db);
  627. }
  628. return 1;
  629. }
  630. /**
  631. * Fetch actions
  632. *
  633. * @return int <0 if KO, >0 if OK
  634. * @see fetchFilters()
  635. */
  636. public function fetchActions()
  637. {
  638. $this->actions = array();
  639. $sql = 'SELECT rowid, type, actionparam, status';
  640. $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectoraction';
  641. $sql .= ' WHERE fk_emailcollector = '.((int) $this->id);
  642. $sql .= ' ORDER BY position';
  643. $resql = $this->db->query($sql);
  644. if ($resql) {
  645. $num = $this->db->num_rows($resql);
  646. $i = 0;
  647. while ($i < $num) {
  648. $obj = $this->db->fetch_object($resql);
  649. $this->actions[$obj->rowid] = array('id'=>$obj->rowid, 'type'=>$obj->type, 'actionparam'=>$obj->actionparam, 'status'=>$obj->status);
  650. $i++;
  651. }
  652. $this->db->free($resql);
  653. return 1;
  654. } else {
  655. dol_print_error($this->db);
  656. return -1;
  657. }
  658. }
  659. /**
  660. * Return the connectstring to use with IMAP connection function
  661. *
  662. * @return string
  663. */
  664. public function getConnectStringIMAP()
  665. {
  666. global $conf;
  667. // Connect to IMAP
  668. $flags = '/service=imap'; // IMAP
  669. if (!empty($conf->global->IMAP_FORCE_TLS)) {
  670. $flags .= '/tls';
  671. } elseif (empty($this->imap_encryption) || ($this->imap_encryption == 'ssl' && !empty($conf->global->IMAP_FORCE_NOSSL))) {
  672. $flags .= '';
  673. } else {
  674. $flags .= '/' . $this->imap_encryption;
  675. }
  676. $flags .= '/novalidate-cert';
  677. //$flags.='/readonly';
  678. //$flags.='/debug';
  679. if (!empty($this->norsh) || !empty($conf->global->IMAP_FORCE_NORSH)) {
  680. $flags .= '/norsh';
  681. }
  682. //Used in shared mailbox from Office365
  683. if (strpos($this->login, '/') != false) {
  684. $partofauth = explode('/', $this->login);
  685. $flags .= '/authuser='.$partofauth[0].'/user='.$partofauth[1];
  686. }
  687. $connectstringserver = '{'.$this->host.':'.$this->port.$flags.'}';
  688. return $connectstringserver;
  689. }
  690. /**
  691. * Convert str to UTF-7 imap default mailbox names
  692. *
  693. * @param string $str String to encode
  694. * @return string Encode string
  695. */
  696. public function getEncodedUtf7($str)
  697. {
  698. if (function_exists('mb_convert_encoding')) {
  699. // change spaces by entropy because mb_convert fail with spaces
  700. $str = preg_replace("/ /", "xyxy", $str);
  701. // if mb_convert work
  702. if ($str = mb_convert_encoding($str, "UTF-7")) {
  703. // change characters
  704. $str = preg_replace("/\+A/", "&A", $str);
  705. // change to spaces again
  706. $str = preg_replace("/xyxy/", " ", $str);
  707. return $str;
  708. } else {
  709. // print error and return false
  710. $this->error = "error: is not possible to encode this string '".$str."'";
  711. return false;
  712. }
  713. } else {
  714. return $str;
  715. }
  716. }
  717. /**
  718. * Action executed by scheduler
  719. * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters'
  720. *
  721. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  722. */
  723. public function doCollect()
  724. {
  725. global $user;
  726. $nberror = 0;
  727. $arrayofcollectors = $this->fetchAll($user, 1);
  728. // Loop on each collector
  729. foreach ($arrayofcollectors as $emailcollector) {
  730. $result = $emailcollector->doCollectOneCollector(0);
  731. dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id);
  732. $this->error .= 'EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'<br>';
  733. if (!empty($emailcollector->errors)) {
  734. $this->error .= join('<br>', $emailcollector->errors);
  735. }
  736. $this->output .= 'EmailCollector ID '.$emailcollector->id.': '.$emailcollector->lastresult.'<br>';
  737. }
  738. return $nberror;
  739. }
  740. /**
  741. * overwitePropertiesOfObject
  742. *
  743. * @param object $object Current object we will set ->properties
  744. * @param string $actionparam Action parameters
  745. * @param string $messagetext Body
  746. * @param string $subject Subject
  747. * @param string $header Header
  748. * @param string $operationslog String with logs of operations done
  749. * @return int 0=OK, Nb of error if error
  750. */
  751. private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header, &$operationslog)
  752. {
  753. global $conf, $langs;
  754. $errorforthisaction = 0;
  755. // set output lang
  756. $outputlangs = $langs;
  757. $newlang = '';
  758. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  759. $newlang = GETPOST('lang_id', 'aZ09');
  760. }
  761. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  762. $newlang = $object->thirdparty->default_lang;
  763. }
  764. if (!empty($newlang)) {
  765. $outputlangs = new Translate('', $conf);
  766. $outputlangs->setDefaultLang($newlang);
  767. }
  768. // Overwrite values with values extracted from source email
  769. // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....'
  770. $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '=');
  771. $tmp = array();
  772. // Loop on each property set into actionparam
  773. foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
  774. $tmpclass = '';
  775. $tmpproperty = '';
  776. $tmparray = explode('.', $propertytooverwrite);
  777. if (count($tmparray) == 2) {
  778. $tmpclass = $tmparray[0];
  779. $tmpproperty = $tmparray[1];
  780. } else {
  781. $tmpproperty = $tmparray[0];
  782. }
  783. if ($tmpclass && ($tmpclass != $object->element)) {
  784. continue; // Property is for another type of object
  785. }
  786. //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty))
  787. if ($tmpproperty) {
  788. $sourcestring = '';
  789. $sourcefield = '';
  790. $regexstring = '';
  791. //$transformationstring='';
  792. $regforregex = array();
  793. if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
  794. $sourcefield = $regforregex[1];
  795. $regexstring = $regforregex[2];
  796. //$transofrmationstring=$regforregex[3];
  797. } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
  798. $sourcefield = $regforregex[1];
  799. $regexstring = $regforregex[2];
  800. }
  801. if (!empty($sourcefield) && !empty($regexstring)) {
  802. if (strtolower($sourcefield) == 'body') {
  803. $sourcestring = $messagetext;
  804. } elseif (strtolower($sourcefield) == 'subject') {
  805. $sourcestring = $subject;
  806. } elseif (strtolower($sourcefield) == 'header') {
  807. $sourcestring = $header;
  808. }
  809. if ($sourcestring) {
  810. $regforval = array();
  811. $regexoptions = '';
  812. if (strtolower($sourcefield) == 'body') {
  813. $regexoptions = 'ms'; // The m means ^ and $ char is valid at each new line. The s means the char '.' is valid for new lines char too
  814. }
  815. if (strtolower($sourcefield) == 'header') {
  816. $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line.
  817. }
  818. //var_dump($tmpproperty.' - '.$regexstring.' - '.$regexoptions.' - '.$sourcestring);
  819. if (preg_match('/'.$regexstring.'/'.$regexoptions, $sourcestring, $regforval)) {
  820. // Overwrite param $tmpproperty
  821. $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) : null;
  822. if (strtolower($sourcefield) == 'header') { // extract from HEADER
  823. if (preg_match('/^options_/', $tmpproperty)) {
  824. $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted);
  825. } else {
  826. if (property_exists($object, $tmpproperty)) {
  827. $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted);
  828. } else {
  829. $tmp[$tmpproperty] = $this->decodeSMTPSubject($valueextracted);
  830. }
  831. }
  832. } else { // extract from BODY
  833. if (preg_match('/^options_/', $tmpproperty)) {
  834. $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted);
  835. } else {
  836. if (property_exists($object, $tmpproperty)) {
  837. $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted);
  838. } else {
  839. $tmp[$tmpproperty] = $this->decodeSMTPSubject($valueextracted);
  840. }
  841. }
  842. }
  843. if (preg_match('/^options_/', $tmpproperty)) {
  844. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> found '.dol_escape_htmltag(dol_trunc($object->array_options[preg_replace('/^options_/', '', $tmpproperty)], 128));
  845. } else {
  846. if (property_exists($object, $tmpproperty)) {
  847. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> found '.dol_escape_htmltag(dol_trunc($object->$tmpproperty, 128));
  848. } else {
  849. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> found '.dol_escape_htmltag(dol_trunc($tmp[$tmpproperty], 128));
  850. }
  851. }
  852. } else {
  853. // Regex not found
  854. if (property_exists($object, $tmpproperty)) {
  855. $object->$tmpproperty = null;
  856. } else {
  857. $tmp[$tmpproperty] = null;
  858. }
  859. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> not found, so property '.dol_escape_htmltag($tmpproperty).' is set to null.';
  860. }
  861. } else {
  862. // Nothing can be done for this param
  863. $errorforthisaction++;
  864. $this->error = 'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
  865. $this->errors[] = $this->error;
  866. $operationslog .= '<br>'.$this->error;
  867. }
  868. } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
  869. $valuecurrent = '';
  870. if (preg_match('/^options_/', $tmpproperty)) {
  871. $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)];
  872. } else {
  873. if (property_exists($object, $tmpproperty)) {
  874. $valuecurrent = $object->$tmpproperty;
  875. } else {
  876. $valuecurrent = $tmp[$tmpproperty];
  877. }
  878. }
  879. if ($regforregex[1] == 'SET' || empty($valuecurrent)) {
  880. $valuetouse = $regforregex[2];
  881. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  882. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  883. $matcharray = array();
  884. preg_match_all('/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
  885. //var_dump($tmpproperty.' - '.$object->$tmpproperty.' - '.$valuetouse); var_dump($matcharray);
  886. if (is_array($matcharray[1])) { // $matcharray[1] is an array with the list of substitution key found without the __X__ syntax into the SET entry
  887. foreach ($matcharray[1] as $keytoreplace) {
  888. if ($keytoreplace) {
  889. if (preg_match('/^options_/', $keytoreplace)) {
  890. $substitutionarray['__'.$keytoreplace.'__'] = $object->array_options[preg_replace('/^options_/', '', $keytoreplace)];
  891. } else {
  892. if (property_exists($object, $keytoreplace)) {
  893. $substitutionarray['__'.$keytoreplace.'__'] = $object->$keytoreplace;
  894. } else {
  895. $substitutionarray['__'.$keytoreplace.'__'] = $tmp[$keytoreplace];
  896. }
  897. }
  898. }
  899. }
  900. }
  901. //var_dump($substitutionarray);
  902. //dol_syslog('substitutionarray='.var_export($substitutionarray, true));
  903. $valuetouse = make_substitutions($valuetouse, $substitutionarray);
  904. if (preg_match('/^options_/', $tmpproperty)) {
  905. $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse;
  906. $operationslog .= '<br>Set value '.dol_escape_htmltag($valuetouse).' into object->array_options['.dol_escape_htmltag(preg_replace('/^options_/', '', $tmpproperty)).']';
  907. } else {
  908. if (property_exists($object, $tmpproperty)) {
  909. $object->$tmpproperty = $valuetouse;
  910. } else {
  911. $tmp[$tmpproperty] = $valuetouse;
  912. }
  913. $operationslog .= '<br>Set value '.dol_escape_htmltag($valuetouse).' into object->'.dol_escape_htmltag($tmpproperty);
  914. }
  915. }
  916. } else {
  917. $errorforthisaction++;
  918. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  919. $this->errors[] = $this->error;
  920. }
  921. }
  922. }
  923. return $errorforthisaction;
  924. }
  925. /**
  926. * Execute collect for current collector loaded previously with fetch.
  927. *
  928. * @param int $mode 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates
  929. * @return int <0 if KO, >0 if OK
  930. */
  931. public function doCollectOneCollector($mode = 0)
  932. {
  933. global $db, $conf, $langs, $user;
  934. global $hookmanager;
  935. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  936. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  937. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  938. require_once DOL_DOCUMENT_ROOT.'/includes/webklex/php-imap/vendor/autoload.php';
  939. }
  940. dol_syslog("EmailCollector::doCollectOneCollector start for id=".$this->id." - ".$this->ref, LOG_INFO);
  941. $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda", "commercial"));
  942. $error = 0;
  943. $this->output = '';
  944. $this->error = '';
  945. $this->debuginfo = '';
  946. $search = '';
  947. $searchhead = '';
  948. $searchfilterdoltrackid = 0;
  949. $searchfilternodoltrackid = 0;
  950. $searchfilterisanswer = 0;
  951. $searchfilterisnotanswer = 0;
  952. $searchfilterreplyto = 0;
  953. $searchfilterexcludebodyarray = array();
  954. $searchfilterexcludesubjectarray = array();
  955. $operationslog = '';
  956. $now = dol_now();
  957. if (empty($this->host)) {
  958. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost'));
  959. return -1;
  960. }
  961. if (empty($this->login)) {
  962. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login'));
  963. return -1;
  964. }
  965. if (empty($this->source_directory)) {
  966. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory'));
  967. return -1;
  968. }
  969. $this->fetchFilters();
  970. $this->fetchActions();
  971. $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
  972. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  973. if ($this->acces_type == 1) {
  974. // Mode OAUth2 with PHP-IMAP
  975. require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
  976. $keyforsupportedoauth2array = $this->oauth_service;
  977. if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
  978. $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
  979. } else {
  980. $keyforprovider = '';
  981. }
  982. $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
  983. $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
  984. $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
  985. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  986. //$debugtext = "Host: ".$this->host."<br>Port: ".$this->port."<br>Login: ".$this->login."<br>Password: ".$this->password."<br>access type: ".$this->acces_type."<br>oauth service: ".$this->oauth_service."<br>Max email per collect: ".$this->maxemailpercollect;
  987. //dol_syslog($debugtext);
  988. $token = '';
  989. $storage = new DoliStorage($db, $conf, $keyforprovider);
  990. try {
  991. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  992. $expire = true;
  993. // Is token expired or will token expire in the next 30 seconds
  994. // if (is_object($tokenobj)) {
  995. // $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
  996. // }
  997. // Token expired so we refresh it
  998. if (is_object($tokenobj) && $expire) {
  999. $credentials = new Credentials(
  1000. getDolGlobalString('OAUTH_'.$this->oauth_service.'_ID'),
  1001. getDolGlobalString('OAUTH_'.$this->oauth_service.'_SECRET'),
  1002. getDolGlobalString('OAUTH_'.$this->oauth_service.'_URLAUTHORIZE')
  1003. );
  1004. $serviceFactory = new \OAuth\ServiceFactory();
  1005. $oauthname = explode('-', $OAUTH_SERVICENAME);
  1006. // ex service is Google-Emails we need only the first part Google
  1007. $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
  1008. // We have to save the token because Google give it only once
  1009. $refreshtoken = $tokenobj->getRefreshToken();
  1010. $tokenobj = $apiService->refreshAccessToken($tokenobj);
  1011. $tokenobj->setRefreshToken($refreshtoken);
  1012. $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
  1013. }
  1014. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  1015. if (is_object($tokenobj)) {
  1016. $token = $tokenobj->getAccessToken();
  1017. } else {
  1018. $this->error = "Token not found";
  1019. return -1;
  1020. }
  1021. } catch (Exception $e) {
  1022. // Return an error if token not found
  1023. $this->error = $e->getMessage();
  1024. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  1025. return -1;
  1026. }
  1027. $cm = new ClientManager();
  1028. $client = $cm->make([
  1029. 'host' => $this->host,
  1030. 'port' => $this->port,
  1031. 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
  1032. 'validate_cert' => true,
  1033. 'protocol' => 'imap',
  1034. 'username' => $this->login,
  1035. 'password' => $token,
  1036. 'authentication' => "oauth",
  1037. ]);
  1038. } else {
  1039. // Mode login/pass with PHP-IMAP
  1040. $cm = new ClientManager();
  1041. $client = $cm->make([
  1042. 'host' => $this->host,
  1043. 'port' => $this->port,
  1044. 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
  1045. 'validate_cert' => true,
  1046. 'protocol' => 'imap',
  1047. 'username' => $this->login,
  1048. 'password' => $this->password,
  1049. 'authentication' => "login",
  1050. ]);
  1051. }
  1052. try {
  1053. $client->connect();
  1054. } catch (ConnectionFailedException $e) {
  1055. $this->error = $e->getMessage();
  1056. $this->errors[] = $this->error;
  1057. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1058. return -1;
  1059. }
  1060. $host = dol_getprefix('email');
  1061. } else {
  1062. // Use native IMAP functions
  1063. if (!function_exists('imap_open')) {
  1064. $this->error = 'IMAP function not enabled on your PHP';
  1065. return -2;
  1066. }
  1067. $sourcedir = $this->source_directory;
  1068. $connectstringserver = $this->getConnectStringIMAP();
  1069. $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
  1070. $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
  1071. $connection = imap_open($connectstringsource, $this->login, $this->password);
  1072. if (!$connection) {
  1073. $this->error = 'Failed to open IMAP connection '.$connectstringsource.' '.imap_last_error();
  1074. return -3;
  1075. }
  1076. imap_errors(); // Clear stack of errors.
  1077. $host = dol_getprefix('email');
  1078. //$host = '123456';
  1079. // Define the IMAP search string
  1080. // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible)
  1081. // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2
  1082. //$search='ALL';
  1083. }
  1084. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1085. // Use PHPIMAP external library
  1086. $criteria = array(array('UNDELETED')); // Seems not supported by some servers
  1087. foreach ($this->filters as $rule) {
  1088. if (empty($rule['status'])) {
  1089. continue;
  1090. }
  1091. $not = '';
  1092. if (strpos($rule['rulevalue'], '!') === 0) {
  1093. // The value start with !, so we exclude the criteria
  1094. $not = 'NOT ';
  1095. }
  1096. if ($rule['type'] == 'from') {
  1097. $tmprulevaluearray = explode('*', $rule['rulevalue']);
  1098. if (count($tmprulevaluearray) >= 2) {
  1099. foreach ($tmprulevaluearray as $tmprulevalue) {
  1100. array_push($criteria, array($not."FROM" => $tmprulevalue));
  1101. }
  1102. } else {
  1103. array_push($criteria, array($not."FROM" => $rule['rulevalue']));
  1104. }
  1105. }
  1106. if ($rule['type'] == 'to') {
  1107. $tmprulevaluearray = explode('*', $rule['rulevalue']);
  1108. if (count($tmprulevaluearray) >= 2) {
  1109. foreach ($tmprulevaluearray as $tmprulevalue) {
  1110. array_push($criteria, array($not."TO" => $tmprulevalue));
  1111. }
  1112. } else {
  1113. array_push($criteria, array($not."TO" => $rule['rulevalue']));
  1114. }
  1115. }
  1116. if ($rule['type'] == 'bcc') {
  1117. array_push($criteria, array($not."BCC" => $rule['rulevalue']));
  1118. }
  1119. if ($rule['type'] == 'cc') {
  1120. array_push($criteria, array($not."CC" => $rule['rulevalue']));
  1121. }
  1122. if ($rule['type'] == 'subject') {
  1123. if (strpos($rule['rulevalue'], '!') === 0) {
  1124. //array_push($criteria, array("NOT SUBJECT" => $rule['rulevalue']));
  1125. $searchfilterexcludesubjectarray[] = preg_replace('/^!/', '', $rule['rulevalue']);
  1126. } else {
  1127. array_push($criteria, array("SUBJECT" => $rule['rulevalue']));
  1128. }
  1129. }
  1130. if ($rule['type'] == 'body') {
  1131. if (strpos($rule['rulevalue'], '!') === 0) {
  1132. //array_push($criteria, array("NOT BODY" => $rule['rulevalue']));
  1133. $searchfilterexcludebodyarray[] = preg_replace('/^!/', '', $rule['rulevalue']);
  1134. } else {
  1135. array_push($criteria, array("BODY" => $rule['rulevalue']));
  1136. }
  1137. }
  1138. if ($rule['type'] == 'header') {
  1139. array_push($criteria, array($not."HEADER" => $rule['rulevalue']));
  1140. }
  1141. /* seems not used */
  1142. /*
  1143. if ($rule['type'] == 'notinsubject') {
  1144. array_push($criteria, array($not."SUBJECT NOT" => $rule['rulevalue']));
  1145. }
  1146. if ($rule['type'] == 'notinbody') {
  1147. array_push($criteria, array($not."BODY NOT" => $rule['rulevalue']));
  1148. }*/
  1149. if ($rule['type'] == 'seen') {
  1150. array_push($criteria, array($not."SEEN"));
  1151. }
  1152. if ($rule['type'] == 'unseen') {
  1153. array_push($criteria, array($not."UNSEEN"));
  1154. }
  1155. if ($rule['type'] == 'unanswered') {
  1156. array_push($criteria, array($not."UNANSWERED"));
  1157. }
  1158. if ($rule['type'] == 'answered') {
  1159. array_push($criteria, array($not."ANSWERED"));
  1160. }
  1161. if ($rule['type'] == 'smaller') {
  1162. array_push($criteria, array($not."SMALLER"));
  1163. }
  1164. if ($rule['type'] == 'larger') {
  1165. array_push($criteria, array($not."LARGER"));
  1166. }
  1167. // Rules to filter after the search imap
  1168. if ($rule['type'] == 'withtrackingidinmsgid') {
  1169. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1170. }
  1171. if ($rule['type'] == 'withouttrackingidinmsgid') {
  1172. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1173. }
  1174. if ($rule['type'] == 'withtrackingid') {
  1175. $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
  1176. }
  1177. if ($rule['type'] == 'withouttrackingid') {
  1178. $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
  1179. }
  1180. if ($rule['type'] == 'isanswer') {
  1181. $searchfilterisanswer++; $searchhead .= '/References.*@.*/';
  1182. }
  1183. if ($rule['type'] == 'isnotanswer') {
  1184. $searchfilterisnotanswer++; $searchhead .= '! /References.*@.*/';
  1185. }
  1186. if ($rule['type'] == 'replyto') {
  1187. $searchfilterreplyto++; $searchhead .= '/Reply-To.*'.preg_quote($rule['rulevalue'], '/').'/';
  1188. }
  1189. }
  1190. if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined.
  1191. $fromdate = 0;
  1192. if ($this->datelastok) {
  1193. $fromdate = $this->datelastok;
  1194. }
  1195. if ($fromdate > 0) {
  1196. // $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10)
  1197. array_push($criteria, array("SINCE" => date('j-M-Y', $fromdate - 1)));
  1198. }
  1199. //$search.=($search?' ':'').'SINCE 8-Apr-2022';
  1200. }
  1201. dol_syslog("IMAP search string = ".var_export($criteria, true));
  1202. $search = var_export($criteria, true);
  1203. } else {
  1204. // Use native IMAP functions
  1205. $search = 'UNDELETED'; // Seems not supported by some servers
  1206. foreach ($this->filters as $rule) {
  1207. if (empty($rule['status'])) {
  1208. continue;
  1209. }
  1210. // Forge the IMAP search string.
  1211. // See https://www.rfc-editor.org/rfc/rfc3501
  1212. $not = '';
  1213. if (strpos($rule['rulevalue'], '!') === 0) {
  1214. // The value start with !, so we exclude the criteria
  1215. $not = 'NOT ';
  1216. }
  1217. if ($rule['type'] == 'from') {
  1218. $tmprulevaluearray = explode('*', $rule['rulevalue']); // Search on abc*def means searching on 'abc' and on 'def'
  1219. if (count($tmprulevaluearray) >= 2) {
  1220. foreach ($tmprulevaluearray as $tmprulevalue) {
  1221. $search .= ($search ? ' ' : '').$not.'FROM "'.str_replace('"', '', $tmprulevalue).'"';
  1222. }
  1223. } else {
  1224. $search .= ($search ? ' ' : '').$not.'FROM "'.str_replace('"', '', $rule['rulevalue']).'"';
  1225. }
  1226. }
  1227. if ($rule['type'] == 'to') {
  1228. $tmprulevaluearray = explode('*', $rule['rulevalue']); // Search on abc*def means searching on 'abc' and on 'def'
  1229. if (count($tmprulevaluearray) >= 2) {
  1230. foreach ($tmprulevaluearray as $tmprulevalue) {
  1231. $search .= ($search ? ' ' : '').$not.'TO "'.str_replace('"', '', $tmprulevalue).'"';
  1232. }
  1233. } else {
  1234. $search .= ($search ? ' ' : '').$not.'TO "'.str_replace('"', '', $rule['rulevalue']).'"';
  1235. }
  1236. }
  1237. if ($rule['type'] == 'bcc') {
  1238. $search .= ($search ? ' ' : '').$not.'BCC';
  1239. }
  1240. if ($rule['type'] == 'cc') {
  1241. $search .= ($search ? ' ' : '').$not.'CC';
  1242. }
  1243. if ($rule['type'] == 'subject') {
  1244. if (strpos($rule['rulevalue'], '!') === 0) {
  1245. //$search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
  1246. $searchfilterexcludesubjectarray[] = preg_replace('/^!/', '', $rule['rulevalue']);
  1247. } else {
  1248. $search .= ($search ? ' ' : '').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
  1249. }
  1250. }
  1251. if ($rule['type'] == 'body') {
  1252. if (strpos($rule['rulevalue'], '!') === 0) {
  1253. //$search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
  1254. $searchfilterexcludebodyarray[] = preg_replace('/^!/', '', $rule['rulevalue']);
  1255. } else {
  1256. // Warning: Google doesn't implement IMAP properly, and only matches whole words,
  1257. $search .= ($search ? ' ' : '').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
  1258. }
  1259. }
  1260. if ($rule['type'] == 'header') {
  1261. $search .= ($search ? ' ' : '').$not.'HEADER '.$rule['rulevalue'];
  1262. }
  1263. /* seems not used */
  1264. /*
  1265. if ($rule['type'] == 'notinsubject') {
  1266. $search .= ($search ? ' ' : '').'NOT SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
  1267. }
  1268. if ($rule['type'] == 'notinbody') {
  1269. $search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
  1270. }*/
  1271. if ($rule['type'] == 'seen') {
  1272. $search .= ($search ? ' ' : '').$not.'SEEN';
  1273. }
  1274. if ($rule['type'] == 'unseen') {
  1275. $search .= ($search ? ' ' : '').$not.'UNSEEN';
  1276. }
  1277. if ($rule['type'] == 'unanswered') {
  1278. $search .= ($search ? ' ' : '').$not.'UNANSWERED';
  1279. }
  1280. if ($rule['type'] == 'answered') {
  1281. $search .= ($search ? ' ' : '').$not.'ANSWERED';
  1282. }
  1283. if ($rule['type'] == 'smaller') {
  1284. $search .= ($search ? ' ' : '').$not.'SMALLER "'.str_replace('"', '', $rule['rulevalue']).'"';
  1285. }
  1286. if ($rule['type'] == 'larger') {
  1287. $search .= ($search ? ' ' : '').$not.'LARGER "'.str_replace('"', '', $rule['rulevalue']).'"';
  1288. }
  1289. // Rules to filter after the search imap
  1290. if ($rule['type'] == 'withtrackingidinmsgid') {
  1291. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1292. }
  1293. if ($rule['type'] == 'withouttrackingidinmsgid') {
  1294. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1295. }
  1296. if ($rule['type'] == 'withtrackingid') {
  1297. $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
  1298. }
  1299. if ($rule['type'] == 'withouttrackingid') {
  1300. $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
  1301. }
  1302. if ($rule['type'] == 'isanswer') {
  1303. $searchfilterisanswer++; $searchhead .= '/References.*@.*/';
  1304. }
  1305. if ($rule['type'] == 'isnotanswer') {
  1306. $searchfilterisnotanswer++; $searchhead .= '! /References.*@.*/';
  1307. }
  1308. if ($rule['type'] == 'replyto') {
  1309. $searchfilterreplyto++; $searchhead .= '/Reply-To.*'.preg_quote($rule['rulevalue'], '/').'/';
  1310. }
  1311. }
  1312. if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined.
  1313. $fromdate = 0;
  1314. if ($this->datelastok) {
  1315. $fromdate = $this->datelastok;
  1316. }
  1317. if ($fromdate > 0) {
  1318. $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10)
  1319. }
  1320. //$search.=($search?' ':'').'SINCE 8-Apr-2018';
  1321. }
  1322. dol_syslog("IMAP search string = ".$search);
  1323. //var_dump($search);
  1324. }
  1325. $nbemailprocessed = 0;
  1326. $nbemailok = 0;
  1327. $nbactiondone = 0;
  1328. $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8");
  1329. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1330. try {
  1331. //$criteria = [['ALL']];
  1332. //$Query = $client->getFolders()[0]->messages()->where($criteria);
  1333. $f = $client->getFolders(false, $this->source_directory);
  1334. $Query = $f[0]->messages()->where($criteria);
  1335. } catch (InvalidWhereQueryCriteriaException $e) {
  1336. $this->error = $e->getMessage();
  1337. $this->errors[] = $this->error;
  1338. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1339. return -1;
  1340. } catch (Exception $e) {
  1341. $this->error = $e->getMessage();
  1342. $this->errors[] = $this->error;
  1343. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1344. return -1;
  1345. }
  1346. try {
  1347. //var_dump($Query->count());
  1348. if ($mode > 0) {
  1349. $Query->leaveUnread();
  1350. }
  1351. $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder("asc")->get();
  1352. //var_dump($arrayofemail);
  1353. } catch (Exception $e) {
  1354. $this->error = $e->getMessage();
  1355. $this->errors[] = $this->error;
  1356. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1357. return -1;
  1358. }
  1359. } else {
  1360. // Scan IMAP inbox
  1361. $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
  1362. if ($arrayofemail === false) {
  1363. // Nothing found or search string not understood
  1364. $mapoferrrors = imap_errors();
  1365. if ($mapoferrrors !== false) {
  1366. $error++;
  1367. $this->error = "Search string not understood - ".join(',', $mapoferrrors);
  1368. $this->errors[] = $this->error;
  1369. }
  1370. }
  1371. }
  1372. $arrayofemailtodelete = array(); // Track email to delete to make the deletion at end.
  1373. // Loop on each email found
  1374. if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
  1375. // Loop to get part html and plain
  1376. /*
  1377. 0 multipart/mixed
  1378. 1 multipart/alternative
  1379. 1.1 text/plain
  1380. 1.2 text/html
  1381. 2 message/rfc822
  1382. 2 multipart/mixed
  1383. 2.1 multipart/alternative
  1384. 2.1.1 text/plain
  1385. 2.1.2 text/html
  1386. 2.2 message/rfc822
  1387. 2.2 multipart/alternative
  1388. 2.2.1 text/plain
  1389. 2.2.2 text/html
  1390. */
  1391. dol_syslog("Start of loop on email", LOG_INFO, 1);
  1392. $iforemailloop = 0;
  1393. foreach ($arrayofemail as $imapemail) {
  1394. if ($nbemailprocessed > 1000) {
  1395. break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect)
  1396. }
  1397. $iforemailloop++;
  1398. // GET header and overview datas
  1399. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1400. $header = $imapemail->getHeader()->raw;
  1401. $overview = $imapemail->getAttributes();
  1402. } else {
  1403. $header = imap_fetchheader($connection, $imapemail, FT_UID);
  1404. $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
  1405. }
  1406. $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines
  1407. $matches = array();
  1408. preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
  1409. $headers = array_combine($matches[1], $matches[2]);
  1410. //var_dump($headers);exit;
  1411. if (!empty($headers['in-reply-to']) && empty($headers['In-Reply-To'])) {
  1412. $headers['In-Reply-To'] = $headers['in-reply-to'];
  1413. }
  1414. if (!empty($headers['references']) && empty($headers['References'])) {
  1415. $headers['References'] = $headers['references'];
  1416. }
  1417. if (!empty($headers['message-id']) && empty($headers['Message-ID'])) {
  1418. $headers['Message-ID'] = $headers['message-id'];
  1419. }
  1420. if (!empty($headers['subject']) && empty($headers['Subject'])) {
  1421. $headers['Subject'] = $headers['subject'];
  1422. }
  1423. $headers['Subject'] = $this->decodeSMTPSubject($headers['Subject']);
  1424. $emailto = $this->decodeSMTPSubject($overview[0]->to);
  1425. $operationslog .= '<br>** Process email #'.dol_escape_htmltag($iforemailloop)." - ".dol_escape_htmltag($this->uidAsString($imapemail))." - References: ".dol_escape_htmltag($headers['References'])." - Subject: ".dol_escape_htmltag($headers['Subject']);
  1426. dol_syslog("** Process email ".$iforemailloop." References: ".$headers['References']." Subject: ".$headers['Subject']);
  1427. $trackidfoundintorecipienttype = '';
  1428. $trackidfoundintorecipientid = 0;
  1429. $reg = array();
  1430. // See also later list of all supported tags...
  1431. if (preg_match('/\+(thi|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
  1432. $trackidfoundintorecipienttype = $reg[1];
  1433. $trackidfoundintorecipientid = $reg[2];
  1434. } elseif (preg_match('/\+emailing-(\w+)@/', $emailto, $reg)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient'
  1435. $trackidfoundintorecipienttype = 'emailing';
  1436. $trackidfoundintorecipientid = $reg[1];
  1437. }
  1438. // If there is a filter on trackid
  1439. if ($searchfilterdoltrackid > 0) {
  1440. if (empty($trackidfoundintorecipienttype)) {
  1441. if (empty($headers['References']) || !preg_match('/@'.preg_quote($host, '/').'/', $headers['References'])) {
  1442. $nbemailprocessed++;
  1443. dol_syslog(" Discarded - No suffix in email recipient and no Header References found matching signature of application so with a trackid");
  1444. continue; // Exclude email
  1445. }
  1446. }
  1447. }
  1448. if ($searchfilternodoltrackid > 0) {
  1449. if (!empty($trackidfoundintorecipienttype) || (!empty($headers['References']) && preg_match('/@'.preg_quote($host, '/').'/', $headers['References']))) {
  1450. $nbemailprocessed++;
  1451. dol_syslog(" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
  1452. continue; // Exclude email
  1453. }
  1454. }
  1455. if ($searchfilterisanswer > 0) {
  1456. if (empty($headers['In-Reply-To'])) {
  1457. $nbemailprocessed++;
  1458. dol_syslog(" Discarded - Email is not an answer (no In-Reply-To header)");
  1459. continue; // Exclude email
  1460. }
  1461. // Note: we can have
  1462. // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten)
  1463. $isanswer = 0;
  1464. if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) {
  1465. $isanswer = 1;
  1466. }
  1467. //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply
  1468. //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
  1469. if (!$isanswer) {
  1470. $nbemailprocessed++;
  1471. dol_syslog(" Discarded - Email is not an answer (no RE prefix in subject)");
  1472. continue; // Exclude email
  1473. }
  1474. }
  1475. if ($searchfilterisnotanswer > 0) {
  1476. if (!empty($headers['In-Reply-To'])) {
  1477. // Note: we can have
  1478. // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten)
  1479. $isanswer = 0;
  1480. if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) {
  1481. $isanswer = 1;
  1482. }
  1483. //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply
  1484. //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
  1485. if ($isanswer) {
  1486. $nbemailprocessed++;
  1487. dol_syslog(" Discarded - Email is an answer");
  1488. continue; // Exclude email
  1489. }
  1490. }
  1491. }
  1492. //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." selected<br>\n";
  1493. $thirdpartystatic = new Societe($this->db);
  1494. $contactstatic = new Contact($this->db);
  1495. $projectstatic = new Project($this->db);
  1496. $nbactiondoneforemail = 0;
  1497. $errorforemail = 0;
  1498. $errorforactions = 0;
  1499. $thirdpartyfoundby = '';
  1500. $contactfoundby = '';
  1501. $projectfoundby = '';
  1502. $ticketfoundby = '';
  1503. $candidaturefoundby = '';
  1504. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1505. dol_syslog("msgid=".$overview['message_id']." date=".dol_print_date($overview['date'], 'dayrfc', 'gmt')." from=".$overview['from']." to=".$overview['to']." subject=".$overview['subject']);
  1506. // Removed emojis
  1507. $overview['subject'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview['subject']);
  1508. } else {
  1509. dol_syslog("msgid=".$overview[0]->message_id." date=".dol_print_date($overview[0]->udate, 'dayrfc', 'gmt')." from=".$overview[0]->from." to=".$overview[0]->to." subject=".$overview[0]->subject);
  1510. $overview[0]->subject = $this->decodeSMTPSubject($overview[0]->subject);
  1511. $overview[0]->from = $this->decodeSMTPSubject($overview[0]->from);
  1512. // Removed emojis
  1513. $overview[0]->subject = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview[0]->subject);
  1514. }
  1515. // GET IMAP email structure/content
  1516. global $htmlmsg, $plainmsg, $charset, $attachments;
  1517. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1518. if ($imapemail->hasHTMLBody()) {
  1519. $htmlmsg = $imapemail->getHTMLBody();
  1520. }
  1521. if ($imapemail->hasTextBody()) {
  1522. $plainmsg = $imapemail->getTextBody();
  1523. }
  1524. if ($imapemail->hasAttachments()) {
  1525. $attachments = $imapemail->getAttachments()->all();
  1526. } else {
  1527. $attachments = [];
  1528. }
  1529. } else {
  1530. $this->getmsg($connection, $imapemail); // This set global var $charset, $htmlmsg, $plainmsg, $attachments
  1531. }
  1532. //print $plainmsg;
  1533. //var_dump($plainmsg); exit;
  1534. //$htmlmsg,$plainmsg,$charset,$attachments
  1535. $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag($htmlmsg, 0);
  1536. // Removed emojis
  1537. if (utf8_valid($messagetext)) {
  1538. //$messagetext = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $messagetext);
  1539. $messagetext = $this->removeEmoji($messagetext);
  1540. } else {
  1541. $operationslog .= '<br>Discarded - Email body is not valid utf8';
  1542. dol_syslog(" Discarded - Email body is not valid utf8");
  1543. continue; // Exclude email
  1544. }
  1545. if (!empty($searchfilterexcludebodyarray)) {
  1546. foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
  1547. if (preg_match('/'.preg_quote($searchfilterexcludebody, '/').'/ms', $messagetext)) {
  1548. $nbemailprocessed++;
  1549. $operationslog .= '<br>Discarded - Email body contains string '.$searchfilterexcludebody;
  1550. dol_syslog(" Discarded - Email body contains string ".$searchfilterexcludebody);
  1551. continue 2; // Exclude email
  1552. }
  1553. }
  1554. }
  1555. //var_dump($plainmsg);
  1556. //var_dump($htmlmsg);
  1557. //var_dump($messagetext);
  1558. //var_dump($charset);
  1559. //var_dump($attachments);
  1560. //exit;
  1561. // Parse IMAP email structure
  1562. /*
  1563. $structure = imap_fetchstructure($connection, $imapemail, FT_UID);
  1564. $partplain = $parthtml = -1;
  1565. $encodingplain = $encodinghtml = '';
  1566. $result = createPartArray($structure, '');
  1567. foreach($result as $part)
  1568. {
  1569. // $part['part_object']->type seems 0 for content
  1570. // $part['part_object']->type seems 5 for attachment
  1571. if (empty($part['part_object'])) continue;
  1572. if ($part['part_object']->subtype == 'HTML')
  1573. {
  1574. $parthtml=$part['part_number'];
  1575. if ($part['part_object']->encoding == 4)
  1576. {
  1577. $encodinghtml = 'aaa';
  1578. }
  1579. }
  1580. if ($part['part_object']->subtype == 'PLAIN')
  1581. {
  1582. $partplain=$part['part_number'];
  1583. if ($part['part_object']->encoding == 4)
  1584. {
  1585. $encodingplain = 'rr';
  1586. }
  1587. }
  1588. }
  1589. //var_dump($result);
  1590. //var_dump($partplain);
  1591. //var_dump($parthtml);
  1592. //var_dump($structure);
  1593. //var_dump($parthtml);
  1594. //var_dump($partplain);
  1595. $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK|FTP_UID);
  1596. */
  1597. //var_dump($messagetext);
  1598. //var_dump($structure->parts[0]->parts);
  1599. //print $header;
  1600. //print $messagetext;
  1601. //exit;
  1602. $fromstring = '';
  1603. $replytostring = '';
  1604. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1605. $fromstring = $overview['from'];
  1606. //$replytostring = empty($overview['reply-to']) ? '' : $overview['reply-to'];
  1607. $sender = $overview['sender'];
  1608. $to = $overview['to'];
  1609. $sendtocc = empty($overview['cc']) ? '' : $overview['cc'];
  1610. $sendtobcc = empty($overview['bcc']) ? '' : $overview['bcc'];
  1611. $date = $overview['date'];
  1612. $msgid = str_replace(array('<', '>'), '', $overview['message_id']);
  1613. $subject = $overview['subject'];
  1614. } else {
  1615. $fromstring = $overview[0]->from;
  1616. //$replytostring = empty($overview[0]->replyto) ? '' : $overview[0]->replyto;
  1617. $sender = $overview[0]->sender;
  1618. $to = $overview[0]->to;
  1619. $sendtocc = $overview[0]->cc;
  1620. $sendtobcc = $overview[0]->bcc;
  1621. $date = $overview[0]->udate;
  1622. $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id);
  1623. $subject = $overview[0]->subject;
  1624. //var_dump($msgid);exit;
  1625. }
  1626. if (!empty($searchfilterexcludesubjectarray)) {
  1627. foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
  1628. if (preg_match('/'.preg_quote($searchfilterexcludesubject, '/').'/ms', $subject)) {
  1629. $nbemailprocessed++;
  1630. $operationslog .= '<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
  1631. dol_syslog(" Discarded - Email subject contains string ".$searchfilterexcludesubject);
  1632. continue 2; // Exclude email
  1633. }
  1634. }
  1635. }
  1636. $reg = array();
  1637. if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) {
  1638. $from = $reg[2];
  1639. $fromtext = $reg[1];
  1640. } else {
  1641. $from = $fromstring;
  1642. $fromtext = '';
  1643. }
  1644. if (preg_match('/^(.*)<(.*)>$/', $replytostring, $reg)) {
  1645. $replyto = $reg[2];
  1646. $replytotext = $reg[1];
  1647. } else {
  1648. $replyto = $replytostring;
  1649. $replytotext = '';
  1650. }
  1651. $fk_element_id = 0; $fk_element_type = '';
  1652. $this->db->begin();
  1653. $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
  1654. // Analyze TrackId in field References. For example:
  1655. // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e>
  1656. // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e>
  1657. // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e>
  1658. $trackid = '';
  1659. $objectid = 0;
  1660. $objectemail = null;
  1661. $reg = array();
  1662. if (!empty($headers['References'])) {
  1663. $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']);
  1664. // var_dump($headers['References']);
  1665. // var_dump($arrayofreferences);
  1666. foreach ($arrayofreferences as $reference) {
  1667. //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($date, 'dayhour').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."<br>\n";
  1668. if (!empty($trackidfoundintorecipienttype)) {
  1669. $resultsearchtrackid = -1;
  1670. $reg[1] = $trackidfoundintorecipienttype;
  1671. $reg[2] = $trackidfoundintorecipientid;
  1672. } else {
  1673. $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $reference, $reg);
  1674. if (empty($resultsearchtrackid) && getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
  1675. $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE'), '/').'/', $reference, $reg);
  1676. }
  1677. }
  1678. if (!empty($resultsearchtrackid)) {
  1679. // We found a tracker (in recipient email or into a Reference matching the Dolibarr server)
  1680. $trackid = $reg[1].$reg[2];
  1681. $objectid = $reg[2];
  1682. // See also list into interface_50_modAgenda_ActionsAuto
  1683. if ($reg[1] == 'thi') { // Third-party
  1684. $objectemail = new Societe($this->db);
  1685. }
  1686. if ($reg[1] == 'ctc') { // Contact
  1687. $objectemail = new Contact($this->db);
  1688. }
  1689. if ($reg[1] == 'inv') { // Customer Invoice
  1690. $objectemail = new Facture($this->db);
  1691. }
  1692. if ($reg[1] == 'sinv') { // Supplier Invoice
  1693. $objectemail = new FactureFournisseur($this->db);
  1694. }
  1695. if ($reg[1] == 'pro') { // Customer Proposal
  1696. $objectemail = new Propal($this->db);
  1697. }
  1698. if ($reg[1] == 'ord') { // Sale Order
  1699. $objectemail = new Commande($this->db);
  1700. }
  1701. if ($reg[1] == 'shi') { // Shipment
  1702. $objectemail = new Expedition($this->db);
  1703. }
  1704. if ($reg[1] == 'spro') { // Supplier Proposal
  1705. $objectemail = new SupplierProposal($this->db);
  1706. }
  1707. if ($reg[1] == 'sord') { // Supplier Order
  1708. $objectemail = new CommandeFournisseur($this->db);
  1709. }
  1710. if ($reg[1] == 'rec') { // Reception
  1711. $objectemail = new Reception($this->db);
  1712. }
  1713. if ($reg[1] == 'proj') { // Project
  1714. $objectemail = new Project($this->db);
  1715. }
  1716. if ($reg[1] == 'tas') { // Task
  1717. $objectemail = new Task($this->db);
  1718. }
  1719. if ($reg[1] == 'con') { // Contact
  1720. $objectemail = new Contact($this->db);
  1721. }
  1722. if ($reg[1] == 'use') { // User
  1723. $objectemail = new User($this->db);
  1724. }
  1725. if ($reg[1] == 'tic') { // Ticket
  1726. $objectemail = new Ticket($this->db);
  1727. }
  1728. if ($reg[1] == 'recruitmentcandidature') { // Recruiting Candidate
  1729. $objectemail = new RecruitmentCandidature($this->db);
  1730. }
  1731. if ($reg[1] == 'mem') { // Member
  1732. $objectemail = new Adherent($this->db);
  1733. }
  1734. /*if ($reg[1] == 'leav') { // Leave / Holiday
  1735. $objectemail = new Holiday($db);
  1736. }
  1737. if ($reg[1] == 'exp') { // ExpenseReport
  1738. $objectemail = new ExpenseReport($db);
  1739. }*/
  1740. } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) {
  1741. // This is an external reference, we check if we have it in our database
  1742. if (!is_object($objectemail)) {
  1743. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ticket where email_msgid = '".$this->db->escape($reg[1])."'";
  1744. $resql = $this->db->query($sql);
  1745. if ($resql) {
  1746. $obj = $this->db->fetch_object($resql);
  1747. if ($obj) {
  1748. $objectid = $obj->rowid;
  1749. $objectemail = new Ticket($this->db);
  1750. $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1751. }
  1752. } else {
  1753. $errorforemail++;
  1754. }
  1755. }
  1756. if (!is_object($objectemail)) {
  1757. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."projet where email_msgid = '".$this->db->escape($reg[1])."'";
  1758. $resql = $this->db->query($sql);
  1759. if ($resql) {
  1760. $obj = $this->db->fetch_object($resql);
  1761. if ($obj) {
  1762. $objectid = $obj->rowid;
  1763. $objectemail = new Project($this->db);
  1764. $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1765. }
  1766. } else {
  1767. $errorforemail++;
  1768. }
  1769. }
  1770. if (!is_object($objectemail)) {
  1771. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1])."'";
  1772. $resql = $this->db->query($sql);
  1773. if ($resql) {
  1774. $obj = $this->db->fetch_object($resql);
  1775. if ($obj) {
  1776. $objectid = $obj->rowid;
  1777. $objectemail = new RecruitmentCandidature($this->db);
  1778. $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1779. }
  1780. } else {
  1781. $errorforemail++;
  1782. }
  1783. }
  1784. }
  1785. // Load object linked to email
  1786. if (is_object($objectemail)) {
  1787. $result = $objectemail->fetch($objectid);
  1788. if ($result > 0) {
  1789. $fk_element_id = $objectemail->id;
  1790. $fk_element_type = $objectemail->element;
  1791. // Fix fk_element_type
  1792. if ($fk_element_type == 'facture') {
  1793. $fk_element_type = 'invoice';
  1794. }
  1795. if (get_class($objectemail) != 'Societe') {
  1796. $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
  1797. } else {
  1798. $thirdpartyid = $objectemail->id;
  1799. }
  1800. if (get_class($objectemail) != 'Contact') {
  1801. $contactid = $objectemail->fk_socpeople;
  1802. } else {
  1803. $contactid = $objectemail->id;
  1804. }
  1805. if (get_class($objectemail) != 'Project') {
  1806. $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
  1807. } else {
  1808. $projectid = $objectemail->id;
  1809. }
  1810. }
  1811. }
  1812. // Project
  1813. if ($projectid > 0) {
  1814. $result = $projectstatic->fetch($projectid);
  1815. if ($result <= 0) {
  1816. $projectstatic->id = 0;
  1817. } else {
  1818. $projectid = $projectstatic->id;
  1819. if ($trackid) {
  1820. $projectfoundby = 'trackid ('.$trackid.')';
  1821. }
  1822. if (empty($contactid)) {
  1823. $contactid = $projectstatic->fk_contact;
  1824. }
  1825. if (empty($thirdpartyid)) {
  1826. $thirdpartyid = $projectstatic->fk_soc;
  1827. }
  1828. }
  1829. }
  1830. // Contact
  1831. if ($contactid > 0) {
  1832. $result = $contactstatic->fetch($contactid);
  1833. if ($result <= 0) {
  1834. $contactstatic->id = 0;
  1835. } else {
  1836. $contactid = $contactstatic->id;
  1837. if ($trackid) {
  1838. $contactfoundby = 'trackid ('.$trackid.')';
  1839. }
  1840. if (empty($thirdpartyid)) {
  1841. $thirdpartyid = $contactstatic->fk_soc;
  1842. }
  1843. }
  1844. }
  1845. // Thirdparty
  1846. if ($thirdpartyid > 0) {
  1847. $result = $thirdpartystatic->fetch($thirdpartyid);
  1848. if ($result <= 0) {
  1849. $thirdpartystatic->id = 0;
  1850. } else {
  1851. $thirdpartyid = $thirdpartystatic->id;
  1852. if ($trackid) {
  1853. $thirdpartyfoundby = 'trackid ('.$trackid.')';
  1854. }
  1855. }
  1856. }
  1857. if (is_object($objectemail)) {
  1858. break; // Exit loop of references. We already found an accurate reference
  1859. }
  1860. }
  1861. }
  1862. if (empty($contactid)) { // Try to find contact using email
  1863. $result = $contactstatic->fetch(0, null, '', $from);
  1864. if ($result > 0) {
  1865. dol_syslog("We found a contact with the email ".$from);
  1866. $contactid = $contactstatic->id;
  1867. $contactfoundby = 'email of contact ('.$from.')';
  1868. if (empty($thirdpartyid) && $contactstatic->socid > 0) {
  1869. $result = $thirdpartystatic->fetch($contactstatic->socid);
  1870. if ($result > 0) {
  1871. $thirdpartyid = $thirdpartystatic->id;
  1872. $thirdpartyfoundby = 'email of contact ('.$from.')';
  1873. }
  1874. }
  1875. }
  1876. }
  1877. if (empty($thirdpartyid)) { // Try to find thirdparty using email
  1878. $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from);
  1879. if ($result > 0) {
  1880. dol_syslog("We found a thirdparty with the email ".$from);
  1881. $thirdpartyid = $thirdpartystatic->id;
  1882. $thirdpartyfoundby = 'email ('.$from.')';
  1883. }
  1884. }
  1885. /*
  1886. if ($replyto) {
  1887. if (empty($contactid)) { // Try to find contact using email
  1888. $result = $contactstatic->fetch(0, null, '', $replyto);
  1889. if ($result > 0) {
  1890. dol_syslog("We found a contact with the email ".$replyto);
  1891. $contactid = $contactstatic->id;
  1892. $contactfoundby = 'email of contact ('.$replyto.')';
  1893. if (empty($thirdpartyid) && $contactstatic->socid > 0) {
  1894. $result = $thirdpartystatic->fetch($contactstatic->socid);
  1895. if ($result > 0) {
  1896. $thirdpartyid = $thirdpartystatic->id;
  1897. $thirdpartyfoundby = 'email of contact ('.$replyto.')';
  1898. }
  1899. }
  1900. }
  1901. }
  1902. if (empty($thirdpartyid)) { // Try to find thirdparty using email
  1903. $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $replyto);
  1904. if ($result > 0) {
  1905. dol_syslog("We found a thirdparty with the email ".$replyto);
  1906. $thirdpartyid = $thirdpartystatic->id;
  1907. $thirdpartyfoundby = 'email ('.$replyto.')';
  1908. }
  1909. }
  1910. }
  1911. */
  1912. // Do operations (extract variables and creating data)
  1913. if ($mode < 2) { // 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates
  1914. foreach ($this->actions as $operation) {
  1915. $errorforthisaction = 0;
  1916. if ($errorforactions) {
  1917. break;
  1918. }
  1919. if (empty($operation['status'])) {
  1920. continue;
  1921. }
  1922. $operationslog .= '<br>* Process operation '.$operation['type'];
  1923. // Make Operation
  1924. dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id);
  1925. dol_syslog("Execute action fk_element_id=".$fk_element_id." fk_element_type=".$fk_element_type); // If a Dolibarr tracker id is found, we should now the id of object
  1926. $actioncode = 'EMAIL_IN';
  1927. // If we scan the Sent box, we use the code for out email
  1928. if ($this->source_directory == 'Sent') {
  1929. $actioncode = 'EMAIL_OUT';
  1930. }
  1931. $description = $descriptiontitle = $descriptionmeta = $descriptionfull = '';
  1932. $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid);
  1933. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject));
  1934. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring));
  1935. if ($sender) {
  1936. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender));
  1937. }
  1938. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to));
  1939. if ($sendtocc) {
  1940. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc));
  1941. }
  1942. // Search and create thirdparty
  1943. if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') {
  1944. if (empty($operation['actionparam'])) {
  1945. $errorforactions++;
  1946. $this->error = "Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be a rule like 'name=HEADER:^From:(.*);' or 'name=SET:xxx' or 'name=EXTRACT:(body|subject):regex where 'name' can be replaced with 'id' or 'email' to define how to set or extract data. More properties can also be set, for example client=SET:2;";
  1947. $this->errors[] = $this->error;
  1948. } else {
  1949. $actionparam = $operation['actionparam'];
  1950. $idtouseforthirdparty = '';
  1951. $nametouseforthirdparty = '';
  1952. $emailtouseforthirdparty = '';
  1953. $namealiastouseforthirdparty = '';
  1954. $operationslog .= '<br>Loop on each property to set into actionparam';
  1955. // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....'
  1956. $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '=');
  1957. foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
  1958. $sourcestring = '';
  1959. $sourcefield = '';
  1960. $regexstring = '';
  1961. $regforregex = array();
  1962. if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
  1963. $sourcefield = $regforregex[1];
  1964. $regexstring = $regforregex[2];
  1965. }
  1966. if (!empty($sourcefield) && !empty($regexstring)) {
  1967. if (strtolower($sourcefield) == 'body') {
  1968. $sourcestring = $messagetext;
  1969. } elseif (strtolower($sourcefield) == 'subject') {
  1970. $sourcestring = $subject;
  1971. } elseif (strtolower($sourcefield) == 'header') {
  1972. $sourcestring = $header;
  1973. }
  1974. if ($sourcestring) {
  1975. $regforval = array();
  1976. //var_dump($regexstring);var_dump($sourcestring);
  1977. if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) {
  1978. //var_dump($regforval[count($regforval)-1]);exit;
  1979. // Overwrite param $tmpproperty
  1980. if ($propertytooverwrite == 'id') {
  1981. $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1982. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found idtouseforthirdparty='.dol_escape_htmltag($idtouseforthirdparty);
  1983. } elseif ($propertytooverwrite == 'email') {
  1984. $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1985. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found emailtouseforthirdparty='.dol_escape_htmltag($emailtouseforthirdparty);
  1986. } elseif ($propertytooverwrite == 'name') {
  1987. $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1988. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
  1989. } elseif ($propertytooverwrite == 'name_alias') {
  1990. $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1991. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found namealiastouseforthirdparty='.dol_escape_htmltag($namealiastouseforthirdparty);
  1992. } else {
  1993. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> We discard this, not a field used to search an existing thirdparty';
  1994. }
  1995. } else {
  1996. // Regex not found
  1997. if (in_array($propertytooverwrite, array('id', 'email', 'name', 'name_alias'))) {
  1998. $idtouseforthirdparty = null;
  1999. $nametouseforthirdparty = null;
  2000. $emailtouseforthirdparty = null;
  2001. $namealiastouseforthirdparty = null;
  2002. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Not found. Property searched is critical so we cancel the search.';
  2003. } else {
  2004. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Not found';
  2005. }
  2006. }
  2007. //var_dump($object->$tmpproperty);exit;
  2008. } else {
  2009. // Nothing can be done for this param
  2010. $errorforactions++;
  2011. $this->error = 'The extract rule to use to load thirdparty for email '.$msgid.' has an unknown source (must be HEADER, SUBJECT or BODY)';
  2012. $this->errors[] = $this->error;
  2013. $operationslog .= '<br>'.$this->error;
  2014. }
  2015. } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
  2016. //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1];
  2017. //else $object->$tmpproperty = $reg[1];
  2018. // Example: id=SETIFEMPTY:123
  2019. if ($propertytooverwrite == 'id') {
  2020. $idtouseforthirdparty = $reg[2];
  2021. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property idtouseforthrdparty='.dol_escape_htmltag($idtouseforthirdparty);
  2022. } elseif ($propertytooverwrite == 'email') {
  2023. $emailtouseforthirdparty = $reg[2];
  2024. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property emailtouseforthrdparty='.dol_escape_htmltag($emailtouseforthirdparty);
  2025. } elseif ($propertytooverwrite == 'name') {
  2026. $nametouseforthirdparty = $reg[2];
  2027. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
  2028. } elseif ($propertytooverwrite == 'name_alias') {
  2029. $namealiastouseforthirdparty = $reg[2];
  2030. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property namealiastouseforthirdparty='.dol_escape_htmltag($namealiastouseforthirdparty);
  2031. }
  2032. } else {
  2033. $errorforactions++;
  2034. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  2035. $this->errors[] = $this->error;
  2036. break;
  2037. }
  2038. }
  2039. if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
  2040. // We make another search on thirdparty
  2041. $operationslog .= '<br>We have this data to search thirdparty: id='.$idtouseforthirdparty.', email='.$emailtouseforthirdparty.', name='.$nametouseforthirdparty.', name_alias='.$namealiastouseforthirdparty;
  2042. $tmpobject = new stdClass();
  2043. $tmpobject->element == 'generic';
  2044. $tmpobject->id = $idtouseforthirdparty;
  2045. $tmpobject->name = $nametouseforthirdparty;
  2046. $tmpobject->name_alias = $namealiastouseforthirdparty;
  2047. $tmpobject->email = $emailtouseforthirdparty;
  2048. $this->overwritePropertiesOfObject($tmpobject, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2049. $idtouseforthirdparty = $tmpobject->id;
  2050. $nametouseforthirdparty = $tmpobject->name;
  2051. $namealiastouseforthirdparty = $tmpobject->name_alias;
  2052. $emailtouseforthirdparty = $tmpobject->email;
  2053. $operationslog .= '<br>We try to search existing thirdparty with '.$idtouseforthirdparty.' '.$emailtouseforthirdparty.' '.$nametouseforthirdparty.' '.$namealiastouseforthirdparty;
  2054. $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty, $namealiastouseforthirdparty);
  2055. if ($result < 0) {
  2056. $errorforactions++;
  2057. $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)';
  2058. $this->errors[] = $this->error;
  2059. break;
  2060. } elseif ($result == 0) {
  2061. if ($operation['type'] == 'loadthirdparty') {
  2062. dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was not found");
  2063. $errorforactions++;
  2064. $langs->load("errors");
  2065. $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
  2066. $this->errors[] = $this->error;
  2067. } elseif ($operation['type'] == 'loadandcreatethirdparty') {
  2068. dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was not found. We try to create it.");
  2069. // Create thirdparty
  2070. $thirdpartystatic = new Societe($db);
  2071. $thirdpartystatic->name = $nametouseforthirdparty;
  2072. if (!empty($namealiastouseforthirdparty)) {
  2073. if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
  2074. $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
  2075. }
  2076. } else {
  2077. $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ? '': $fromtext) : $replytostring);
  2078. }
  2079. $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ? '' : $from) : $replyto) : $emailtouseforthirdparty);
  2080. // Overwrite values with values extracted from source email
  2081. $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2082. if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
  2083. $thirdpartystatic->code_client = 'auto';
  2084. }
  2085. if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
  2086. $thirdpartystatic->code_fournisseur = 'auto';
  2087. }
  2088. if ($errorforthisaction) {
  2089. $errorforactions++;
  2090. } else {
  2091. $result = $thirdpartystatic->create($user);
  2092. if ($result <= 0) {
  2093. $errorforactions++;
  2094. $this->error = $thirdpartystatic->error;
  2095. $this->errors = $thirdpartystatic->errors;
  2096. } else {
  2097. $operationslog .= '<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
  2098. }
  2099. }
  2100. }
  2101. } else {
  2102. dol_syslog("One and only one existing third party has been found");
  2103. $operationslog .= '<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id);
  2104. }
  2105. }
  2106. }
  2107. } elseif ($operation['type'] == 'loadandcreatecontact') { // Search and create contact
  2108. if (empty($operation['actionparam'])) {
  2109. $errorforactions++;
  2110. $this->error = "Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
  2111. $this->errors[] = $this->error;
  2112. } else {
  2113. $contact_static = new Contact($this->db);
  2114. // Overwrite values with values extracted from source email
  2115. $errorforthisaction = $this->overwritePropertiesOfObject($contact_static, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2116. if ($errorforthisaction) {
  2117. $errorforactions++;
  2118. } else {
  2119. if (!empty($contact_static->email) && $contact_static->email != $from) $from = $contact_static->email;
  2120. $result = $contactstatic->fetch(0, null, '', $from);
  2121. if ($result < 0) {
  2122. $errorforactions++;
  2123. $this->error = 'Error when getting contact with email ' . $from;
  2124. $this->errors[] = $this->error;
  2125. break;
  2126. } elseif ($result == 0) {
  2127. dol_syslog("Contact with email " . $from . " was not found. We try to create it.");
  2128. $contactstatic = new Contact($this->db);
  2129. // Create contact
  2130. $contactstatic->email = $from;
  2131. $operationslog .= '<br>We set property email='.dol_escape_htmltag($from);
  2132. // Overwrite values with values extracted from source email
  2133. $errorforthisaction = $this->overwritePropertiesOfObject($contactstatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2134. if ($errorforthisaction) {
  2135. $errorforactions++;
  2136. } else {
  2137. // Search country by name or code
  2138. if (!empty($contactstatic->country)) {
  2139. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2140. $result = getCountry('', 3, $this->db, '', 1, $contactstatic->country);
  2141. if ($result == 'NotDefined') {
  2142. $errorforactions++;
  2143. $this->error = "Error country not found by this name '" . $contactstatic->country . "'";
  2144. } elseif (!($result > 0)) {
  2145. $errorforactions++;
  2146. $this->error = "Error when search country by this name '" . $contactstatic->country . "'";
  2147. $this->errors[] = $this->db->lasterror();
  2148. } else {
  2149. $contactstatic->country_id = $result;
  2150. $operationslog .= '<br>We set property country_id='.dol_escape_htmltag($result);
  2151. }
  2152. } elseif (!empty($contactstatic->country_code)) {
  2153. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2154. $result = getCountry($contactstatic->country_code, 3, $this->db);
  2155. if ($result == 'NotDefined') {
  2156. $errorforactions++;
  2157. $this->error = "Error country not found by this code '" . $contactstatic->country_code . "'";
  2158. } elseif (!($result > 0)) {
  2159. $errorforactions++;
  2160. $this->error = "Error when search country by this code '" . $contactstatic->country_code . "'";
  2161. $this->errors[] = $this->db->lasterror();
  2162. } else {
  2163. $contactstatic->country_id = $result;
  2164. $operationslog .= '<br>We set property country_id='.dol_escape_htmltag($result);
  2165. }
  2166. }
  2167. if (!$errorforactions) {
  2168. // Search state by name or code (for country if defined)
  2169. if (!empty($contactstatic->state)) {
  2170. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
  2171. $result = dol_getIdFromCode($this->db, $contactstatic->state, 'c_departements', 'nom', 'rowid');
  2172. if (empty($result)) {
  2173. $errorforactions++;
  2174. $this->error = "Error state not found by this name '" . $contactstatic->state . "'";
  2175. } elseif (!($result > 0)) {
  2176. $errorforactions++;
  2177. $this->error = "Error when search state by this name '" . $contactstatic->state . "'";
  2178. $this->errors[] = $this->db->lasterror();
  2179. } else {
  2180. $contactstatic->state_id = $result;
  2181. $operationslog .= '<br>We set property state_id='.dol_escape_htmltag($result);
  2182. }
  2183. } elseif (!empty($contactstatic->state_code)) {
  2184. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
  2185. $result = dol_getIdFromCode($this->db, $contactstatic->state_code, 'c_departements', 'code_departement', 'rowid');
  2186. if (empty($result)) {
  2187. $errorforactions++;
  2188. $this->error = "Error state not found by this code '" . $contactstatic->state_code . "'";
  2189. } elseif (!($result > 0)) {
  2190. $errorforactions++;
  2191. $this->error = "Error when search state by this code '" . $contactstatic->state_code . "'";
  2192. $this->errors[] = $this->db->lasterror();
  2193. } else {
  2194. $contactstatic->state_id = $result;
  2195. $operationslog .= '<br>We set property state_id='.dol_escape_htmltag($result);
  2196. }
  2197. }
  2198. }
  2199. if (!$errorforactions) {
  2200. $result = $contactstatic->create($user);
  2201. if ($result <= 0) {
  2202. $errorforactions++;
  2203. $this->error = $contactstatic->error;
  2204. $this->errors = $contactstatic->errors;
  2205. } else {
  2206. $operationslog .= '<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
  2207. }
  2208. }
  2209. }
  2210. }
  2211. }
  2212. }
  2213. } elseif ($operation['type'] == 'recordevent') {
  2214. // Create event
  2215. $actioncomm = new ActionComm($this->db);
  2216. $alreadycreated = $actioncomm->fetch(0, '', '', $msgid);
  2217. if ($alreadycreated == 0) {
  2218. if ($projectstatic->id > 0) {
  2219. if ($projectfoundby) {
  2220. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby);
  2221. }
  2222. }
  2223. if ($thirdpartystatic->id > 0) {
  2224. if ($thirdpartyfoundby) {
  2225. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2226. }
  2227. }
  2228. if ($contactstatic->id > 0) {
  2229. if ($contactfoundby) {
  2230. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2231. }
  2232. }
  2233. $description = $descriptiontitle;
  2234. $description = dol_concatdesc($description, "-----");
  2235. $description = dol_concatdesc($description, $descriptionmeta);
  2236. $description = dol_concatdesc($description, "-----");
  2237. $description = dol_concatdesc($description, $messagetext);
  2238. $descriptionfull = $description;
  2239. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2240. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2241. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2242. }
  2243. // Insert record of emails sent
  2244. $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
  2245. $actioncomm->code = 'AC_'.$actioncode;
  2246. $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from;
  2247. $actioncomm->note_private = $descriptionfull;
  2248. $actioncomm->fk_project = $projectstatic->id;
  2249. $actioncomm->datep = $date; // date of email
  2250. $actioncomm->datef = $date; // date of email
  2251. $actioncomm->percentage = -1; // Not applicable
  2252. $actioncomm->socid = $thirdpartystatic->id;
  2253. $actioncomm->contact_id = $contactstatic->id;
  2254. $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array());
  2255. $actioncomm->authorid = $user->id; // User saving action
  2256. $actioncomm->userownerid = $user->id; // Owner of action
  2257. // Fields when action is an email (content should be added into note)
  2258. $actioncomm->email_msgid = $msgid;
  2259. $actioncomm->email_from = $fromstring;
  2260. $actioncomm->email_sender = $sender;
  2261. $actioncomm->email_to = $to;
  2262. $actioncomm->email_tocc = $sendtocc;
  2263. $actioncomm->email_tobcc = $sendtobcc;
  2264. $actioncomm->email_subject = $subject;
  2265. $actioncomm->errors_to = '';
  2266. if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) {
  2267. $actioncomm->fk_element = $fk_element_id;
  2268. $actioncomm->elementid = $fk_element_id;
  2269. $actioncomm->elementtype = $fk_element_type;
  2270. if (is_object($objectemail) && $objectemail->module) {
  2271. $actioncomm->elementtype .= '@'.$objectemail->module;
  2272. }
  2273. }
  2274. //$actioncomm->extraparams = $extraparams;
  2275. // Overwrite values with values extracted from source email
  2276. $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2277. //var_dump($fk_element_id);
  2278. //var_dump($fk_element_type);
  2279. //var_dump($alreadycreated);
  2280. //var_dump($operation['type']);
  2281. //var_dump($actioncomm);
  2282. //exit;
  2283. if ($errorforthisaction) {
  2284. $errorforactions++;
  2285. } else {
  2286. $result = $actioncomm->create($user);
  2287. if ($result <= 0) {
  2288. $errorforactions++;
  2289. $this->errors = $actioncomm->errors;
  2290. } else {
  2291. $operationslog .= '<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
  2292. }
  2293. }
  2294. }
  2295. } elseif ($operation['type'] == 'recordjoinpiece') {
  2296. $data = [];
  2297. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2298. foreach ($attachments as $attachment) {
  2299. if ($attachment->getName() === 'undefined') {
  2300. continue;
  2301. }
  2302. $data[$attachment->getName()] = $attachment->getContent();
  2303. }
  2304. } else {
  2305. $pj = getAttachments($imapemail, $connection);
  2306. foreach ($pj as $key => $val) {
  2307. $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection);
  2308. }
  2309. }
  2310. if (count($data) > 0) {
  2311. $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."user WHERE email LIKE '%".$this->db->escape($from)."%'";
  2312. $resql = $this->db->query($sql);
  2313. if ($this->db->num_rows($resql) == 0) {
  2314. $this->errors[] = "User Not allowed to add documents ({$from})";
  2315. }
  2316. $arrayobject = array(
  2317. 'propale' => array('table' => 'propal',
  2318. 'fields' => array('ref'),
  2319. 'class' => 'comm/propal/class/propal.class.php',
  2320. 'object' => 'Propal'),
  2321. 'holiday' => array('table' => 'holiday',
  2322. 'fields' => array('ref'),
  2323. 'class' => 'holiday/class/holiday.class.php',
  2324. 'object' => 'Holiday'),
  2325. 'expensereport' => array('table' => 'expensereport',
  2326. 'fields' => array('ref'),
  2327. 'class' => 'expensereport/class/expensereport.class.php',
  2328. 'object' => 'ExpenseReport'),
  2329. 'recruitment/recruitmentjobposition' => array('table' => 'recruitment_recruitmentjobposition',
  2330. 'fields' => array('ref'),
  2331. 'class' => 'recruitment/class/recruitmentjobposition.class.php',
  2332. 'object' => 'RecruitmentJobPosition'),
  2333. 'recruitment/recruitmentcandidature' => array('table' => 'recruitment_recruitmentcandidature',
  2334. 'fields' => array('ref'),
  2335. 'class' => 'recruitment/class/recruitmentcandidature.class.php',
  2336. 'object' => ' RecruitmentCandidature'),
  2337. 'societe' => array('table' => 'societe',
  2338. 'fields' => array('code_client', 'code_fournisseur'),
  2339. 'class' => 'societe/class/societe.class.php',
  2340. 'object' => 'Societe'),
  2341. 'commande' => array('table' => 'commande',
  2342. 'fields' => array('ref'),
  2343. 'class' => 'commande/class/commande.class.php',
  2344. 'object' => 'Commande'),
  2345. 'expedition' => array('table' => 'expedition',
  2346. 'fields' => array('ref'),
  2347. 'class' => 'expedition/class/expedition.class.php',
  2348. 'object' => 'Expedition'),
  2349. 'contract' => array('table' => 'contrat',
  2350. 'fields' => array('ref'),
  2351. 'class' => 'contrat/class/contrat.class.php',
  2352. 'object' => 'Contrat'),
  2353. 'fichinter' => array('table' => 'fichinter',
  2354. 'fields' => array('ref'),
  2355. 'class' => 'fichinter/class/fichinter.class.php',
  2356. 'object' => 'Fichinter'),
  2357. 'ticket' => array('table' => 'ticket',
  2358. 'fields' => array('ref'),
  2359. 'class' => 'ticket/class/ticket.class.php',
  2360. 'object' => 'Ticket'),
  2361. 'knowledgemanagement' => array('table' => 'knowledgemanagement_knowledgerecord',
  2362. 'fields' => array('ref'),
  2363. 'class' => 'knowledgemanagement/class/knowledgemanagement.class.php',
  2364. 'object' => 'KnowledgeRecord'),
  2365. 'supplier_proposal' => array('table' => 'supplier_proposal',
  2366. 'fields' => array('ref'),
  2367. 'class' => 'supplier_proposal/class/supplier_proposal.class.php',
  2368. 'object' => 'SupplierProposal'),
  2369. 'fournisseur/commande' => array('table' => 'commande_fournisseur',
  2370. 'fields' => array('ref', 'ref_supplier'),
  2371. 'class' => 'fourn/class/fournisseur.commande.class.php',
  2372. 'object' => 'SupplierProposal'),
  2373. 'facture' => array('table' => 'facture',
  2374. 'fields' => array('ref'),
  2375. 'class' => 'compta/facture/class/facture.class.php',
  2376. 'object' => 'Facture'),
  2377. 'fournisseur/facture' => array('table' => 'facture_fourn',
  2378. 'fields' => array('ref', 'ref_client'),
  2379. 'class' => 'fourn/class/fournisseur.facture.class.php',
  2380. 'object' => 'FactureFournisseur'),
  2381. 'produit' => array('table' => 'product',
  2382. 'fields' => array('ref'),
  2383. 'class' => 'product/class/product.class.php',
  2384. 'object' => 'Product'),
  2385. 'productlot' => array('table' => 'product_lot',
  2386. 'fields' => array('batch'),
  2387. 'class' => 'product/stock/class/productlot.class.php',
  2388. 'object' => 'Productlot'),
  2389. 'projet' => array('table' => 'projet',
  2390. 'fields' => array('ref'),
  2391. 'class' => 'projet/class/projet.class.php',
  2392. 'object' => 'Project'),
  2393. 'projet_task' => array('table' => 'projet_task',
  2394. 'fields' => array('ref'),
  2395. 'class' => 'projet/class/task.class.php',
  2396. 'object' => 'Task'),
  2397. 'ressource' => array('table' => 'resource',
  2398. 'fields' => array('ref'),
  2399. 'class' => 'ressource/class/dolressource.class.php',
  2400. 'object' => 'Dolresource'),
  2401. 'bom' => array('table' => 'bom_bom',
  2402. 'fields' => array('ref'),
  2403. 'class' => 'bom/class/bom.class.php',
  2404. 'object' => 'BOM'),
  2405. 'mrp' => array('table' => 'mrp_mo',
  2406. 'fields' => array('ref'),
  2407. 'class' => 'mrp/class/mo.class.php',
  2408. 'object' => 'Mo'),
  2409. );
  2410. if (!is_object($hookmanager)) {
  2411. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  2412. $hookmanager = new HookManager($this->db);
  2413. }
  2414. $hookmanager->initHooks(array('emailcolector'));
  2415. $parameters = array('arrayobject' => $arrayobject);
  2416. $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks
  2417. if ($reshook > 0) {
  2418. $arrayobject = $hookmanager->resArray;
  2419. }
  2420. $resultobj = array();
  2421. foreach ($arrayobject as $key => $objectdesc) {
  2422. $sql = 'SELECT DISTINCT t.rowid ';
  2423. $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectdesc['table'] . ' AS t';
  2424. $sql .= ' WHERE ';
  2425. foreach ($objectdesc['fields'] as $field) {
  2426. $sql .= "'" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $field . ", '%') OR ";
  2427. }
  2428. $sql = substr($sql, 0, -4);
  2429. $ressqlobj = $this->db->query($sql);
  2430. if ($ressqlobj) {
  2431. while ($obj = $this->db->fetch_object($ressqlobj)) {
  2432. $resultobj[$key][] = $obj->rowid;
  2433. }
  2434. }
  2435. }
  2436. $dirs = array();
  2437. foreach ($resultobj as $mod => $ids) {
  2438. $moddesc = $arrayobject[$mod];
  2439. $elementpath = $mod;
  2440. dol_include_once($moddesc['class']);
  2441. $objectmanaged = new $moddesc['object']($this->db);
  2442. foreach ($ids as $val) {
  2443. $res = $objectmanaged->fetch($val);
  2444. if ($res) {
  2445. $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : '');
  2446. $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/';
  2447. } else {
  2448. $this->errors[] = 'object not found';
  2449. }
  2450. }
  2451. }
  2452. foreach ($dirs as $target) {
  2453. $prefix = $this->actions[$this->id]['actionparam'];
  2454. foreach ($data as $filename => $content) {
  2455. $resr = saveAttachment($target, $prefix . '_' . $filename, $content);
  2456. if ($resr == -1) {
  2457. $this->errors[] = 'Doc not saved';
  2458. }
  2459. }
  2460. }
  2461. $operationslog .= '<br>Save attachment files on disk';
  2462. } else {
  2463. $this->errors[] = 'no joined piece';
  2464. $operationslog .= '<br>No joinded files';
  2465. }
  2466. } elseif ($operation['type'] == 'project') {
  2467. // Create project / lead
  2468. $projecttocreate = new Project($this->db);
  2469. $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid);
  2470. if ($alreadycreated == 0) {
  2471. if ($thirdpartystatic->id > 0) {
  2472. $projecttocreate->socid = $thirdpartystatic->id;
  2473. if ($thirdpartyfoundby) {
  2474. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2475. }
  2476. }
  2477. if ($contactstatic->id > 0) {
  2478. $projecttocreate->contact_id = $contactstatic->id;
  2479. if ($contactfoundby) {
  2480. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2481. }
  2482. }
  2483. $description = $descriptiontitle;
  2484. $description = dol_concatdesc($description, "-----");
  2485. $description = dol_concatdesc($description, $descriptionmeta);
  2486. $description = dol_concatdesc($description, "-----");
  2487. $description = dol_concatdesc($description, $messagetext);
  2488. $descriptionfull = $description;
  2489. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2490. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2491. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2492. }
  2493. $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
  2494. $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
  2495. $projecttocreate->title = $subject;
  2496. $projecttocreate->date_start = $date; // date of email
  2497. $projecttocreate->date_end = '';
  2498. $projecttocreate->opp_status = $id_opp_status;
  2499. $projecttocreate->opp_percent = $percent_opp_status;
  2500. $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...');
  2501. $projecttocreate->note_private = $descriptionfull;
  2502. $projecttocreate->entity = $conf->entity;
  2503. $projecttocreate->email_msgid = $msgid;
  2504. $savesocid = $projecttocreate->socid;
  2505. // Overwrite values with values extracted from source email.
  2506. // This may overwrite any $projecttocreate->xxx properties.
  2507. $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2508. // Set project ref if not yet defined
  2509. if (empty($projecttocreate->ref)) {
  2510. // Get next Ref
  2511. $defaultref = '';
  2512. $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
  2513. // Search template files
  2514. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2515. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2516. foreach ($dirmodels as $reldir) {
  2517. $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0);
  2518. if (file_exists($file)) {
  2519. $filefound = 1;
  2520. $classname = $modele;
  2521. break;
  2522. }
  2523. }
  2524. if ($filefound) {
  2525. if ($savesocid > 0) {
  2526. if ($savesocid != $projecttocreate->socid) {
  2527. $errorforactions++;
  2528. setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$projecttocreate->socid.') by setting socid in operation with a different value', null, 'errors');
  2529. }
  2530. } else {
  2531. if ($projecttocreate->socid > 0) {
  2532. $thirdpartystatic->fetch($projecttocreate->socid);
  2533. }
  2534. }
  2535. $result = dol_include_once($reldir."core/modules/project/".$modele.'.php');
  2536. $modModuleToUseForNextValue = new $classname;
  2537. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
  2538. }
  2539. $projecttocreate->ref = $defaultref;
  2540. }
  2541. if ($errorforthisaction) {
  2542. $errorforactions++;
  2543. } else {
  2544. if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
  2545. $errorforactions++;
  2546. $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
  2547. $operationslog .= '<br>'.$this->error;
  2548. } else {
  2549. // Create project
  2550. $result = $projecttocreate->create($user);
  2551. if ($result <= 0) {
  2552. $errorforactions++;
  2553. $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
  2554. $this->errors = $projecttocreate->errors;
  2555. $operationslog .= '<br>'.$this->error;
  2556. } else {
  2557. if ($attachments) {
  2558. $destdir = $conf->project->dir_output.'/'.$projecttocreate->ref;
  2559. if (!dol_is_dir($destdir)) {
  2560. dol_mkdir($destdir);
  2561. }
  2562. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2563. foreach ($attachments as $attachment) {
  2564. $attachment->save($destdir.'/');
  2565. }
  2566. } else {
  2567. $this->getmsg($connection, $imapemail, $destdir);
  2568. }
  2569. $operationslog .= '<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
  2570. } else {
  2571. $operationslog .= '<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
  2572. }
  2573. }
  2574. }
  2575. }
  2576. } else {
  2577. dol_syslog("Project already exists for msgid = ".dol_escape_htmltag($msgid).", so we do not recreate it.");
  2578. $operationslog .= '<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
  2579. }
  2580. } elseif ($operation['type'] == 'ticket') {
  2581. // Create ticket
  2582. $tickettocreate = new Ticket($this->db);
  2583. $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid);
  2584. if ($alreadycreated == 0) {
  2585. if ($thirdpartystatic->id > 0) {
  2586. $tickettocreate->socid = $thirdpartystatic->id;
  2587. $tickettocreate->fk_soc = $thirdpartystatic->id;
  2588. if ($thirdpartyfoundby) {
  2589. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2590. }
  2591. }
  2592. if ($contactstatic->id > 0) {
  2593. $tickettocreate->contact_id = $contactstatic->id;
  2594. if ($contactfoundby) {
  2595. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2596. }
  2597. }
  2598. $description = $descriptiontitle;
  2599. $description = dol_concatdesc($description, "-----");
  2600. $description = dol_concatdesc($description, $descriptionmeta);
  2601. $description = dol_concatdesc($description, "-----");
  2602. $description = dol_concatdesc($description, $messagetext);
  2603. $descriptionfull = $description;
  2604. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2605. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2606. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2607. }
  2608. $tickettocreate->subject = $subject;
  2609. $tickettocreate->message = $description;
  2610. $tickettocreate->type_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_type', 'use_default', 'code', 1));
  2611. $tickettocreate->category_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_category', 'use_default', 'code', 1));
  2612. $tickettocreate->severity_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE : dol_getIdFromCode($this->db, 1, 'c_ticket_severity', 'use_default', 'code', 1));
  2613. $tickettocreate->origin_email = $from;
  2614. $tickettocreate->fk_user_create = $user->id;
  2615. $tickettocreate->datec = dol_now();
  2616. $tickettocreate->fk_project = $projectstatic->id;
  2617. $tickettocreate->notify_tiers_at_create = 0;
  2618. $tickettocreate->note_private = $descriptionfull;
  2619. $tickettocreate->entity = $conf->entity;
  2620. $tickettocreate->email_msgid = $msgid;
  2621. $tickettocreate->email_date = $date;
  2622. //$tickettocreate->fk_contact = $contactstatic->id;
  2623. $savesocid = $tickettocreate->socid;
  2624. // Overwrite values with values extracted from source email.
  2625. // This may overwrite any $projecttocreate->xxx properties.
  2626. $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2627. // Set ticket ref if not yet defined
  2628. if (empty($tickettocreate->ref)) {
  2629. // Get next Ref
  2630. $defaultref = '';
  2631. $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON;
  2632. // Search template files
  2633. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2634. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2635. foreach ($dirmodels as $reldir) {
  2636. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2637. if (file_exists($file)) {
  2638. $filefound = 1;
  2639. $classname = $modele;
  2640. break;
  2641. }
  2642. }
  2643. if ($filefound) {
  2644. if ($savesocid > 0) {
  2645. if ($savesocid != $tickettocreate->socid) {
  2646. $errorforactions++;
  2647. setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$tickettocreate->socid.') by setting socid in operation with a different value', null, 'errors');
  2648. }
  2649. } else {
  2650. if ($tickettocreate->socid > 0) {
  2651. $thirdpartystatic->fetch($tickettocreate->socid);
  2652. }
  2653. }
  2654. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2655. $modModuleToUseForNextValue = new $classname;
  2656. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
  2657. }
  2658. $tickettocreate->ref = $defaultref;
  2659. }
  2660. if ($errorforthisaction) {
  2661. $errorforactions++;
  2662. } else {
  2663. if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
  2664. $errorforactions++;
  2665. $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
  2666. } else {
  2667. // Create project
  2668. $result = $tickettocreate->create($user);
  2669. if ($result <= 0) {
  2670. $errorforactions++;
  2671. $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error);
  2672. $this->errors = $tickettocreate->errors;
  2673. } else {
  2674. if ($attachments) {
  2675. $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref;
  2676. if (!dol_is_dir($destdir)) {
  2677. dol_mkdir($destdir);
  2678. }
  2679. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2680. foreach ($attachments as $attachment) {
  2681. $attachment->save($destdir.'/');
  2682. }
  2683. } else {
  2684. $this->getmsg($connection, $imapemail, $destdir);
  2685. }
  2686. $operationslog .= '<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
  2687. } else {
  2688. $operationslog .= '<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
  2689. }
  2690. }
  2691. }
  2692. }
  2693. }
  2694. } elseif ($operation['type'] == 'candidature') {
  2695. // Create candidature
  2696. $candidaturetocreate = new RecruitmentCandidature($this->db);
  2697. $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid);
  2698. if ($alreadycreated == 0) {
  2699. $description = $descriptiontitle;
  2700. $description = dol_concatdesc($description, "-----");
  2701. $description = dol_concatdesc($description, $descriptionmeta);
  2702. $description = dol_concatdesc($description, "-----");
  2703. $description = dol_concatdesc($description, $messagetext);
  2704. $descriptionfull = $description;
  2705. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2706. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2707. $candidaturetocreate->subject = $subject;
  2708. $candidaturetocreate->message = $description;
  2709. $candidaturetocreate->type_code = 0;
  2710. $candidaturetocreate->category_code = null;
  2711. $candidaturetocreate->severity_code = null;
  2712. $candidaturetocreate->email = $from;
  2713. //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from;
  2714. $candidaturetocreate->fk_user_creat = $user->id;
  2715. $candidaturetocreate->date_creation = dol_now();
  2716. $candidaturetocreate->fk_project = $projectstatic->id;
  2717. $candidaturetocreate->description = $description;
  2718. $candidaturetocreate->note_private = $descriptionfull;
  2719. $candidaturetocreate->entity = $conf->entity;
  2720. $candidaturetocreate->email_msgid = $msgid;
  2721. $candidaturetocreate->email_date = $date; // date of email
  2722. $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
  2723. //$candidaturetocreate->fk_contact = $contactstatic->id;
  2724. // Overwrite values with values extracted from source email.
  2725. // This may overwrite any $projecttocreate->xxx properties.
  2726. $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2727. // Set candidature ref if not yet defined
  2728. /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status
  2729. {
  2730. // Get next Ref
  2731. $defaultref = '';
  2732. $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON;
  2733. // Search template files
  2734. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2735. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2736. foreach ($dirmodels as $reldir)
  2737. {
  2738. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2739. if (file_exists($file)) {
  2740. $filefound = 1;
  2741. $classname = $modele;
  2742. break;
  2743. }
  2744. }
  2745. if ($filefound) {
  2746. if ($savesocid > 0) {
  2747. if ($savesocid != $candidaturetocreate->socid) {
  2748. $errorforactions++;
  2749. setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$candidaturetocreate->socid.') by setting socid in operation with a different value', null, 'errors');
  2750. }
  2751. } else {
  2752. if ($candidaturetocreate->socid > 0)
  2753. {
  2754. $thirdpartystatic->fetch($candidaturetocreate->socid);
  2755. }
  2756. }
  2757. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2758. $modModuleToUseForNextValue = new $classname;
  2759. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
  2760. }
  2761. $candidaturetocreate->ref = $defaultref;
  2762. }*/
  2763. if ($errorforthisaction) {
  2764. $errorforactions++;
  2765. } else {
  2766. // Create project
  2767. $result = $candidaturetocreate->create($user);
  2768. if ($result <= 0) {
  2769. $errorforactions++;
  2770. $this->error = 'Failed to create candidature: '.join(', ', $candidaturetocreate->errors);
  2771. $this->errors = $candidaturetocreate->errors;
  2772. }
  2773. $operationslog .= '<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
  2774. }
  2775. }
  2776. } elseif (substr($operation['type'], 0, 4) == 'hook') {
  2777. // Create event specific on hook
  2778. // this code action is hook..... for support this call
  2779. if (!is_object($hookmanager)) {
  2780. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  2781. $hookmanager = new HookManager($this->db);
  2782. }
  2783. $parameters = array(
  2784. 'connection'=> $connection,
  2785. 'imapemail'=>$imapemail,
  2786. 'overview'=>$overview,
  2787. 'from' => $from,
  2788. 'fromtext' => $fromtext,
  2789. 'actionparam'=> $operation['actionparam'],
  2790. 'thirdpartyid' => $thirdpartyid,
  2791. 'objectid'=> $objectid,
  2792. 'objectemail'=> $objectemail,
  2793. 'messagetext'=>$messagetext,
  2794. 'subject'=>$subject,
  2795. 'header'=>$header,
  2796. 'attachments'=>$attachments,
  2797. );
  2798. $reshook = $hookmanager->executeHooks('doCollectImapOneCollector', $parameters, $this, $operation['type']);
  2799. if ($reshook < 0) {
  2800. $errorforthisaction++;
  2801. $this->error = $hookmanager->resPrint;
  2802. }
  2803. if ($errorforthisaction) {
  2804. $errorforactions++;
  2805. $operationslog .= '<br>Hook doCollectImapOneCollector executed with error';
  2806. } else {
  2807. $operationslog .= '<br>Hook doCollectImapOneCollector executed without error';
  2808. }
  2809. }
  2810. if (!$errorforactions) {
  2811. $nbactiondoneforemail++;
  2812. }
  2813. }
  2814. }
  2815. // Error for email or not ?
  2816. if (!$errorforactions) {
  2817. if (!empty($targetdir)) {
  2818. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2819. // Move mail using PHP-IMAP
  2820. dol_syslog("EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get('subject'))." to ".$targetdir, LOG_DEBUG);
  2821. if (empty($mode)) {
  2822. $imapemail->move($targetdir);
  2823. }
  2824. } else {
  2825. dol_syslog("EmailCollector::doCollectOneCollector move message ".($this->uidAsString($imapemail))." to ".$connectstringtarget, LOG_DEBUG);
  2826. $operationslog .= '<br>Move mail '.($this->uidAsString($imapemail)).' - '.$msgid;
  2827. $arrayofemailtodelete[$imapemail] = $msgid;
  2828. }
  2829. } else {
  2830. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2831. dol_syslog("EmailCollector::doCollectOneCollector message '".($imapemail->getHeader()->get('subject'))."' using this->host=".$this->host.", this->access_type=".$this->acces_type." was set to read", LOG_DEBUG);
  2832. } else {
  2833. dol_syslog("EmailCollector::doCollectOneCollector message ".($this->uidAsString($imapemail))." to ".$connectstringtarget." was set to read", LOG_DEBUG);
  2834. }
  2835. }
  2836. } else {
  2837. $errorforemail++;
  2838. }
  2839. unset($objectemail);
  2840. unset($projectstatic);
  2841. unset($thirdpartystatic);
  2842. unset($contactstatic);
  2843. $nbemailprocessed++;
  2844. if (!$errorforemail) {
  2845. $nbactiondone += $nbactiondoneforemail;
  2846. $nbemailok++;
  2847. if (empty($mode)) {
  2848. $this->db->commit();
  2849. } else {
  2850. $this->db->rollback();
  2851. }
  2852. // Stop the loop to process email if we reach maximum collected per collect
  2853. if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
  2854. dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok." collected with success, so we stop this collector now.");
  2855. break;
  2856. }
  2857. } else {
  2858. $error++;
  2859. $this->db->rollback();
  2860. }
  2861. }
  2862. $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
  2863. dol_syslog("End of loop on emails", LOG_INFO, -1);
  2864. } else {
  2865. $langs->load("admin");
  2866. $output = $langs->trans('NoNewEmailToProcess');
  2867. }
  2868. // Disconnect
  2869. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2870. $client->disconnect();
  2871. } else {
  2872. foreach ($arrayofemailtodelete as $imapemail => $msgid) {
  2873. dol_syslog("EmailCollect::doCollectOneCollector delete email ".$imapemail." ".$msgid);
  2874. $operationslog .= "<br> delete email ".$imapemail." ".$msgid;
  2875. if (empty($mode) && empty($error)) {
  2876. $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
  2877. if ($res == false) {
  2878. $errorforemail++;
  2879. $this->error = imap_last_error();
  2880. $this->errors[] = $this->error;
  2881. $operationslog .= '<br>Error in move '.$this->error;
  2882. dol_syslog(imap_last_error());
  2883. }
  2884. }
  2885. }
  2886. if (empty($mode) && empty($error)) {
  2887. dol_syslog("Expunge", LOG_DEBUG);
  2888. $operationslog .= "<br>Expunge";
  2889. imap_expunge($connection); // To validate all moves
  2890. }
  2891. imap_close($connection);
  2892. }
  2893. $this->datelastresult = $now;
  2894. $this->lastresult = $output;
  2895. $this->debuginfo .= 'IMAP search string used : '.$search;
  2896. if ($searchhead) {
  2897. $this->debuginfo .= '<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
  2898. }
  2899. if ($operationslog) {
  2900. $this->debuginfo .= $operationslog;
  2901. }
  2902. if (empty($error) && empty($mode)) {
  2903. $this->datelastok = $now;
  2904. }
  2905. if (!empty($this->errors)) {
  2906. $this->lastresult .= "<br>".join("<br>", $this->errors);
  2907. }
  2908. $this->codelastresult = ($error ? 'KO' : 'OK');
  2909. if (empty($mode)) {
  2910. $this->update($user);
  2911. }
  2912. dol_syslog("EmailCollector::doCollectOneCollector end", LOG_INFO);
  2913. return $error ? -1 : 1;
  2914. }
  2915. // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation
  2916. /**
  2917. * getmsg
  2918. *
  2919. * @param Object $mbox Structure
  2920. * @param string $mid UID email
  2921. * @param string $destdir Target dir for attachments
  2922. * @return void
  2923. */
  2924. private function getmsg($mbox, $mid, $destdir = '')
  2925. {
  2926. // input $mbox = IMAP stream, $mid = message id
  2927. // output all the following:
  2928. global $charset, $htmlmsg, $plainmsg, $attachments;
  2929. $htmlmsg = $plainmsg = $charset = '';
  2930. $attachments = array();
  2931. // HEADER
  2932. //$h = imap_header($mbox,$mid);
  2933. // add code here to get date, from, to, cc, subject...
  2934. // BODY
  2935. $s = imap_fetchstructure($mbox, $mid, FT_UID);
  2936. if (!$s->parts) {
  2937. // simple
  2938. $this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number
  2939. } else {
  2940. // multipart: cycle through each part
  2941. foreach ($s->parts as $partno0 => $p) {
  2942. $this->getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
  2943. }
  2944. }
  2945. }
  2946. /* partno string
  2947. 0 multipart/mixed
  2948. 1 multipart/alternative
  2949. 1.1 text/plain
  2950. 1.2 text/html
  2951. 2 message/rfc822
  2952. 2 multipart/mixed
  2953. 2.1 multipart/alternative
  2954. 2.1.1 text/plain
  2955. 2.1.2 text/html
  2956. 2.2 message/rfc822
  2957. 2.2 multipart/alternative
  2958. 2.2.1 text/plain
  2959. 2.2.2 text/html
  2960. */
  2961. /**
  2962. * Sub function for getpart(). Only called by createPartArray() and itself.
  2963. *
  2964. * @param Object $mbox Structure
  2965. * @param string $mid Part no
  2966. * @param Object $p Object p
  2967. * @param string $partno Partno
  2968. * @param string $destdir Target dir for attachments
  2969. * @return void
  2970. */
  2971. private function getpart($mbox, $mid, $p, $partno, $destdir = '')
  2972. {
  2973. // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
  2974. global $htmlmsg, $plainmsg, $charset, $attachments;
  2975. // DECODE DATA
  2976. $data = ($partno) ?
  2977. imap_fetchbody($mbox, $mid, $partno, FT_UID) : // multipart
  2978. imap_body($mbox, $mid, FT_UID); // simple
  2979. // Any part may be encoded, even plain text messages, so check everything.
  2980. if ($p->encoding == 4) {
  2981. $data = quoted_printable_decode($data);
  2982. } elseif ($p->encoding == 3) {
  2983. $data = base64_decode($data);
  2984. }
  2985. // PARAMETERS
  2986. // get all parameters, like charset, filenames of attachments, etc.
  2987. $params = array();
  2988. if ($p->parameters) {
  2989. foreach ($p->parameters as $x) {
  2990. $params[strtolower($x->attribute)] = $x->value;
  2991. }
  2992. }
  2993. if ($p->dparameters) {
  2994. foreach ($p->dparameters as $x) {
  2995. $params[strtolower($x->attribute)] = $x->value;
  2996. }
  2997. }
  2998. // ATTACHMENT
  2999. // Any part with a filename is an attachment,
  3000. // so an attached text file (type 0) is not mistaken as the message.
  3001. if ($params['filename'] || $params['name']) {
  3002. // filename may be given as 'Filename' or 'Name' or both
  3003. $filename = ($params['filename']) ? $params['filename'] : $params['name'];
  3004. // filename may be encoded, so see imap_mime_header_decode()
  3005. $attachments[$filename] = $data; // this is a problem if two files have same name
  3006. // Get file name (with extension)
  3007. $file_name_complete = $params['filename'];
  3008. $destination = $destdir.'/'.$file_name_complete;
  3009. // Extract file extension
  3010. $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
  3011. // Extract file name without extension
  3012. $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
  3013. // Save an original file name variable to track while renaming if file already exists
  3014. $file_name_original = $file_name;
  3015. // Increment file name by 1
  3016. $num = 1;
  3017. /**
  3018. * Check if the same file name already exists in the upload folder,
  3019. * append increment number to the original filename
  3020. */
  3021. while (file_exists($destdir."/".$file_name.".".$extension)) {
  3022. $file_name = $file_name_original . ' (' . $num . ')';
  3023. $file_name_complete = $file_name . "." . $extension;
  3024. $destination = $destdir.'/'.$file_name_complete;
  3025. $num++;
  3026. }
  3027. $destination = dol_sanitizePathName($destination);
  3028. file_put_contents($destination, $data);
  3029. }
  3030. // TEXT
  3031. if ($p->type == 0 && $data) {
  3032. if (!empty($params['charset'])) {
  3033. $data = $this->convertStringEncoding($data, $params['charset']);
  3034. }
  3035. // Messages may be split in different parts because of inline attachments,
  3036. // so append parts together with blank row.
  3037. if (strtolower($p->subtype) == 'plain') {
  3038. $plainmsg .= trim($data)."\n\n";
  3039. } else {
  3040. $htmlmsg .= $data."<br><br>";
  3041. }
  3042. $charset = $params['charset']; // assume all parts are same charset
  3043. } elseif ($p->type == 2 && $data) {
  3044. // EMBEDDED MESSAGE
  3045. // Many bounce notifications embed the original message as type 2,
  3046. // but AOL uses type 1 (multipart), which is not handled here.
  3047. // There are no PHP functions to parse embedded messages,
  3048. // so this just appends the raw source to the main message.
  3049. if (!empty($params['charset'])) {
  3050. $data = $this->convertStringEncoding($data, $params['charset']);
  3051. }
  3052. $plainmsg .= $data."\n\n";
  3053. }
  3054. // SUBPART RECURSION
  3055. if ($p->parts) {
  3056. foreach ($p->parts as $partno0 => $p2) {
  3057. $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1)); // 1.2, 1.2.1, etc.
  3058. }
  3059. }
  3060. }
  3061. /**
  3062. * Converts a string from one encoding to another.
  3063. *
  3064. * @param string $string String to convert
  3065. * @param string $fromEncoding String encoding
  3066. * @param string $toEncoding String return encoding
  3067. * @return string Converted string if conversion was successful, or the original string if not
  3068. * @throws Exception
  3069. */
  3070. protected function convertStringEncoding($string, $fromEncoding, $toEncoding = 'UTF-8')
  3071. {
  3072. if (!$string || $fromEncoding == $toEncoding) {
  3073. return $string;
  3074. }
  3075. $convertedString = function_exists('iconv') ? @iconv($fromEncoding, $toEncoding.'//IGNORE', $string) : null;
  3076. if (!$convertedString && extension_loaded('mbstring')) {
  3077. $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
  3078. }
  3079. if (!$convertedString) {
  3080. throw new Exception('Mime string encoding conversion failed');
  3081. }
  3082. return $convertedString;
  3083. }
  3084. /**
  3085. * Decode a subject string according to RFC2047
  3086. * Example: '=?Windows-1252?Q?RE=A0:_ABC?=' => 'RE : ABC...'
  3087. * Example: '=?UTF-8?Q?A=C3=A9B?=' => 'AéB'
  3088. * Example: '=?UTF-8?B?2KLYstmF2KfbjNi0?=' =>
  3089. * Example: '=?utf-8?B?UkU6IG1vZHVsZSBkb2xpYmFyciBnZXN0aW9ubmFpcmUgZGUgZmljaGllcnMg?= =?utf-8?B?UsOpZsOpcmVuY2UgZGUgbGEgY29tbWFuZGUgVFVHRURJSklSIOKAkyBwYXNz?= =?utf-8?B?w6llIGxlIDIyLzA0LzIwMjA=?='
  3090. *
  3091. * @param string $subject Subject
  3092. * @return string Decoded subject (in UTF-8)
  3093. */
  3094. protected function decodeSMTPSubject($subject)
  3095. {
  3096. // Decode $overview[0]->subject according to RFC2047
  3097. // Can use also imap_mime_header_decode($str)
  3098. // Can use also mb_decode_mimeheader($str)
  3099. // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8')
  3100. if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) {
  3101. $elements = imap_mime_header_decode($subject);
  3102. $newstring = '';
  3103. if (!empty($elements)) {
  3104. $num = count($elements);
  3105. for ($i = 0; $i < $num; $i++) {
  3106. $stringinutf8 = (in_array(strtoupper($elements[$i]->charset), array('DEFAULT', 'UTF-8')) ? $elements[$i]->text : iconv_mime_decode($elements[$i]->text, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $elements[$i]->charset));
  3107. $newstring .= $stringinutf8;
  3108. }
  3109. $subject = $newstring;
  3110. }
  3111. } elseif (!function_exists('mb_decode_mimeheader')) {
  3112. $subject = mb_decode_mimeheader($subject);
  3113. } elseif (function_exists('iconv_mime_decode')) {
  3114. $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
  3115. }
  3116. return $subject;
  3117. }
  3118. /**
  3119. * Remove EMoji from email content
  3120. *
  3121. * @param string $text String to sanitize
  3122. * @return string Sanitized string
  3123. */
  3124. protected function removeEmoji($text)
  3125. {
  3126. // Supprimer les caractères emoji en utilisant une expression régulière
  3127. $text = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $text);
  3128. $text = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $text);
  3129. $text = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $text);
  3130. $text = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $text);
  3131. $text = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $text);
  3132. $text = preg_replace('/[\x{1F900}-\x{1F9FF}]/u', '', $text);
  3133. $text = preg_replace('/[\x{1F1E0}-\x{1F1FF}]/u', '', $text);
  3134. return $text;
  3135. }
  3136. /**
  3137. * Get UID of message as a string
  3138. *
  3139. * @param int|Webklex\PHPIMAP\Message $imapemail UID as int (if native IMAP) or as object (if external library)
  3140. * @return string UID as string
  3141. */
  3142. protected function uidAsString($imapemail)
  3143. {
  3144. if (is_object($imapemail)) {
  3145. return $imapemail->getAttributes()["uid"];
  3146. } else {
  3147. return (string) $imapemail;
  3148. }
  3149. }
  3150. }