emailcollector.class.php 118 KB

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