emailcollector.class.php 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537
  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. $searchfilterexcludebody = '';
  954. $searchfilterexcludesubject = '';
  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. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  972. if ($this->acces_type == 1) {
  973. // Mode OAUth2 with PHP-IMAP
  974. require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
  975. $keyforsupportedoauth2array = $this->oauth_service;
  976. if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
  977. $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
  978. } else {
  979. $keyforprovider = '';
  980. }
  981. $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
  982. $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
  983. $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
  984. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  985. //$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;
  986. //dol_syslog($debugtext);
  987. $token = '';
  988. $storage = new DoliStorage($db, $conf, $keyforprovider);
  989. try {
  990. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  991. $expire = true;
  992. // Is token expired or will token expire in the next 30 seconds
  993. // if (is_object($tokenobj)) {
  994. // $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
  995. // }
  996. // Token expired so we refresh it
  997. if (is_object($tokenobj) && $expire) {
  998. $credentials = new Credentials(
  999. getDolGlobalString('OAUTH_'.$this->oauth_service.'_ID'),
  1000. getDolGlobalString('OAUTH_'.$this->oauth_service.'_SECRET'),
  1001. getDolGlobalString('OAUTH_'.$this->oauth_service.'_URLAUTHORIZE')
  1002. );
  1003. $serviceFactory = new \OAuth\ServiceFactory();
  1004. $oauthname = explode('-', $OAUTH_SERVICENAME);
  1005. // ex service is Google-Emails we need only the first part Google
  1006. $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
  1007. // We have to save the token because Google give it only once
  1008. $refreshtoken = $tokenobj->getRefreshToken();
  1009. $tokenobj = $apiService->refreshAccessToken($tokenobj);
  1010. $tokenobj->setRefreshToken($refreshtoken);
  1011. $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
  1012. }
  1013. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  1014. if (is_object($tokenobj)) {
  1015. $token = $tokenobj->getAccessToken();
  1016. } else {
  1017. $this->error = "Token not found";
  1018. return -1;
  1019. }
  1020. } catch (Exception $e) {
  1021. // Return an error if token not found
  1022. $this->error = $e->getMessage();
  1023. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  1024. return -1;
  1025. }
  1026. $cm = new ClientManager();
  1027. $client = $cm->make([
  1028. 'host' => $this->host,
  1029. 'port' => $this->port,
  1030. 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
  1031. 'validate_cert' => true,
  1032. 'protocol' => 'imap',
  1033. 'username' => $this->login,
  1034. 'password' => $token,
  1035. 'authentication' => "oauth",
  1036. ]);
  1037. } else {
  1038. // Mode login/pass with PHP-IMAP
  1039. $cm = new ClientManager();
  1040. $client = $cm->make([
  1041. 'host' => $this->host,
  1042. 'port' => $this->port,
  1043. 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
  1044. 'validate_cert' => true,
  1045. 'protocol' => 'imap',
  1046. 'username' => $this->login,
  1047. 'password' => $this->password,
  1048. 'authentication' => "login",
  1049. ]);
  1050. }
  1051. try {
  1052. $client->connect();
  1053. } catch (ConnectionFailedException $e) {
  1054. $this->error = $e->getMessage();
  1055. $this->errors[] = $this->error;
  1056. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1057. return -1;
  1058. }
  1059. $host = dol_getprefix('email');
  1060. } else {
  1061. // Use native IMAP functions
  1062. if (!function_exists('imap_open')) {
  1063. $this->error = 'IMAP function not enabled on your PHP';
  1064. return -2;
  1065. }
  1066. $sourcedir = $this->source_directory;
  1067. $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
  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. $searchfilterexcludesubject = 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. $searchfilterexcludebody = 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. $searchfilterexcludesubject = 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. $searchfilterexcludebody = 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((string) $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 ($searchfilterexcludebody) {
  1546. if (preg_match('/'.preg_quote($searchfilterexcludebody, '/').'/ms', $messagetext)) {
  1547. $nbemailprocessed++;
  1548. $operationslog .= '<br>Discarded - Email body contains string '.$searchfilterexcludebody;
  1549. dol_syslog(" Discarded - Email body contains string ".$searchfilterexcludebody);
  1550. continue; // Exclude email
  1551. }
  1552. }
  1553. //var_dump($plainmsg);
  1554. //var_dump($htmlmsg);
  1555. //var_dump($messagetext);
  1556. //var_dump($charset);
  1557. //var_dump($attachments);
  1558. //exit;
  1559. // Parse IMAP email structure
  1560. /*
  1561. $structure = imap_fetchstructure($connection, $imapemail, FT_UID);
  1562. $partplain = $parthtml = -1;
  1563. $encodingplain = $encodinghtml = '';
  1564. $result = createPartArray($structure, '');
  1565. foreach($result as $part)
  1566. {
  1567. // $part['part_object']->type seems 0 for content
  1568. // $part['part_object']->type seems 5 for attachment
  1569. if (empty($part['part_object'])) continue;
  1570. if ($part['part_object']->subtype == 'HTML')
  1571. {
  1572. $parthtml=$part['part_number'];
  1573. if ($part['part_object']->encoding == 4)
  1574. {
  1575. $encodinghtml = 'aaa';
  1576. }
  1577. }
  1578. if ($part['part_object']->subtype == 'PLAIN')
  1579. {
  1580. $partplain=$part['part_number'];
  1581. if ($part['part_object']->encoding == 4)
  1582. {
  1583. $encodingplain = 'rr';
  1584. }
  1585. }
  1586. }
  1587. //var_dump($result);
  1588. //var_dump($partplain);
  1589. //var_dump($parthtml);
  1590. //var_dump($structure);
  1591. //var_dump($parthtml);
  1592. //var_dump($partplain);
  1593. $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK|FTP_UID);
  1594. */
  1595. //var_dump($messagetext);
  1596. //var_dump($structure->parts[0]->parts);
  1597. //print $header;
  1598. //print $messagetext;
  1599. //exit;
  1600. $fromstring = '';
  1601. $replytostring = '';
  1602. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1603. $fromstring = $overview['from'];
  1604. //$replytostring = empty($overview['reply-to']) ? '' : $overview['reply-to'];
  1605. $sender = $overview['sender'];
  1606. $to = $overview['to'];
  1607. $sendtocc = empty($overview['cc']) ? '' : $overview['cc'];
  1608. $sendtobcc = empty($overview['bcc']) ? '' : $overview['bcc'];
  1609. $date = $overview['date'];
  1610. $msgid = str_replace(array('<', '>'), '', $overview['message_id']);
  1611. $subject = $overview['subject'];
  1612. } else {
  1613. $fromstring = $overview[0]->from;
  1614. //$replytostring = empty($overview[0]->replyto) ? '' : $overview[0]->replyto;
  1615. $sender = $overview[0]->sender;
  1616. $to = $overview[0]->to;
  1617. $sendtocc = $overview[0]->cc;
  1618. $sendtobcc = $overview[0]->bcc;
  1619. $date = $overview[0]->udate;
  1620. $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id);
  1621. $subject = $overview[0]->subject;
  1622. //var_dump($msgid);exit;
  1623. }
  1624. if ($searchfilterexcludesubject) {
  1625. if (preg_match('/'.preg_quote($searchfilterexcludesubject, '/').'/ms', $subject)) {
  1626. $nbemailprocessed++;
  1627. $operationslog .= '<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
  1628. dol_syslog(" Discarded - Email subject contains string ".$searchfilterexcludesubject);
  1629. continue; // Exclude email
  1630. }
  1631. }
  1632. $reg = array();
  1633. if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) {
  1634. $from = $reg[2];
  1635. $fromtext = $reg[1];
  1636. } else {
  1637. $from = $fromstring;
  1638. $fromtext = '';
  1639. }
  1640. if (preg_match('/^(.*)<(.*)>$/', $replytostring, $reg)) {
  1641. $replyto = $reg[2];
  1642. $replytotext = $reg[1];
  1643. } else {
  1644. $replyto = $replytostring;
  1645. $replytotext = '';
  1646. }
  1647. $fk_element_id = 0; $fk_element_type = '';
  1648. $this->db->begin();
  1649. $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
  1650. // Analyze TrackId in field References. For example:
  1651. // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e>
  1652. // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e>
  1653. // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e>
  1654. $trackid = '';
  1655. $objectid = 0;
  1656. $objectemail = null;
  1657. $reg = array();
  1658. if (!empty($headers['References'])) {
  1659. $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']);
  1660. // var_dump($headers['References']);
  1661. // var_dump($arrayofreferences);
  1662. foreach ($arrayofreferences as $reference) {
  1663. //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($date, 'dayhour').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."<br>\n";
  1664. if (!empty($trackidfoundintorecipienttype)) {
  1665. $resultsearchtrackid = -1;
  1666. $reg[1] = $trackidfoundintorecipienttype;
  1667. $reg[2] = $trackidfoundintorecipientid;
  1668. } else {
  1669. $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $reference, $reg);
  1670. if (empty($resultsearchtrackid) && getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
  1671. $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE'), '/').'/', $reference, $reg);
  1672. }
  1673. }
  1674. if (!empty($resultsearchtrackid)) {
  1675. // We found a tracker (in recipient email or into a Reference matching the Dolibarr server)
  1676. $trackid = $reg[1].$reg[2];
  1677. $objectid = $reg[2];
  1678. // See also list into interface_50_modAgenda_ActionsAuto
  1679. if ($reg[1] == 'thi') { // Third-party
  1680. $objectemail = new Societe($this->db);
  1681. }
  1682. if ($reg[1] == 'ctc') { // Contact
  1683. $objectemail = new Contact($this->db);
  1684. }
  1685. if ($reg[1] == 'inv') { // Customer Invoice
  1686. $objectemail = new Facture($this->db);
  1687. }
  1688. if ($reg[1] == 'sinv') { // Supplier Invoice
  1689. $objectemail = new FactureFournisseur($this->db);
  1690. }
  1691. if ($reg[1] == 'pro') { // Customer Proposal
  1692. $objectemail = new Propal($this->db);
  1693. }
  1694. if ($reg[1] == 'ord') { // Sale Order
  1695. $objectemail = new Commande($this->db);
  1696. }
  1697. if ($reg[1] == 'shi') { // Shipment
  1698. $objectemail = new Expedition($this->db);
  1699. }
  1700. if ($reg[1] == 'spro') { // Supplier Proposal
  1701. $objectemail = new SupplierProposal($this->db);
  1702. }
  1703. if ($reg[1] == 'sord') { // Supplier Order
  1704. $objectemail = new CommandeFournisseur($this->db);
  1705. }
  1706. if ($reg[1] == 'rec') { // Reception
  1707. $objectemail = new Reception($this->db);
  1708. }
  1709. if ($reg[1] == 'proj') { // Project
  1710. $objectemail = new Project($this->db);
  1711. }
  1712. if ($reg[1] == 'tas') { // Task
  1713. $objectemail = new Task($this->db);
  1714. }
  1715. if ($reg[1] == 'con') { // Contact
  1716. $objectemail = new Contact($this->db);
  1717. }
  1718. if ($reg[1] == 'use') { // User
  1719. $objectemail = new User($this->db);
  1720. }
  1721. if ($reg[1] == 'tic') { // Ticket
  1722. $objectemail = new Ticket($this->db);
  1723. }
  1724. if ($reg[1] == 'recruitmentcandidature') { // Recruiting Candidate
  1725. $objectemail = new RecruitmentCandidature($this->db);
  1726. }
  1727. if ($reg[1] == 'mem') { // Member
  1728. $objectemail = new Adherent($this->db);
  1729. }
  1730. /*if ($reg[1] == 'leav') { // Leave / Holiday
  1731. $objectemail = new Holiday($db);
  1732. }
  1733. if ($reg[1] == 'exp') { // ExpenseReport
  1734. $objectemail = new ExpenseReport($db);
  1735. }*/
  1736. } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) {
  1737. // This is an external reference, we check if we have it in our database
  1738. if (!is_object($objectemail)) {
  1739. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ticket where email_msgid = '".$this->db->escape($reg[1])."'";
  1740. $resql = $this->db->query($sql);
  1741. if ($resql) {
  1742. $obj = $this->db->fetch_object($resql);
  1743. if ($obj) {
  1744. $objectid = $obj->rowid;
  1745. $objectemail = new Ticket($this->db);
  1746. $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1747. }
  1748. } else {
  1749. $errorforemail++;
  1750. }
  1751. }
  1752. if (!is_object($objectemail)) {
  1753. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."projet where email_msgid = '".$this->db->escape($reg[1])."'";
  1754. $resql = $this->db->query($sql);
  1755. if ($resql) {
  1756. $obj = $this->db->fetch_object($resql);
  1757. if ($obj) {
  1758. $objectid = $obj->rowid;
  1759. $objectemail = new Project($this->db);
  1760. $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1761. }
  1762. } else {
  1763. $errorforemail++;
  1764. }
  1765. }
  1766. if (!is_object($objectemail)) {
  1767. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1])."'";
  1768. $resql = $this->db->query($sql);
  1769. if ($resql) {
  1770. $obj = $this->db->fetch_object($resql);
  1771. if ($obj) {
  1772. $objectid = $obj->rowid;
  1773. $objectemail = new RecruitmentCandidature($this->db);
  1774. $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1775. }
  1776. } else {
  1777. $errorforemail++;
  1778. }
  1779. }
  1780. }
  1781. // Load object linked to email
  1782. if (is_object($objectemail)) {
  1783. $result = $objectemail->fetch($objectid);
  1784. if ($result > 0) {
  1785. $fk_element_id = $objectemail->id;
  1786. $fk_element_type = $objectemail->element;
  1787. // Fix fk_element_type
  1788. if ($fk_element_type == 'facture') {
  1789. $fk_element_type = 'invoice';
  1790. }
  1791. if (get_class($objectemail) != 'Societe') {
  1792. $thirdpartyid = $objectemail->fk_soc;
  1793. } else {
  1794. $thirdpartyid = $objectemail->id;
  1795. }
  1796. if (get_class($objectemail) != 'Contact') {
  1797. $contactid = $objectemail->fk_socpeople;
  1798. } else {
  1799. $contactid = $objectemail->id;
  1800. }
  1801. if (get_class($objectemail) != 'Project') {
  1802. $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
  1803. } else {
  1804. $projectid = $objectemail->id;
  1805. }
  1806. }
  1807. }
  1808. // Project
  1809. if ($projectid > 0) {
  1810. $result = $projectstatic->fetch($projectid);
  1811. if ($result <= 0) {
  1812. $projectstatic->id = 0;
  1813. } else {
  1814. $projectid = $projectstatic->id;
  1815. if ($trackid) {
  1816. $projectfoundby = 'trackid ('.$trackid.')';
  1817. }
  1818. if (empty($contactid)) {
  1819. $contactid = $projectstatic->fk_contact;
  1820. }
  1821. if (empty($thirdpartyid)) {
  1822. $thirdpartyid = $projectstatic->fk_soc;
  1823. }
  1824. }
  1825. }
  1826. // Contact
  1827. if ($contactid > 0) {
  1828. $result = $contactstatic->fetch($contactid);
  1829. if ($result <= 0) {
  1830. $contactstatic->id = 0;
  1831. } else {
  1832. $contactid = $contactstatic->id;
  1833. if ($trackid) {
  1834. $contactfoundby = 'trackid ('.$trackid.')';
  1835. }
  1836. if (empty($thirdpartyid)) {
  1837. $thirdpartyid = $contactstatic->fk_soc;
  1838. }
  1839. }
  1840. }
  1841. // Thirdparty
  1842. if ($thirdpartyid > 0) {
  1843. $result = $thirdpartystatic->fetch($thirdpartyid);
  1844. if ($result <= 0) {
  1845. $thirdpartystatic->id = 0;
  1846. } else {
  1847. $thirdpartyid = $thirdpartystatic->id;
  1848. if ($trackid) {
  1849. $thirdpartyfoundby = 'trackid ('.$trackid.')';
  1850. }
  1851. }
  1852. }
  1853. if (is_object($objectemail)) {
  1854. break; // Exit loop of references. We already found an accurate reference
  1855. }
  1856. }
  1857. }
  1858. if (empty($contactid)) { // Try to find contact using email
  1859. $result = $contactstatic->fetch(0, null, '', $from);
  1860. if ($result > 0) {
  1861. dol_syslog("We found a contact with the email ".$from);
  1862. $contactid = $contactstatic->id;
  1863. $contactfoundby = 'email of contact ('.$from.')';
  1864. if (empty($thirdpartyid) && $contactstatic->socid > 0) {
  1865. $result = $thirdpartystatic->fetch($contactstatic->socid);
  1866. if ($result > 0) {
  1867. $thirdpartyid = $thirdpartystatic->id;
  1868. $thirdpartyfoundby = 'email of contact ('.$from.')';
  1869. }
  1870. }
  1871. }
  1872. }
  1873. if (empty($thirdpartyid)) { // Try to find thirdparty using email
  1874. $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from);
  1875. if ($result > 0) {
  1876. dol_syslog("We found a thirdparty with the email ".$from);
  1877. $thirdpartyid = $thirdpartystatic->id;
  1878. $thirdpartyfoundby = 'email ('.$from.')';
  1879. }
  1880. }
  1881. /*
  1882. if ($replyto) {
  1883. if (empty($contactid)) { // Try to find contact using email
  1884. $result = $contactstatic->fetch(0, null, '', $replyto);
  1885. if ($result > 0) {
  1886. dol_syslog("We found a contact with the email ".$replyto);
  1887. $contactid = $contactstatic->id;
  1888. $contactfoundby = 'email of contact ('.$replyto.')';
  1889. if (empty($thirdpartyid) && $contactstatic->socid > 0) {
  1890. $result = $thirdpartystatic->fetch($contactstatic->socid);
  1891. if ($result > 0) {
  1892. $thirdpartyid = $thirdpartystatic->id;
  1893. $thirdpartyfoundby = 'email of contact ('.$replyto.')';
  1894. }
  1895. }
  1896. }
  1897. }
  1898. if (empty($thirdpartyid)) { // Try to find thirdparty using email
  1899. $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $replyto);
  1900. if ($result > 0) {
  1901. dol_syslog("We found a thirdparty with the email ".$replyto);
  1902. $thirdpartyid = $thirdpartystatic->id;
  1903. $thirdpartyfoundby = 'email ('.$replyto.')';
  1904. }
  1905. }
  1906. }
  1907. */
  1908. // Do operations (extract variables and creating data)
  1909. if ($mode < 2) { // 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates
  1910. foreach ($this->actions as $operation) {
  1911. $errorforthisaction = 0;
  1912. if ($errorforactions) {
  1913. break;
  1914. }
  1915. if (empty($operation['status'])) {
  1916. continue;
  1917. }
  1918. $operationslog .= '<br>* Process operation '.$operation['type'];
  1919. // Make Operation
  1920. dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id);
  1921. 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
  1922. $actioncode = 'EMAIL_IN';
  1923. // If we scan the Sent box, we use the code for out email
  1924. if ($this->source_directory == 'Sent') {
  1925. $actioncode = 'EMAIL_OUT';
  1926. }
  1927. $description = $descriptiontitle = $descriptionmeta = $descriptionfull = '';
  1928. $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid);
  1929. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject));
  1930. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring));
  1931. if ($sender) {
  1932. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender));
  1933. }
  1934. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to));
  1935. if ($sendtocc) {
  1936. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc));
  1937. }
  1938. // Search and create thirdparty
  1939. if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') {
  1940. if (empty($operation['actionparam'])) {
  1941. $errorforactions++;
  1942. $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;";
  1943. $this->errors[] = $this->error;
  1944. } else {
  1945. $actionparam = $operation['actionparam'];
  1946. $idtouseforthirdparty = '';
  1947. $nametouseforthirdparty = '';
  1948. $emailtouseforthirdparty = '';
  1949. $namealiastouseforthirdparty = '';
  1950. $operationslog .= '<br>Loop on each property to set into actionparam';
  1951. // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....'
  1952. $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '=');
  1953. foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
  1954. $sourcestring = '';
  1955. $sourcefield = '';
  1956. $regexstring = '';
  1957. $regforregex = array();
  1958. if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
  1959. $sourcefield = $regforregex[1];
  1960. $regexstring = $regforregex[2];
  1961. }
  1962. if (!empty($sourcefield) && !empty($regexstring)) {
  1963. if (strtolower($sourcefield) == 'body') {
  1964. $sourcestring = $messagetext;
  1965. } elseif (strtolower($sourcefield) == 'subject') {
  1966. $sourcestring = $subject;
  1967. } elseif (strtolower($sourcefield) == 'header') {
  1968. $sourcestring = $header;
  1969. }
  1970. if ($sourcestring) {
  1971. $regforval = array();
  1972. //var_dump($regexstring);var_dump($sourcestring);
  1973. if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) {
  1974. //var_dump($regforval[count($regforval)-1]);exit;
  1975. // Overwrite param $tmpproperty
  1976. if ($propertytooverwrite == 'id') {
  1977. $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1978. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found idtouseforthirdparty='.dol_escape_htmltag($idtouseforthirdparty);
  1979. } elseif ($propertytooverwrite == 'email') {
  1980. $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1981. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found emailtouseforthirdparty='.dol_escape_htmltag($emailtouseforthirdparty);
  1982. } elseif ($propertytooverwrite == 'name') {
  1983. $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1984. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
  1985. } elseif ($propertytooverwrite == 'name_alias') {
  1986. $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1987. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found namealiastouseforthirdparty='.dol_escape_htmltag($namealiastouseforthirdparty);
  1988. } else {
  1989. $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';
  1990. }
  1991. } else {
  1992. // Regex not found
  1993. $idtouseforthirdparty = null;
  1994. $nametouseforthirdparty = null;
  1995. $emailtouseforthirdparty = null;
  1996. $namealiastouseforthirdparty = null;
  1997. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Not found';
  1998. }
  1999. //var_dump($object->$tmpproperty);exit;
  2000. } else {
  2001. // Nothing can be done for this param
  2002. $errorforactions++;
  2003. $this->error = 'The extract rule to use to load thirdparty for email '.$msgid.' has an unknown source (must be HEADER, SUBJECT or BODY)';
  2004. $this->errors[] = $this->error;
  2005. $operationslog .= '<br>'.$this->error;
  2006. }
  2007. } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
  2008. //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1];
  2009. //else $object->$tmpproperty = $reg[1];
  2010. // Example: id=SETIFEMPTY:123
  2011. if ($propertytooverwrite == 'id') {
  2012. $idtouseforthirdparty = $reg[2];
  2013. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property idtouseforthrdparty='.dol_escape_htmltag($idtouseforthirdparty);
  2014. } elseif ($propertytooverwrite == 'email') {
  2015. $emailtouseforthirdparty = $reg[2];
  2016. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property emailtouseforthrdparty='.dol_escape_htmltag($emailtouseforthirdparty);
  2017. } elseif ($propertytooverwrite == 'name') {
  2018. $nametouseforthirdparty = $reg[2];
  2019. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
  2020. } elseif ($propertytooverwrite == 'name_alias') {
  2021. $namealiastouseforthirdparty = $reg[2];
  2022. $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property namealiastouseforthirdparty='.dol_escape_htmltag($namealiastouseforthirdparty);
  2023. }
  2024. } else {
  2025. $errorforactions++;
  2026. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  2027. $this->errors[] = $this->error;
  2028. break;
  2029. }
  2030. }
  2031. if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
  2032. // We make another search on thirdparty
  2033. $operationslog .= '<br>We have this data to search thirdparty: '.$idtouseforthirdparty.' '.$emailtouseforthirdparty.' '.$nametouseforthirdparty.' '.$namealiastouseforthirdparty;
  2034. $tmpobject = new stdClass();
  2035. $tmpobject->element == 'generic';
  2036. $tmpobject->id = $idtouseforthirdparty;
  2037. $tmpobject->name = $nametouseforthirdparty;
  2038. $tmpobject->name_alias = $namealiastouseforthirdparty;
  2039. $tmpobject->email = $emailtouseforthirdparty;
  2040. $this->overwritePropertiesOfObject($tmpobject, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2041. $idtouseforthirdparty = $tmpobject->id;
  2042. $nametouseforthirdparty = $tmpobject->name;
  2043. $namealiastouseforthirdparty = $tmpobject->name_alias;
  2044. $emailtouseforthirdparty = $tmpobject->email;
  2045. $operationslog .= '<br>We try to search existing thirdparty with '.$idtouseforthirdparty.' '.$emailtouseforthirdparty.' '.$nametouseforthirdparty.' '.$namealiastouseforthirdparty;
  2046. $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty, $namealiastouseforthirdparty);
  2047. if ($result < 0) {
  2048. $errorforactions++;
  2049. $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)';
  2050. $this->errors[] = $this->error;
  2051. break;
  2052. } elseif ($result == 0) {
  2053. if ($operation['type'] == 'loadthirdparty') {
  2054. dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was not found");
  2055. $errorforactions++;
  2056. $langs->load("errors");
  2057. $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
  2058. $this->errors[] = $this->error;
  2059. } elseif ($operation['type'] == 'loadandcreatethirdparty') {
  2060. dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was not found. We try to create it.");
  2061. // Create thirdparty
  2062. $thirdpartystatic = new Societe($db);
  2063. $thirdpartystatic->name = $nametouseforthirdparty;
  2064. if (!empty($namealiastouseforthirdparty)) {
  2065. if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
  2066. $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
  2067. }
  2068. } else {
  2069. $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ? '': $fromtext) : $replytostring);
  2070. }
  2071. $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ? '' : $from) : $replyto) : $emailtouseforthirdparty);
  2072. // Overwrite values with values extracted from source email
  2073. $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2074. if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
  2075. $thirdpartystatic->code_client = 'auto';
  2076. }
  2077. if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
  2078. $thirdpartystatic->code_fournisseur = 'auto';
  2079. }
  2080. if ($errorforthisaction) {
  2081. $errorforactions++;
  2082. } else {
  2083. $result = $thirdpartystatic->create($user);
  2084. if ($result <= 0) {
  2085. $errorforactions++;
  2086. $this->error = $thirdpartystatic->error;
  2087. $this->errors = $thirdpartystatic->errors;
  2088. } else {
  2089. $operationslog .= '<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
  2090. }
  2091. }
  2092. }
  2093. } else {
  2094. dol_syslog("One and only one existing third party has been found");
  2095. $operationslog .= '<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id);
  2096. }
  2097. }
  2098. }
  2099. } elseif ($operation['type'] == 'loadandcreatecontact') { // Search and create contact
  2100. if (empty($operation['actionparam'])) {
  2101. $errorforactions++;
  2102. $this->error = "Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
  2103. $this->errors[] = $this->error;
  2104. } else {
  2105. $contact_static = new Contact($this->db);
  2106. // Overwrite values with values extracted from source email
  2107. $errorforthisaction = $this->overwritePropertiesOfObject($contact_static, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2108. if ($errorforthisaction) {
  2109. $errorforactions++;
  2110. } else {
  2111. if (!empty($contact_static->email) && $contact_static->email != $from) $from = $contact_static->email;
  2112. $result = $contactstatic->fetch(0, null, '', $from);
  2113. if ($result < 0) {
  2114. $errorforactions++;
  2115. $this->error = 'Error when getting contact with email ' . $from;
  2116. $this->errors[] = $this->error;
  2117. break;
  2118. } elseif ($result == 0) {
  2119. dol_syslog("Contact with email " . $from . " was not found. We try to create it.");
  2120. $contactstatic = new Contact($this->db);
  2121. // Create contact
  2122. $contactstatic->email = $from;
  2123. $operationslog .= '<br>We set property email='.dol_escape_htmltag($from);
  2124. // Overwrite values with values extracted from source email
  2125. $errorforthisaction = $this->overwritePropertiesOfObject($contactstatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2126. if ($errorforthisaction) {
  2127. $errorforactions++;
  2128. } else {
  2129. // Search country by name or code
  2130. if (!empty($contactstatic->country)) {
  2131. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2132. $result = getCountry('', 3, $this->db, '', 1, $contactstatic->country);
  2133. if ($result == 'NotDefined') {
  2134. $errorforactions++;
  2135. $this->error = "Error country not found by this name '" . $contactstatic->country . "'";
  2136. } elseif (!($result > 0)) {
  2137. $errorforactions++;
  2138. $this->error = "Error when search country by this name '" . $contactstatic->country . "'";
  2139. $this->errors[] = $this->db->lasterror();
  2140. } else {
  2141. $contactstatic->country_id = $result;
  2142. $operationslog .= '<br>We set property country_id='.dol_escape_htmltag($result);
  2143. }
  2144. } elseif (!empty($contactstatic->country_code)) {
  2145. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2146. $result = getCountry($contactstatic->country_code, 3, $this->db);
  2147. if ($result == 'NotDefined') {
  2148. $errorforactions++;
  2149. $this->error = "Error country not found by this code '" . $contactstatic->country_code . "'";
  2150. } elseif (!($result > 0)) {
  2151. $errorforactions++;
  2152. $this->error = "Error when search country by this code '" . $contactstatic->country_code . "'";
  2153. $this->errors[] = $this->db->lasterror();
  2154. } else {
  2155. $contactstatic->country_id = $result;
  2156. $operationslog .= '<br>We set property country_id='.dol_escape_htmltag($result);
  2157. }
  2158. }
  2159. if (!$errorforactions) {
  2160. // Search state by name or code (for country if defined)
  2161. if (!empty($contactstatic->state)) {
  2162. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
  2163. $result = dol_getIdFromCode($this->db, $contactstatic->state, 'c_departements', 'nom', 'rowid');
  2164. if (empty($result)) {
  2165. $errorforactions++;
  2166. $this->error = "Error state not found by this name '" . $contactstatic->state . "'";
  2167. } elseif (!($result > 0)) {
  2168. $errorforactions++;
  2169. $this->error = "Error when search state by this name '" . $contactstatic->state . "'";
  2170. $this->errors[] = $this->db->lasterror();
  2171. } else {
  2172. $contactstatic->state_id = $result;
  2173. $operationslog .= '<br>We set property state_id='.dol_escape_htmltag($result);
  2174. }
  2175. } elseif (!empty($contactstatic->state_code)) {
  2176. require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
  2177. $result = dol_getIdFromCode($this->db, $contactstatic->state_code, 'c_departements', 'code_departement', 'rowid');
  2178. if (empty($result)) {
  2179. $errorforactions++;
  2180. $this->error = "Error state not found by this code '" . $contactstatic->state_code . "'";
  2181. } elseif (!($result > 0)) {
  2182. $errorforactions++;
  2183. $this->error = "Error when search state by this code '" . $contactstatic->state_code . "'";
  2184. $this->errors[] = $this->db->lasterror();
  2185. } else {
  2186. $contactstatic->state_id = $result;
  2187. $operationslog .= '<br>We set property state_id='.dol_escape_htmltag($result);
  2188. }
  2189. }
  2190. }
  2191. if (!$errorforactions) {
  2192. $result = $contactstatic->create($user);
  2193. if ($result <= 0) {
  2194. $errorforactions++;
  2195. $this->error = $contactstatic->error;
  2196. $this->errors = $contactstatic->errors;
  2197. } else {
  2198. $operationslog .= '<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
  2199. }
  2200. }
  2201. }
  2202. }
  2203. }
  2204. }
  2205. } elseif ($operation['type'] == 'recordevent') {
  2206. // Create event
  2207. $actioncomm = new ActionComm($this->db);
  2208. $alreadycreated = $actioncomm->fetch(0, '', '', $msgid);
  2209. if ($alreadycreated == 0) {
  2210. if ($projectstatic->id > 0) {
  2211. if ($projectfoundby) {
  2212. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby);
  2213. }
  2214. }
  2215. if ($thirdpartystatic->id > 0) {
  2216. if ($thirdpartyfoundby) {
  2217. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2218. }
  2219. }
  2220. if ($contactstatic->id > 0) {
  2221. if ($contactfoundby) {
  2222. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2223. }
  2224. }
  2225. $description = $descriptiontitle;
  2226. $description = dol_concatdesc($description, "-----");
  2227. $description = dol_concatdesc($description, $descriptionmeta);
  2228. $description = dol_concatdesc($description, "-----");
  2229. $description = dol_concatdesc($description, $messagetext);
  2230. $descriptionfull = $description;
  2231. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2232. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2233. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2234. }
  2235. // Insert record of emails sent
  2236. $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
  2237. $actioncomm->code = 'AC_'.$actioncode;
  2238. $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from;
  2239. $actioncomm->note_private = $descriptionfull;
  2240. $actioncomm->fk_project = $projectstatic->id;
  2241. $actioncomm->datep = $date; // date of email
  2242. $actioncomm->datef = $date; // date of email
  2243. $actioncomm->percentage = -1; // Not applicable
  2244. $actioncomm->socid = $thirdpartystatic->id;
  2245. $actioncomm->contact_id = $contactstatic->id;
  2246. $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array());
  2247. $actioncomm->authorid = $user->id; // User saving action
  2248. $actioncomm->userownerid = $user->id; // Owner of action
  2249. // Fields when action is an email (content should be added into note)
  2250. $actioncomm->email_msgid = $msgid;
  2251. $actioncomm->email_from = $fromstring;
  2252. $actioncomm->email_sender = $sender;
  2253. $actioncomm->email_to = $to;
  2254. $actioncomm->email_tocc = $sendtocc;
  2255. $actioncomm->email_tobcc = $sendtobcc;
  2256. $actioncomm->email_subject = $subject;
  2257. $actioncomm->errors_to = '';
  2258. if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) {
  2259. $actioncomm->fk_element = $fk_element_id;
  2260. $actioncomm->elementid = $fk_element_id;
  2261. $actioncomm->elementtype = $fk_element_type;
  2262. if (is_object($objectemail) && $objectemail->module) {
  2263. $actioncomm->elementtype .= '@'.$objectemail->module;
  2264. }
  2265. }
  2266. //$actioncomm->extraparams = $extraparams;
  2267. // Overwrite values with values extracted from source email
  2268. $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2269. //var_dump($fk_element_id);
  2270. //var_dump($fk_element_type);
  2271. //var_dump($alreadycreated);
  2272. //var_dump($operation['type']);
  2273. //var_dump($actioncomm);
  2274. //exit;
  2275. if ($errorforthisaction) {
  2276. $errorforactions++;
  2277. } else {
  2278. $result = $actioncomm->create($user);
  2279. if ($result <= 0) {
  2280. $errorforactions++;
  2281. $this->errors = $actioncomm->errors;
  2282. } else {
  2283. $operationslog .= '<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
  2284. }
  2285. }
  2286. }
  2287. } elseif ($operation['type'] == 'recordjoinpiece') {
  2288. $pj = getAttachments($imapemail, $connection);
  2289. foreach ($pj as $key => $val) {
  2290. $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection);
  2291. }
  2292. if (count($pj) > 0) {
  2293. $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."user WHERE email LIKE '%".$this->db->escape($from)."%'";
  2294. $resql = $this->db->query($sql);
  2295. if ($this->db->num_rows($resql) == 0) {
  2296. $this->errors[] = 'User Not allowed to add documents';
  2297. }
  2298. $arrayobject = array(
  2299. 'propale' => array('table' => 'propal',
  2300. 'fields' => array('ref'),
  2301. 'class' => 'comm/propal/class/propal.class.php',
  2302. 'object' => 'Propal'),
  2303. 'holiday' => array('table' => 'holiday',
  2304. 'fields' => array('ref'),
  2305. 'class' => 'holiday/class/holiday.class.php',
  2306. 'object' => 'Holiday'),
  2307. 'expensereport' => array('table' => 'expensereport',
  2308. 'fields' => array('ref'),
  2309. 'class' => 'expensereport/class/expensereport.class.php',
  2310. 'object' => 'ExpenseReport'),
  2311. 'recruitment/recruitmentjobposition' => array('table' => 'recruitment_recruitmentjobposition',
  2312. 'fields' => array('ref'),
  2313. 'class' => 'recruitment/class/recruitmentjobposition.class.php',
  2314. 'object' => 'RecruitmentJobPosition'),
  2315. 'recruitment/recruitmentcandidature' => array('table' => 'recruitment_recruitmentcandidature',
  2316. 'fields' => array('ref'),
  2317. 'class' => 'recruitment/class/recruitmentcandidature.class.php',
  2318. 'object' => ' RecruitmentCandidature'),
  2319. 'societe' => array('table' => 'societe',
  2320. 'fields' => array('code_client', 'code_fournisseur'),
  2321. 'class' => 'societe/class/societe.class.php',
  2322. 'object' => 'Societe'),
  2323. 'commande' => array('table' => 'commande',
  2324. 'fields' => array('ref'),
  2325. 'class' => 'commande/class/commande.class.php',
  2326. 'object' => 'Commande'),
  2327. 'expedition' => array('table' => 'expedition',
  2328. 'fields' => array('ref'),
  2329. 'class' => 'expedition/class/expedition.class.php',
  2330. 'object' => 'Expedition'),
  2331. 'contract' => array('table' => 'contrat',
  2332. 'fields' => array('ref'),
  2333. 'class' => 'contrat/class/contrat.class.php',
  2334. 'object' => 'Contrat'),
  2335. 'fichinter' => array('table' => 'fichinter',
  2336. 'fields' => array('ref'),
  2337. 'class' => 'fichinter/class/fichinter.class.php',
  2338. 'object' => 'Fichinter'),
  2339. 'ticket' => array('table' => 'ticket',
  2340. 'fields' => array('ref'),
  2341. 'class' => 'ticket/class/ticket.class.php',
  2342. 'object' => 'Ticket'),
  2343. 'knowledgemanagement' => array('table' => 'knowledgemanagement_knowledgerecord',
  2344. 'fields' => array('ref'),
  2345. 'class' => 'knowledgemanagement/class/knowledgemanagement.class.php',
  2346. 'object' => 'KnowledgeRecord'),
  2347. 'supplier_proposal' => array('table' => 'supplier_proposal',
  2348. 'fields' => array('ref'),
  2349. 'class' => 'supplier_proposal/class/supplier_proposal.class.php',
  2350. 'object' => 'SupplierProposal'),
  2351. 'fournisseur/commande' => array('table' => 'commande_fournisseur',
  2352. 'fields' => array('ref', 'ref_supplier'),
  2353. 'class' => 'fourn/class/fournisseur.commande.class.php',
  2354. 'object' => 'SupplierProposal'),
  2355. 'facture' => array('table' => 'facture',
  2356. 'fields' => array('ref'),
  2357. 'class' => 'compta/facture/class/facture.class.php',
  2358. 'object' => 'Facture'),
  2359. 'fournisseur/facture' => array('table' => 'facture_fourn',
  2360. 'fields' => array('ref', 'ref_client'),
  2361. 'class' => 'fourn/class/fournisseur.facture.class.php',
  2362. 'object' => 'FactureFournisseur'),
  2363. 'produit' => array('table' => 'product',
  2364. 'fields' => array('ref'),
  2365. 'class' => 'product/class/product.class.php',
  2366. 'object' => 'Product'),
  2367. 'productlot' => array('table' => 'product_lot',
  2368. 'fields' => array('batch'),
  2369. 'class' => 'product/stock/class/productlot.class.php',
  2370. 'object' => 'Productlot'),
  2371. 'projet' => array('table' => 'projet',
  2372. 'fields' => array('ref'),
  2373. 'class' => 'projet/class/projet.class.php',
  2374. 'object' => 'Project'),
  2375. 'projet_task' => array('table' => 'projet_task',
  2376. 'fields' => array('ref'),
  2377. 'class' => 'projet/class/task.class.php',
  2378. 'object' => 'Task'),
  2379. 'ressource' => array('table' => 'resource',
  2380. 'fields' => array('ref'),
  2381. 'class' => 'ressource/class/dolressource.class.php',
  2382. 'object' => 'Dolresource'),
  2383. 'bom' => array('table' => 'bom_bom',
  2384. 'fields' => array('ref'),
  2385. 'class' => 'bom/class/bom.class.php',
  2386. 'object' => 'BOM'),
  2387. 'mrp' => array('table' => 'mrp_mo',
  2388. 'fields' => array('ref'),
  2389. 'class' => 'mrp/class/mo.class.php',
  2390. 'object' => 'Mo'),
  2391. );
  2392. if (!is_object($hookmanager)) {
  2393. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  2394. $hookmanager = new HookManager($this->db);
  2395. }
  2396. $hookmanager->initHooks(array('emailcolector'));
  2397. $parameters = array('arrayobject' => $arrayobject);
  2398. $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks
  2399. if ($reshook > 0) {
  2400. $arrayobject = $hookmanager->resArray;
  2401. }
  2402. $resultobj = array();
  2403. foreach ($arrayobject as $key => $objectdesc) {
  2404. $sql = 'SELECT DISTINCT t.rowid ';
  2405. $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectdesc['table'] . ' AS t';
  2406. $sql .= ' WHERE ';
  2407. foreach ($objectdesc['fields'] as $field) {
  2408. $sql .= "'" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $field . ", '%') OR ";
  2409. }
  2410. $sql = substr($sql, 0, -4);
  2411. $ressqlobj = $this->db->query($sql);
  2412. if ($ressqlobj) {
  2413. while ($obj = $this->db->fetch_object($ressqlobj)) {
  2414. $resultobj[$key][] = $obj->rowid;
  2415. }
  2416. }
  2417. }
  2418. $dirs = array();
  2419. foreach ($resultobj as $mod => $ids) {
  2420. $moddesc = $arrayobject[$mod];
  2421. $elementpath = $mod;
  2422. dol_include_once($moddesc['class']);
  2423. $objectmanaged = new $moddesc['object']($this->db);
  2424. foreach ($ids as $val) {
  2425. $res = $objectmanaged->fetch($val);
  2426. if ($res) {
  2427. $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : '');
  2428. $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/';
  2429. } else {
  2430. $this->errors[] = 'object not found';
  2431. }
  2432. }
  2433. }
  2434. foreach ($dirs as $target) {
  2435. foreach ($data as $filename => $content) {
  2436. $prefix = $this->actions[$this->id]['actionparam'];
  2437. $resr = saveAttachment($target, $prefix . '_' . $filename, $content);
  2438. if ($resr == -1) {
  2439. $this->errors[] = 'Doc not saved';
  2440. }
  2441. }
  2442. }
  2443. $operationslog .= '<br>Save attachment files on disk';
  2444. } else {
  2445. $this->errors[] = 'no joined piece';
  2446. $operationslog .= '<br>No joinded files';
  2447. }
  2448. } elseif ($operation['type'] == 'project') {
  2449. // Create project / lead
  2450. $projecttocreate = new Project($this->db);
  2451. $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid);
  2452. if ($alreadycreated == 0) {
  2453. if ($thirdpartystatic->id > 0) {
  2454. $projecttocreate->socid = $thirdpartystatic->id;
  2455. if ($thirdpartyfoundby) {
  2456. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2457. }
  2458. }
  2459. if ($contactstatic->id > 0) {
  2460. $projecttocreate->contact_id = $contactstatic->id;
  2461. if ($contactfoundby) {
  2462. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2463. }
  2464. }
  2465. $description = $descriptiontitle;
  2466. $description = dol_concatdesc($description, "-----");
  2467. $description = dol_concatdesc($description, $descriptionmeta);
  2468. $description = dol_concatdesc($description, "-----");
  2469. $description = dol_concatdesc($description, $messagetext);
  2470. $descriptionfull = $description;
  2471. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2472. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2473. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2474. }
  2475. $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
  2476. $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
  2477. $projecttocreate->title = $subject;
  2478. $projecttocreate->date_start = $date; // date of email
  2479. $projecttocreate->date_end = '';
  2480. $projecttocreate->opp_status = $id_opp_status;
  2481. $projecttocreate->opp_percent = $percent_opp_status;
  2482. $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...');
  2483. $projecttocreate->note_private = $descriptionfull;
  2484. $projecttocreate->entity = $conf->entity;
  2485. $projecttocreate->email_msgid = $msgid;
  2486. $savesocid = $projecttocreate->socid;
  2487. // Overwrite values with values extracted from source email.
  2488. // This may overwrite any $projecttocreate->xxx properties.
  2489. $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2490. // Set project ref if not yet defined
  2491. if (empty($projecttocreate->ref)) {
  2492. // Get next Ref
  2493. $defaultref = '';
  2494. $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
  2495. // Search template files
  2496. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2497. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2498. foreach ($dirmodels as $reldir) {
  2499. $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0);
  2500. if (file_exists($file)) {
  2501. $filefound = 1;
  2502. $classname = $modele;
  2503. break;
  2504. }
  2505. }
  2506. if ($filefound) {
  2507. if ($savesocid > 0) {
  2508. if ($savesocid != $projecttocreate->socid) {
  2509. $errorforactions++;
  2510. 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');
  2511. }
  2512. } else {
  2513. if ($projecttocreate->socid > 0) {
  2514. $thirdpartystatic->fetch($projecttocreate->socid);
  2515. }
  2516. }
  2517. $result = dol_include_once($reldir."core/modules/project/".$modele.'.php');
  2518. $modModuleToUseForNextValue = new $classname;
  2519. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
  2520. }
  2521. $projecttocreate->ref = $defaultref;
  2522. }
  2523. if ($errorforthisaction) {
  2524. $errorforactions++;
  2525. } else {
  2526. if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
  2527. $errorforactions++;
  2528. $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
  2529. $operationslog .= '<br>'.$this->error;
  2530. } else {
  2531. // Create project
  2532. $result = $projecttocreate->create($user);
  2533. if ($result <= 0) {
  2534. $errorforactions++;
  2535. $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
  2536. $this->errors = $projecttocreate->errors;
  2537. $operationslog .= '<br>'.$this->error;
  2538. } else {
  2539. if ($attachments) {
  2540. $destdir = $conf->project->dir_output.'/'.$projecttocreate->ref;
  2541. if (!dol_is_dir($destdir)) {
  2542. dol_mkdir($destdir);
  2543. }
  2544. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2545. foreach ($attachments as $attachment) {
  2546. $attachment->save($destdir.'/');
  2547. }
  2548. } else {
  2549. $this->getmsg($connection, $imapemail, $destdir);
  2550. }
  2551. $operationslog .= '<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
  2552. } else {
  2553. $operationslog .= '<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
  2554. }
  2555. }
  2556. }
  2557. }
  2558. } else {
  2559. dol_syslog("Project already exists for msgid = ".dol_escape_htmltag($msgid).", so we do not recreate it.");
  2560. $operationslog .= '<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
  2561. }
  2562. } elseif ($operation['type'] == 'ticket') {
  2563. // Create ticket
  2564. $tickettocreate = new Ticket($this->db);
  2565. $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid);
  2566. if ($alreadycreated == 0) {
  2567. if ($thirdpartystatic->id > 0) {
  2568. $tickettocreate->socid = $thirdpartystatic->id;
  2569. $tickettocreate->fk_soc = $thirdpartystatic->id;
  2570. if ($thirdpartyfoundby) {
  2571. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2572. }
  2573. }
  2574. if ($contactstatic->id > 0) {
  2575. $tickettocreate->contact_id = $contactstatic->id;
  2576. if ($contactfoundby) {
  2577. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2578. }
  2579. }
  2580. $description = $descriptiontitle;
  2581. $description = dol_concatdesc($description, "-----");
  2582. $description = dol_concatdesc($description, $descriptionmeta);
  2583. $description = dol_concatdesc($description, "-----");
  2584. $description = dol_concatdesc($description, $messagetext);
  2585. $descriptionfull = $description;
  2586. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2587. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2588. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2589. }
  2590. $tickettocreate->subject = $subject;
  2591. $tickettocreate->message = $description;
  2592. $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));
  2593. $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));
  2594. $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));
  2595. $tickettocreate->origin_email = $from;
  2596. $tickettocreate->fk_user_create = $user->id;
  2597. $tickettocreate->datec = dol_now();
  2598. $tickettocreate->fk_project = $projectstatic->id;
  2599. $tickettocreate->notify_tiers_at_create = 0;
  2600. $tickettocreate->note_private = $descriptionfull;
  2601. $tickettocreate->entity = $conf->entity;
  2602. $tickettocreate->email_msgid = $msgid;
  2603. $tickettocreate->email_date = $date;
  2604. //$tickettocreate->fk_contact = $contactstatic->id;
  2605. $savesocid = $tickettocreate->socid;
  2606. // Overwrite values with values extracted from source email.
  2607. // This may overwrite any $projecttocreate->xxx properties.
  2608. $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2609. // Set ticket ref if not yet defined
  2610. if (empty($tickettocreate->ref)) {
  2611. // Get next Ref
  2612. $defaultref = '';
  2613. $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON;
  2614. // Search template files
  2615. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2616. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2617. foreach ($dirmodels as $reldir) {
  2618. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2619. if (file_exists($file)) {
  2620. $filefound = 1;
  2621. $classname = $modele;
  2622. break;
  2623. }
  2624. }
  2625. if ($filefound) {
  2626. if ($savesocid > 0) {
  2627. if ($savesocid != $tickettocreate->socid) {
  2628. $errorforactions++;
  2629. 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');
  2630. }
  2631. } else {
  2632. if ($tickettocreate->socid > 0) {
  2633. $thirdpartystatic->fetch($tickettocreate->socid);
  2634. }
  2635. }
  2636. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2637. $modModuleToUseForNextValue = new $classname;
  2638. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
  2639. }
  2640. $tickettocreate->ref = $defaultref;
  2641. }
  2642. if ($errorforthisaction) {
  2643. $errorforactions++;
  2644. } else {
  2645. if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
  2646. $errorforactions++;
  2647. $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
  2648. } else {
  2649. // Create project
  2650. $result = $tickettocreate->create($user);
  2651. if ($result <= 0) {
  2652. $errorforactions++;
  2653. $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error);
  2654. $this->errors = $tickettocreate->errors;
  2655. } else {
  2656. if ($attachments) {
  2657. $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref;
  2658. if (!dol_is_dir($destdir)) {
  2659. dol_mkdir($destdir);
  2660. }
  2661. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2662. foreach ($attachments as $attachment) {
  2663. $attachment->save($destdir.'/');
  2664. }
  2665. } else {
  2666. $this->getmsg($connection, $imapemail, $destdir);
  2667. }
  2668. $operationslog .= '<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
  2669. } else {
  2670. $operationslog .= '<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
  2671. }
  2672. }
  2673. }
  2674. }
  2675. }
  2676. } elseif ($operation['type'] == 'candidature') {
  2677. // Create candidature
  2678. $candidaturetocreate = new RecruitmentCandidature($this->db);
  2679. $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid);
  2680. if ($alreadycreated == 0) {
  2681. $description = $descriptiontitle;
  2682. $description = dol_concatdesc($description, "-----");
  2683. $description = dol_concatdesc($description, $descriptionmeta);
  2684. $description = dol_concatdesc($description, "-----");
  2685. $description = dol_concatdesc($description, $messagetext);
  2686. $descriptionfull = $description;
  2687. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2688. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2689. $candidaturetocreate->subject = $subject;
  2690. $candidaturetocreate->message = $description;
  2691. $candidaturetocreate->type_code = 0;
  2692. $candidaturetocreate->category_code = null;
  2693. $candidaturetocreate->severity_code = null;
  2694. $candidaturetocreate->email = $from;
  2695. //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from;
  2696. $candidaturetocreate->fk_user_creat = $user->id;
  2697. $candidaturetocreate->date_creation = dol_now();
  2698. $candidaturetocreate->fk_project = $projectstatic->id;
  2699. $candidaturetocreate->description = $description;
  2700. $candidaturetocreate->note_private = $descriptionfull;
  2701. $candidaturetocreate->entity = $conf->entity;
  2702. $candidaturetocreate->email_msgid = $msgid;
  2703. $candidaturetocreate->email_date = $date; // date of email
  2704. $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
  2705. //$candidaturetocreate->fk_contact = $contactstatic->id;
  2706. // Overwrite values with values extracted from source email.
  2707. // This may overwrite any $projecttocreate->xxx properties.
  2708. $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2709. // Set candidature ref if not yet defined
  2710. /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status
  2711. {
  2712. // Get next Ref
  2713. $defaultref = '';
  2714. $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON;
  2715. // Search template files
  2716. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2717. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2718. foreach ($dirmodels as $reldir)
  2719. {
  2720. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2721. if (file_exists($file)) {
  2722. $filefound = 1;
  2723. $classname = $modele;
  2724. break;
  2725. }
  2726. }
  2727. if ($filefound) {
  2728. if ($savesocid > 0) {
  2729. if ($savesocid != $candidaturetocreate->socid) {
  2730. $errorforactions++;
  2731. 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');
  2732. }
  2733. } else {
  2734. if ($candidaturetocreate->socid > 0)
  2735. {
  2736. $thirdpartystatic->fetch($candidaturetocreate->socid);
  2737. }
  2738. }
  2739. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2740. $modModuleToUseForNextValue = new $classname;
  2741. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
  2742. }
  2743. $candidaturetocreate->ref = $defaultref;
  2744. }*/
  2745. if ($errorforthisaction) {
  2746. $errorforactions++;
  2747. } else {
  2748. // Create project
  2749. $result = $candidaturetocreate->create($user);
  2750. if ($result <= 0) {
  2751. $errorforactions++;
  2752. $this->error = 'Failed to create candidature: '.join(', ', $candidaturetocreate->errors);
  2753. $this->errors = $candidaturetocreate->errors;
  2754. }
  2755. $operationslog .= '<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
  2756. }
  2757. }
  2758. } elseif (substr($operation['type'], 0, 4) == 'hook') {
  2759. // Create event specific on hook
  2760. // this code action is hook..... for support this call
  2761. if (!is_object($hookmanager)) {
  2762. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  2763. $hookmanager = new HookManager($this->db);
  2764. }
  2765. $parameters = array(
  2766. 'connection'=> $connection,
  2767. 'imapemail'=>$imapemail,
  2768. 'overview'=>$overview,
  2769. 'from' => $from,
  2770. 'fromtext' => $fromtext,
  2771. 'actionparam'=> $operation['actionparam'],
  2772. 'thirdpartyid' => $thirdpartyid,
  2773. 'objectid'=> $objectid,
  2774. 'objectemail'=> $objectemail,
  2775. 'messagetext'=>$messagetext,
  2776. 'subject'=>$subject,
  2777. 'header'=>$header,
  2778. 'attachments'=>$attachments,
  2779. );
  2780. $reshook = $hookmanager->executeHooks('doCollectImapOneCollector', $parameters, $this, $operation['type']);
  2781. if ($reshook < 0) {
  2782. $errorforthisaction++;
  2783. $this->error = $hookmanager->resPrint;
  2784. }
  2785. if ($errorforthisaction) {
  2786. $errorforactions++;
  2787. $operationslog .= '<br>Hook doCollectImapOneCollector executed with error';
  2788. } else {
  2789. $operationslog .= '<br>Hook doCollectImapOneCollector executed without error';
  2790. }
  2791. }
  2792. if (!$errorforactions) {
  2793. $nbactiondoneforemail++;
  2794. }
  2795. }
  2796. }
  2797. // Error for email or not ?
  2798. if (!$errorforactions) {
  2799. if (!empty($targetdir)) {
  2800. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2801. // Move mail using PHP-IMAP
  2802. dol_syslog("EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get('subject'))." to ".$targetdir, LOG_DEBUG);
  2803. if (empty($mode)) {
  2804. $imapemail->move($targetdir);
  2805. }
  2806. } else {
  2807. dol_syslog("EmailCollector::doCollectOneCollector move message ".((string) $imapemail)." to ".$connectstringtarget, LOG_DEBUG);
  2808. $operationslog .= '<br>Move mail '.((string) $imapemail).' - '.$msgid;
  2809. $arrayofemailtodelete[$imapemail] = $msgid;
  2810. }
  2811. } else {
  2812. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2813. 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);
  2814. } else {
  2815. dol_syslog("EmailCollector::doCollectOneCollector message ".((string) $imapemail)." to ".$connectstringtarget." was set to read", LOG_DEBUG);
  2816. }
  2817. }
  2818. } else {
  2819. $errorforemail++;
  2820. }
  2821. unset($objectemail);
  2822. unset($projectstatic);
  2823. unset($thirdpartystatic);
  2824. unset($contactstatic);
  2825. $nbemailprocessed++;
  2826. if (!$errorforemail) {
  2827. $nbactiondone += $nbactiondoneforemail;
  2828. $nbemailok++;
  2829. if (empty($mode)) {
  2830. $this->db->commit();
  2831. } else {
  2832. $this->db->rollback();
  2833. }
  2834. // Stop the loop to process email if we reach maximum collected per collect
  2835. if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
  2836. dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok." collected with success, so we stop this collector now.");
  2837. break;
  2838. }
  2839. } else {
  2840. $error++;
  2841. $this->db->rollback();
  2842. }
  2843. }
  2844. $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
  2845. dol_syslog("End of loop on emails", LOG_INFO, -1);
  2846. } else {
  2847. $langs->load("admin");
  2848. $output = $langs->trans('NoNewEmailToProcess');
  2849. }
  2850. // Disconnect
  2851. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2852. $client->disconnect();
  2853. } else {
  2854. foreach ($arrayofemailtodelete as $imapemail => $msgid) {
  2855. dol_syslog("EmailCollect::doCollectOneCollector delete email ".$imapemail." ".$msgid);
  2856. $operationslog .= "<br> delete email ".$imapemail." ".$msgid;
  2857. if (empty($mode) && empty($error)) {
  2858. $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
  2859. if ($res == false) {
  2860. $errorforemail++;
  2861. $this->error = imap_last_error();
  2862. $this->errors[] = $this->error;
  2863. $operationslog .= '<br>Error in move '.$this->error;
  2864. dol_syslog(imap_last_error());
  2865. }
  2866. }
  2867. }
  2868. if (empty($mode) && empty($error)) {
  2869. dol_syslog("Expunge", LOG_DEBUG);
  2870. $operationslog .= "<br>Expunge";
  2871. imap_expunge($connection); // To validate all moves
  2872. }
  2873. imap_close($connection);
  2874. }
  2875. $this->datelastresult = $now;
  2876. $this->lastresult = $output;
  2877. $this->debuginfo .= 'IMAP search string used : '.$search;
  2878. if ($searchhead) {
  2879. $this->debuginfo .= '<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
  2880. }
  2881. if ($operationslog) {
  2882. $this->debuginfo .= $operationslog;
  2883. }
  2884. if (empty($error) && empty($mode)) {
  2885. $this->datelastok = $now;
  2886. }
  2887. if (!empty($this->errors)) {
  2888. $this->lastresult .= "<br>".join("<br>", $this->errors);
  2889. }
  2890. $this->codelastresult = ($error ? 'KO' : 'OK');
  2891. if (empty($mode)) {
  2892. $this->update($user);
  2893. }
  2894. dol_syslog("EmailCollector::doCollectOneCollector end", LOG_INFO);
  2895. return $error ? -1 : 1;
  2896. }
  2897. // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation
  2898. /**
  2899. * getmsg
  2900. *
  2901. * @param Object $mbox Structure
  2902. * @param string $mid UID email
  2903. * @param string $destdir Target dir for attachments
  2904. * @return void
  2905. */
  2906. private function getmsg($mbox, $mid, $destdir = '')
  2907. {
  2908. // input $mbox = IMAP stream, $mid = message id
  2909. // output all the following:
  2910. global $charset, $htmlmsg, $plainmsg, $attachments;
  2911. $htmlmsg = $plainmsg = $charset = '';
  2912. $attachments = array();
  2913. // HEADER
  2914. //$h = imap_header($mbox,$mid);
  2915. // add code here to get date, from, to, cc, subject...
  2916. // BODY
  2917. $s = imap_fetchstructure($mbox, $mid, FT_UID);
  2918. if (!$s->parts) {
  2919. // simple
  2920. $this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number
  2921. } else {
  2922. // multipart: cycle through each part
  2923. foreach ($s->parts as $partno0 => $p) {
  2924. $this->getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
  2925. }
  2926. }
  2927. }
  2928. /* partno string
  2929. 0 multipart/mixed
  2930. 1 multipart/alternative
  2931. 1.1 text/plain
  2932. 1.2 text/html
  2933. 2 message/rfc822
  2934. 2 multipart/mixed
  2935. 2.1 multipart/alternative
  2936. 2.1.1 text/plain
  2937. 2.1.2 text/html
  2938. 2.2 message/rfc822
  2939. 2.2 multipart/alternative
  2940. 2.2.1 text/plain
  2941. 2.2.2 text/html
  2942. */
  2943. /**
  2944. * Sub function for getpart(). Only called by createPartArray() and itself.
  2945. *
  2946. * @param Object $mbox Structure
  2947. * @param string $mid Part no
  2948. * @param Object $p Object p
  2949. * @param string $partno Partno
  2950. * @param string $destdir Target dir for attachments
  2951. * @return void
  2952. */
  2953. private function getpart($mbox, $mid, $p, $partno, $destdir = '')
  2954. {
  2955. // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
  2956. global $htmlmsg, $plainmsg, $charset, $attachments;
  2957. // DECODE DATA
  2958. $data = ($partno) ?
  2959. imap_fetchbody($mbox, $mid, $partno, FT_UID) : // multipart
  2960. imap_body($mbox, $mid, FT_UID); // simple
  2961. // Any part may be encoded, even plain text messages, so check everything.
  2962. if ($p->encoding == 4) {
  2963. $data = quoted_printable_decode($data);
  2964. } elseif ($p->encoding == 3) {
  2965. $data = base64_decode($data);
  2966. }
  2967. // PARAMETERS
  2968. // get all parameters, like charset, filenames of attachments, etc.
  2969. $params = array();
  2970. if ($p->parameters) {
  2971. foreach ($p->parameters as $x) {
  2972. $params[strtolower($x->attribute)] = $x->value;
  2973. }
  2974. }
  2975. if ($p->dparameters) {
  2976. foreach ($p->dparameters as $x) {
  2977. $params[strtolower($x->attribute)] = $x->value;
  2978. }
  2979. }
  2980. // ATTACHMENT
  2981. // Any part with a filename is an attachment,
  2982. // so an attached text file (type 0) is not mistaken as the message.
  2983. if ($params['filename'] || $params['name']) {
  2984. // filename may be given as 'Filename' or 'Name' or both
  2985. $filename = ($params['filename']) ? $params['filename'] : $params['name'];
  2986. // filename may be encoded, so see imap_mime_header_decode()
  2987. $attachments[$filename] = $data; // this is a problem if two files have same name
  2988. // Get file name (with extension)
  2989. $file_name_complete = $params['filename'];
  2990. $destination = $destdir.'/'.$file_name_complete;
  2991. // Extract file extension
  2992. $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
  2993. // Extract file name without extension
  2994. $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
  2995. // Save an original file name variable to track while renaming if file already exists
  2996. $file_name_original = $file_name;
  2997. // Increment file name by 1
  2998. $num = 1;
  2999. /**
  3000. * Check if the same file name already exists in the upload folder,
  3001. * append increment number to the original filename
  3002. */
  3003. while (file_exists($destdir."/".$file_name.".".$extension)) {
  3004. $file_name = $file_name_original . ' (' . $num . ')';
  3005. $file_name_complete = $file_name . "." . $extension;
  3006. $destination = $destdir.'/'.$file_name_complete;
  3007. $num++;
  3008. }
  3009. $destination = dol_sanitizePathName($destination);
  3010. file_put_contents($destination, $data);
  3011. }
  3012. // TEXT
  3013. if ($p->type == 0 && $data) {
  3014. if (!empty($params['charset'])) {
  3015. $data = $this->convertStringEncoding($data, $params['charset']);
  3016. }
  3017. // Messages may be split in different parts because of inline attachments,
  3018. // so append parts together with blank row.
  3019. if (strtolower($p->subtype) == 'plain') {
  3020. $plainmsg .= trim($data)."\n\n";
  3021. } else {
  3022. $htmlmsg .= $data."<br><br>";
  3023. }
  3024. $charset = $params['charset']; // assume all parts are same charset
  3025. } elseif ($p->type == 2 && $data) {
  3026. // EMBEDDED MESSAGE
  3027. // Many bounce notifications embed the original message as type 2,
  3028. // but AOL uses type 1 (multipart), which is not handled here.
  3029. // There are no PHP functions to parse embedded messages,
  3030. // so this just appends the raw source to the main message.
  3031. if (!empty($params['charset'])) {
  3032. $data = $this->convertStringEncoding($data, $params['charset']);
  3033. }
  3034. $plainmsg .= $data."\n\n";
  3035. }
  3036. // SUBPART RECURSION
  3037. if ($p->parts) {
  3038. foreach ($p->parts as $partno0 => $p2) {
  3039. $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1)); // 1.2, 1.2.1, etc.
  3040. }
  3041. }
  3042. }
  3043. /**
  3044. * Converts a string from one encoding to another.
  3045. *
  3046. * @param string $string String to convert
  3047. * @param string $fromEncoding String encoding
  3048. * @param string $toEncoding String return encoding
  3049. * @return string Converted string if conversion was successful, or the original string if not
  3050. * @throws Exception
  3051. */
  3052. protected function convertStringEncoding($string, $fromEncoding, $toEncoding = 'UTF-8')
  3053. {
  3054. if (!$string || $fromEncoding == $toEncoding) {
  3055. return $string;
  3056. }
  3057. $convertedString = function_exists('iconv') ? @iconv($fromEncoding, $toEncoding.'//IGNORE', $string) : null;
  3058. if (!$convertedString && extension_loaded('mbstring')) {
  3059. $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
  3060. }
  3061. if (!$convertedString) {
  3062. throw new Exception('Mime string encoding conversion failed');
  3063. }
  3064. return $convertedString;
  3065. }
  3066. /**
  3067. * Decode a subject string according to RFC2047
  3068. * Example: '=?Windows-1252?Q?RE=A0:_ABC?=' => 'RE : ABC...'
  3069. * Example: '=?UTF-8?Q?A=C3=A9B?=' => 'AéB'
  3070. * Example: '=?UTF-8?B?2KLYstmF2KfbjNi0?=' =>
  3071. * Example: '=?utf-8?B?UkU6IG1vZHVsZSBkb2xpYmFyciBnZXN0aW9ubmFpcmUgZGUgZmljaGllcnMg?= =?utf-8?B?UsOpZsOpcmVuY2UgZGUgbGEgY29tbWFuZGUgVFVHRURJSklSIOKAkyBwYXNz?= =?utf-8?B?w6llIGxlIDIyLzA0LzIwMjA=?='
  3072. *
  3073. * @param string $subject Subject
  3074. * @return string Decoded subject (in UTF-8)
  3075. */
  3076. protected function decodeSMTPSubject($subject)
  3077. {
  3078. // Decode $overview[0]->subject according to RFC2047
  3079. // Can use also imap_mime_header_decode($str)
  3080. // Can use also mb_decode_mimeheader($str)
  3081. // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8')
  3082. if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) {
  3083. $elements = imap_mime_header_decode($subject);
  3084. $newstring = '';
  3085. if (!empty($elements)) {
  3086. $num = count($elements);
  3087. for ($i = 0; $i < $num; $i++) {
  3088. $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));
  3089. $newstring .= $stringinutf8;
  3090. }
  3091. $subject = $newstring;
  3092. }
  3093. } elseif (!function_exists('mb_decode_mimeheader')) {
  3094. $subject = mb_decode_mimeheader($subject);
  3095. } elseif (function_exists('iconv_mime_decode')) {
  3096. $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
  3097. }
  3098. return $subject;
  3099. }
  3100. /**
  3101. * Remove EMoji from email content
  3102. *
  3103. * @param string $text String to sanitize
  3104. * @return string Sanitized string
  3105. */
  3106. protected function removeEmoji($text)
  3107. {
  3108. // Supprimer les caractères emoji en utilisant une expression régulière
  3109. $text = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $text);
  3110. $text = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $text);
  3111. $text = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $text);
  3112. $text = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $text);
  3113. $text = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $text);
  3114. $text = preg_replace('/[\x{1F900}-\x{1F9FF}]/u', '', $text);
  3115. $text = preg_replace('/[\x{1F1E0}-\x{1F1FF}]/u', '', $text);
  3116. return $text;
  3117. }
  3118. }