emailcollector.class.php 118 KB

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