emailcollector.class.php 145 KB

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