emailcollector.class.php 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114
  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. $errorforthisaction = 0;
  755. // Overwrite values with values extracted from source email
  756. // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....'
  757. $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
  758. foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
  759. $tmpclass = ''; $tmpproperty = '';
  760. $tmparray = explode('.', $propertytooverwrite);
  761. if (count($tmparray) == 2) {
  762. $tmpclass = $tmparray[0];
  763. $tmpproperty = $tmparray[1];
  764. } else {
  765. $tmpproperty = $tmparray[0];
  766. }
  767. if ($tmpclass && ($tmpclass != $object->element)) {
  768. continue; // Property is for another type of object
  769. }
  770. //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty))
  771. if ($tmpproperty) {
  772. $sourcestring = '';
  773. $sourcefield = '';
  774. $regexstring = '';
  775. //$transformationstring='';
  776. $regforregex = array();
  777. if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
  778. $sourcefield = $regforregex[1];
  779. $regexstring = $regforregex[2];
  780. //$transofrmationstring=$regforregex[3];
  781. } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
  782. $sourcefield = $regforregex[1];
  783. $regexstring = $regforregex[2];
  784. }
  785. if (!empty($sourcefield) && !empty($regexstring)) {
  786. if (strtolower($sourcefield) == 'body') {
  787. $sourcestring = $messagetext;
  788. } elseif (strtolower($sourcefield) == 'subject') {
  789. $sourcestring = $subject;
  790. } elseif (strtolower($sourcefield) == 'header') {
  791. $sourcestring = $header;
  792. }
  793. if ($sourcestring) {
  794. $regforval = array();
  795. $regexoptions = '';
  796. if (strtolower($sourcefield) == 'body') {
  797. $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
  798. }
  799. if (strtolower($sourcefield) == 'header') {
  800. $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line.
  801. }
  802. //var_dump($tmpproperty.' - '.$regexstring.' - '.$regexoptions.' - '.$sourcestring);
  803. if (preg_match('/'.$regexstring.'/'.$regexoptions, $sourcestring, $regforval)) {
  804. // Overwrite param $tmpproperty
  805. $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) : null;
  806. if (strtolower($sourcefield) == 'header') {
  807. if (preg_match('/^options_/', $tmpproperty)) {
  808. $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted);
  809. } else {
  810. $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted);
  811. }
  812. } else {
  813. if (preg_match('/^options_/', $tmpproperty)) {
  814. $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted);
  815. } else {
  816. $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted);
  817. }
  818. }
  819. if (preg_match('/^options_/', $tmpproperty)) {
  820. $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));
  821. } else {
  822. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> found '.dol_escape_htmltag(dol_trunc($object->$tmpproperty, 128));
  823. }
  824. } else {
  825. // Regex not found
  826. $object->$tmpproperty = null;
  827. $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.';
  828. }
  829. } else {
  830. // Nothing can be done for this param
  831. $errorforthisaction++;
  832. $this->error = 'The extract rule to use has on an unknown source (must be HEADER, SUBJECT or BODY)';
  833. $this->errors[] = $this->error;
  834. }
  835. } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
  836. $valuecurrent = '';
  837. if (preg_match('/^options_/', $tmpproperty)) {
  838. $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)];
  839. } else {
  840. $valuecurrent = $object->$tmpproperty;
  841. }
  842. if ($regforregex[1] == 'SET' || empty($valuecurrent)) {
  843. $valuetouse = $regforregex[2];
  844. $substitutionarray = array();
  845. $matcharray = array();
  846. preg_match_all('/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
  847. //var_dump($tmpproperty.' - '.$object->$tmpproperty.' - '.$valuetouse); var_dump($matcharray);
  848. if (is_array($matcharray[1])) { // $matcharray[1] is array with list of substitution key found without the __
  849. foreach ($matcharray[1] as $keytoreplace) {
  850. if ($keytoreplace && isset($object->$keytoreplace)) {
  851. $substitutionarray['__'.$keytoreplace.'__'] = $object->$keytoreplace;
  852. }
  853. }
  854. }
  855. //var_dump($substitutionarray);
  856. dol_syslog(var_export($substitutionarray, true));
  857. //var_dump($substitutionarray);
  858. $valuetouse = make_substitutions($valuetouse, $substitutionarray);
  859. if (preg_match('/^options_/', $tmpproperty)) {
  860. $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse;
  861. } else {
  862. $object->$tmpproperty = $valuetouse;
  863. }
  864. $operationslog .= '<br>Set value '.dol_escape_htmltag($valuetouse).' into variable '.dol_escape_htmltag($tmpproperty);
  865. }
  866. } else {
  867. $errorforthisaction++;
  868. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  869. $this->errors[] = $this->error;
  870. }
  871. }
  872. }
  873. return $errorforthisaction;
  874. }
  875. /**
  876. * Execute collect for current collector loaded previously with fetch.
  877. *
  878. * @param int $mode 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates
  879. * @return int <0 if KO, >0 if OK
  880. */
  881. public function doCollectOneCollector($mode = 0)
  882. {
  883. global $db, $conf, $langs, $user;
  884. global $hookmanager;
  885. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  886. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  887. dol_syslog("EmailCollector::doCollectOneCollector start for id=".$this->id." - ".$this->ref, LOG_DEBUG);
  888. $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda", "commercial"));
  889. $error = 0;
  890. $this->output = '';
  891. $this->error = '';
  892. $this->debuginfo = '';
  893. $search = '';
  894. $searchhead = '';
  895. $searchfilterdoltrackid = 0;
  896. $searchfilternodoltrackid = 0;
  897. $searchfilterisanswer = 0;
  898. $searchfilterisnotanswer = 0;
  899. $operationslog = '';
  900. $now = dol_now();
  901. if (empty($this->host)) {
  902. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost'));
  903. return -1;
  904. }
  905. if (empty($this->login)) {
  906. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login'));
  907. return -1;
  908. }
  909. if (empty($this->source_directory)) {
  910. $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory'));
  911. return -1;
  912. }
  913. $this->fetchFilters();
  914. $this->fetchActions();
  915. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  916. if ($this->acces_type == 1) {
  917. // Mode OAUth2 with PHP-IMAP
  918. require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
  919. $keyforsupportedoauth2array = $this->oauth_service;
  920. if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
  921. $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
  922. } else {
  923. $keyforprovider = '';
  924. }
  925. $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
  926. $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
  927. $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
  928. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  929. //$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;
  930. //dol_syslog($debugtext);
  931. $storage = new DoliStorage($db, $conf);
  932. try {
  933. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  934. $expire = true;
  935. // Is token expired or will token expire in the next 30 seconds
  936. // if (is_object($tokenobj)) {
  937. // $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
  938. // }
  939. // Token expired so we refresh it
  940. if (is_object($tokenobj) && $expire) {
  941. $credentials = new Credentials(
  942. getDolGlobalString('OAUTH_'.$this->oauth_service.'_ID'),
  943. getDolGlobalString('OAUTH_'.$this->oauth_service.'_SECRET'),
  944. getDolGlobalString('OAUTH_'.$this->oauth_service.'_URLAUTHORIZE')
  945. );
  946. $serviceFactory = new \OAuth\ServiceFactory();
  947. $oauthname = explode('-', $OAUTH_SERVICENAME);
  948. // ex service is Google-Emails we need only the first part Google
  949. $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
  950. // We have to save the token because Google give it only once
  951. $refreshtoken = $tokenobj->getRefreshToken();
  952. $tokenobj = $apiService->refreshAccessToken($tokenobj);
  953. $tokenobj->setRefreshToken($refreshtoken);
  954. $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
  955. }
  956. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  957. if (is_object($tokenobj)) {
  958. $token = $tokenobj->getAccessToken();
  959. } else {
  960. $this->error = "Token not found";
  961. return -1;
  962. }
  963. } catch (Exception $e) {
  964. // Return an error if token not found
  965. $this->error = $e->getMessage();
  966. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  967. return -1;
  968. }
  969. $cm = new ClientManager();
  970. $client = $cm->make([
  971. 'host' => $this->host,
  972. 'port' => $this->port,
  973. 'encryption' => 'ssl',
  974. 'validate_cert' => true,
  975. 'protocol' => 'imap',
  976. 'username' => $this->login,
  977. 'password' => $token,
  978. 'authentication' => "oauth",
  979. ]);
  980. } else {
  981. // Mode login/pass with PHP-IMAP
  982. $cm = new ClientManager();
  983. $client = $cm->make([
  984. 'host' => $this->host,
  985. 'port' => $this->port,
  986. 'encryption' => 'ssl',
  987. 'validate_cert' => true,
  988. 'protocol' => 'imap',
  989. 'username' => $this->login,
  990. 'password' => $this->password,
  991. 'authentication' => "login",
  992. ]);
  993. }
  994. try {
  995. $client->connect();
  996. } catch (ConnectionFailedException $e) {
  997. $this->error = $e->getMessage();
  998. $this->errors[] = $this->error;
  999. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1000. return -1;
  1001. }
  1002. $host = dol_getprefix('email');
  1003. } else {
  1004. // Use native IMAP functions
  1005. if (!function_exists('imap_open')) {
  1006. $this->error = 'IMAP function not enabled on your PHP';
  1007. return -2;
  1008. }
  1009. $sourcedir = $this->source_directory;
  1010. $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
  1011. $connectstringserver = $this->getConnectStringIMAP();
  1012. $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
  1013. $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
  1014. $connection = imap_open($connectstringsource, $this->login, $this->password);
  1015. if (!$connection) {
  1016. $this->error = 'Failed to open IMAP connection '.$connectstringsource.' '.imap_last_error();
  1017. return -3;
  1018. }
  1019. imap_errors(); // Clear stack of errors.
  1020. $host = dol_getprefix('email');
  1021. //$host = '123456';
  1022. // Define the IMAP search string
  1023. // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible)
  1024. // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2
  1025. //$search='ALL';
  1026. }
  1027. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1028. $criteria = array(array('UNDELETED')); // Seems not supported by some servers
  1029. foreach ($this->filters as $rule) {
  1030. if (empty($rule['status'])) {
  1031. continue;
  1032. }
  1033. if ($rule['type'] == 'to') {
  1034. $tmprulevaluearray = explode('*', $rule['rulevalue']);
  1035. if (count($tmprulevaluearray) >= 2) {
  1036. foreach ($tmprulevaluearray as $tmprulevalue) {
  1037. array_push($criteria, array("TO" => $tmprulevalue));
  1038. }
  1039. } else {
  1040. array_push($criteria, array("TO" => $rule['rulevalue']));
  1041. }
  1042. }
  1043. if ($rule['type'] == 'bcc') {
  1044. array_push($criteria, array("BCC" => $rule['rulevalue']));
  1045. }
  1046. if ($rule['type'] == 'cc') {
  1047. array_push($criteria, array("CC" => $rule['rulevalue']));
  1048. }
  1049. if ($rule['type'] == 'from') {
  1050. array_push($criteria, array("FROM" => $rule['rulevalue']));
  1051. }
  1052. if ($rule['type'] == 'subject') {
  1053. array_push($criteria, array("SUBJECT" => $rule['rulevalue']));
  1054. }
  1055. if ($rule['type'] == 'body') {
  1056. array_push($criteria, array("BODY" => $rule['rulevalue']));
  1057. }
  1058. if ($rule['type'] == 'header') {
  1059. array_push($criteria, array("HEADER" => $rule['rulevalue']));
  1060. }
  1061. if ($rule['type'] == 'notinsubject') {
  1062. array_push($criteria, array("SUBJECT NOT" => $rule['rulevalue']));
  1063. }
  1064. if ($rule['type'] == 'notinbody') {
  1065. array_push($criteria, array("BODY NOT" => $rule['rulevalue']));
  1066. }
  1067. if ($rule['type'] == 'seen') {
  1068. array_push($criteria, array("SEEN"));
  1069. }
  1070. if ($rule['type'] == 'unseen') {
  1071. array_push($criteria, array("UNSEEN"));
  1072. }
  1073. if ($rule['type'] == 'unanswered') {
  1074. array_push($criteria, array("UNANSWERED"));
  1075. }
  1076. if ($rule['type'] == 'answered') {
  1077. array_push($criteria, array("ANSWERED"));
  1078. }
  1079. if ($rule['type'] == 'smaller') {
  1080. array_push($criteria, array("SMALLER"));
  1081. }
  1082. if ($rule['type'] == 'larger') {
  1083. array_push($criteria, array("LARGER"));
  1084. }
  1085. // Rules to filter after the search imap
  1086. if ($rule['type'] == 'withtrackingidinmsgid') {
  1087. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1088. }
  1089. if ($rule['type'] == 'withouttrackingidinmsgid') {
  1090. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1091. }
  1092. if ($rule['type'] == 'withtrackingid') {
  1093. $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
  1094. }
  1095. if ($rule['type'] == 'withouttrackingid') {
  1096. $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
  1097. }
  1098. if ($rule['type'] == 'isanswer') {
  1099. $searchfilterisanswer++; $searchhead .= '/References.*@.*/';
  1100. }
  1101. if ($rule['type'] == 'isnotanswer') {
  1102. $searchfilterisnotanswer++; $searchhead .= '! /References.*@.*/';
  1103. }
  1104. }
  1105. if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined.
  1106. $fromdate = 0;
  1107. if ($this->datelastok) {
  1108. $fromdate = $this->datelastok;
  1109. }
  1110. if ($fromdate > 0) {
  1111. // $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10)
  1112. array_push($criteria, array("SINCE" => date('j-M-Y', $fromdate - 1)));
  1113. }
  1114. //$search.=($search?' ':'').'SINCE 8-Apr-2022';
  1115. }
  1116. dol_syslog("IMAP search string = ".var_export($criteria, true));
  1117. $search = var_export($criteria, true);
  1118. } else {
  1119. $search = 'UNDELETED'; // Seems not supported by some servers
  1120. foreach ($this->filters as $rule) {
  1121. if (empty($rule['status'])) {
  1122. continue;
  1123. }
  1124. if ($rule['type'] == 'to') {
  1125. $tmprulevaluearray = explode('*', $rule['rulevalue']);
  1126. if (count($tmprulevaluearray) >= 2) {
  1127. foreach ($tmprulevaluearray as $tmprulevalue) {
  1128. $search .= ($search ? ' ' : '').'TO "'.str_replace('"', '', $tmprulevalue).'"';
  1129. }
  1130. } else {
  1131. $search .= ($search ? ' ' : '').'TO "'.str_replace('"', '', $rule['rulevalue']).'"';
  1132. }
  1133. }
  1134. if ($rule['type'] == 'bcc') {
  1135. $search .= ($search ? ' ' : '').'BCC';
  1136. }
  1137. if ($rule['type'] == 'cc') {
  1138. $search .= ($search ? ' ' : '').'CC';
  1139. }
  1140. if ($rule['type'] == 'from') {
  1141. $search .= ($search ? ' ' : '').'FROM "'.str_replace('"', '', $rule['rulevalue']).'"';
  1142. }
  1143. if ($rule['type'] == 'subject') {
  1144. $search .= ($search ? ' ' : '').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
  1145. }
  1146. if ($rule['type'] == 'body') {
  1147. $search .= ($search ? ' ' : '').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
  1148. }
  1149. if ($rule['type'] == 'header') {
  1150. $search .= ($search ? ' ' : '').'HEADER '.$rule['rulevalue'];
  1151. }
  1152. if ($rule['type'] == 'notinsubject') {
  1153. $search .= ($search ? ' ' : '').'SUBJECT NOT "'.str_replace('"', '', $rule['rulevalue']).'"';
  1154. }
  1155. if ($rule['type'] == 'notinbody') {
  1156. $search .= ($search ? ' ' : '').'BODY NOT "'.str_replace('"', '', $rule['rulevalue']).'"';
  1157. }
  1158. if ($rule['type'] == 'seen') {
  1159. $search .= ($search ? ' ' : '').'SEEN';
  1160. }
  1161. if ($rule['type'] == 'unseen') {
  1162. $search .= ($search ? ' ' : '').'UNSEEN';
  1163. }
  1164. if ($rule['type'] == 'unanswered') {
  1165. $search .= ($search ? ' ' : '').'UNANSWERED';
  1166. }
  1167. if ($rule['type'] == 'answered') {
  1168. $search .= ($search ? ' ' : '').'ANSWERED';
  1169. }
  1170. if ($rule['type'] == 'smaller') {
  1171. $search .= ($search ? ' ' : '').'SMALLER "'.str_replace('"', '', $rule['rulevalue']).'"';
  1172. }
  1173. if ($rule['type'] == 'larger') {
  1174. $search .= ($search ? ' ' : '').'LARGER "'.str_replace('"', '', $rule['rulevalue']).'"';
  1175. }
  1176. // Rules to filter after the search imap
  1177. if ($rule['type'] == 'withtrackingidinmsgid') {
  1178. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1179. }
  1180. if ($rule['type'] == 'withouttrackingidinmsgid') {
  1181. $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
  1182. }
  1183. if ($rule['type'] == 'withtrackingid') {
  1184. $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
  1185. }
  1186. if ($rule['type'] == 'withouttrackingid') {
  1187. $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
  1188. }
  1189. if ($rule['type'] == 'isanswer') {
  1190. $searchfilterisanswer++; $searchhead .= '/References.*@.*/';
  1191. }
  1192. if ($rule['type'] == 'isnotanswer') {
  1193. $searchfilterisnotanswer++; $searchhead .= '! /References.*@.*/';
  1194. }
  1195. }
  1196. if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined.
  1197. $fromdate = 0;
  1198. if ($this->datelastok) {
  1199. $fromdate = $this->datelastok;
  1200. }
  1201. if ($fromdate > 0) {
  1202. $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10)
  1203. }
  1204. //$search.=($search?' ':'').'SINCE 8-Apr-2018';
  1205. }
  1206. dol_syslog("IMAP search string = ".$search);
  1207. //var_dump($search);
  1208. }
  1209. $nbemailprocessed = 0;
  1210. $nbemailok = 0;
  1211. $nbactiondone = 0;
  1212. $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8");
  1213. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1214. try {
  1215. //$criteria = [['ALL']];
  1216. //$Query = $client->getFolders()[0]->messages()->where($criteria);
  1217. $f = $client->getFolders(false, $this->source_directory);
  1218. $Query = $f[0]->messages()->where($criteria);
  1219. } catch (InvalidWhereQueryCriteriaException $e) {
  1220. $this->error = $e->getMessage();
  1221. $this->errors[] = $this->error;
  1222. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1223. return -1;
  1224. } catch (Exception $e) {
  1225. $this->error = $e->getMessage();
  1226. $this->errors[] = $this->error;
  1227. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1228. return -1;
  1229. }
  1230. try {
  1231. //var_dump($Query->count());
  1232. $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder("asc")->get();
  1233. //var_dump($arrayofemail);
  1234. } catch (Exception $e) {
  1235. $this->error = $e->getMessage();
  1236. $this->errors[] = $this->error;
  1237. dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
  1238. return -1;
  1239. }
  1240. } else {
  1241. // Scan IMAP inbox
  1242. $arrayofemail = imap_search($connection, $search, null, $charset);
  1243. if ($arrayofemail === false) {
  1244. // Nothing found or search string not understood
  1245. $mapoferrrors = imap_errors();
  1246. if ($mapoferrrors !== false) {
  1247. $error++;
  1248. $this->error = "Search string not understood - ".join(',', $mapoferrrors);
  1249. $this->errors[] = $this->error;
  1250. }
  1251. }
  1252. }
  1253. // Loop on each email found
  1254. if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
  1255. // Loop to get part html and plain
  1256. /*
  1257. 0 multipart/mixed
  1258. 1 multipart/alternative
  1259. 1.1 text/plain
  1260. 1.2 text/html
  1261. 2 message/rfc822
  1262. 2 multipart/mixed
  1263. 2.1 multipart/alternative
  1264. 2.1.1 text/plain
  1265. 2.1.2 text/html
  1266. 2.2 message/rfc822
  1267. 2.2 multipart/alternative
  1268. 2.2.1 text/plain
  1269. 2.2.2 text/html
  1270. */
  1271. dol_syslog("Start of loop on email", LOG_INFO, 1);
  1272. $iforemailloop = 0;
  1273. foreach ($arrayofemail as $imapemail) {
  1274. if ($nbemailprocessed > 1000) {
  1275. break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect)
  1276. }
  1277. $iforemailloop++;
  1278. // GET header and overview datas
  1279. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1280. $header = $imapemail->getHeader()->raw;
  1281. $overview = $imapemail->getAttributes();
  1282. } else {
  1283. //$header = imap_headerinfo($connection, $imapemail);
  1284. $header = imap_fetchheader($connection, $imapemail, 0);
  1285. $overview = imap_fetch_overview($connection, $imapemail, 0);
  1286. }
  1287. $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines
  1288. $matches = array();
  1289. preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
  1290. $headers = array_combine($matches[1], $matches[2]);
  1291. //var_dump($headers);exit;
  1292. if (!empty($headers['in-reply-to']) && empty($headers['In-Reply-To'])) {
  1293. $headers['In-Reply-To'] = $headers['in-reply-to'];
  1294. }
  1295. if (!empty($headers['references']) && empty($headers['References'])) {
  1296. $headers['References'] = $headers['references'];
  1297. }
  1298. if (!empty($headers['message-id']) && empty($headers['Message-ID'])) {
  1299. $headers['Message-ID'] = $headers['message-id'];
  1300. }
  1301. if (!empty($headers['subject']) && empty($headers['Subject'])) {
  1302. $headers['Subject'] = $headers['subject'];
  1303. }
  1304. $headers['Subject'] = $this->decodeSMTPSubject($headers['Subject']);
  1305. $emailto = $this->decodeSMTPSubject($overview[0]->to);
  1306. $operationslog .= '<br>Process email '.dol_escape_htmltag($iforemailloop)." - References: ".dol_escape_htmltag($headers['References'])." - Subject: ".dol_escape_htmltag($headers['Subject']);
  1307. dol_syslog("** Process email ".$iforemailloop." References: ".$headers['References']." Subject: ".$headers['Subject']);
  1308. $trackidfoundintorecipienttype = '';
  1309. $trackidfoundintorecipientid = 0;
  1310. $reg = array();
  1311. // See also later list of all supported tags...
  1312. if (preg_match('/\+(thi|ctc|use|mem|sub|proj|tas|con|tic|job|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
  1313. $trackidfoundintorecipienttype = $reg[1];
  1314. $trackidfoundintorecipientid = $reg[2];
  1315. } elseif (preg_match('/\+emailing-(\w+)@/', $emailto, $reg)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient'
  1316. $trackidfoundintorecipienttype = 'emailing';
  1317. $trackidfoundintorecipientid = $reg[1];
  1318. }
  1319. // If there is a filter on trackid
  1320. if ($searchfilterdoltrackid > 0) {
  1321. if (empty($trackidfoundintorecipienttype)) {
  1322. if (empty($headers['References']) || !preg_match('/@'.preg_quote($host, '/').'/', $headers['References'])) {
  1323. $nbemailprocessed++;
  1324. dol_syslog(" Discarded - No suffix in email recipient and no Header References found matching signature of application so with a trackid");
  1325. continue; // Exclude email
  1326. }
  1327. }
  1328. }
  1329. if ($searchfilternodoltrackid > 0) {
  1330. if (!empty($trackidfoundintorecipienttype) || (!empty($headers['References']) && preg_match('/@'.preg_quote($host, '/').'/', $headers['References']))) {
  1331. $nbemailprocessed++;
  1332. dol_syslog(" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
  1333. continue; // Exclude email
  1334. }
  1335. }
  1336. if ($searchfilterisanswer > 0) {
  1337. if (empty($headers['In-Reply-To'])) {
  1338. $nbemailprocessed++;
  1339. dol_syslog(" Discarded - Email is not an answer (no In-Reply-To header)");
  1340. continue; // Exclude email
  1341. }
  1342. // Note: we can have
  1343. // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten)
  1344. $isanswer = 0;
  1345. if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) {
  1346. $isanswer = 1;
  1347. }
  1348. //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
  1349. //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
  1350. if (!$isanswer) {
  1351. $nbemailprocessed++;
  1352. dol_syslog(" Discarded - Email is not an answer (no RE prefix in subject)");
  1353. continue; // Exclude email
  1354. }
  1355. }
  1356. if ($searchfilterisnotanswer > 0) {
  1357. if (!empty($headers['In-Reply-To'])) {
  1358. // Note: we can have
  1359. // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten)
  1360. $isanswer = 0;
  1361. if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) {
  1362. $isanswer = 1;
  1363. }
  1364. //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
  1365. //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
  1366. if ($isanswer) {
  1367. $nbemailprocessed++;
  1368. dol_syslog(" Discarded - Email is an answer");
  1369. continue; // Exclude email
  1370. }
  1371. }
  1372. }
  1373. //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." selected<br>\n";
  1374. $thirdpartystatic = new Societe($this->db);
  1375. $contactstatic = new Contact($this->db);
  1376. $projectstatic = new Project($this->db);
  1377. $nbactiondoneforemail = 0;
  1378. $errorforemail = 0;
  1379. $errorforactions = 0;
  1380. $thirdpartyfoundby = '';
  1381. $contactfoundby = '';
  1382. $projectfoundby = '';
  1383. $ticketfoundby = '';
  1384. $candidaturefoundby = '';
  1385. $this->db->begin();
  1386. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1387. dol_syslog("msgid=".$overview['message_id']." date=".dol_print_date($overview['date'], 'dayrfc', 'gmt')." from=".$overview['from']." to=".$overview['to']." subject=".$overview['subject']);
  1388. // Removed emojis
  1389. $overview['subject'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview['subject']);
  1390. } else {
  1391. 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);
  1392. $overview[0]->subject = $this->decodeSMTPSubject($overview[0]->subject);
  1393. $overview[0]->from = $this->decodeSMTPSubject($overview[0]->from);
  1394. // Removed emojis
  1395. $overview[0]->subject = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview[0]->subject);
  1396. }
  1397. // GET IMAP email structure/content
  1398. global $htmlmsg, $plainmsg, $charset, $attachments;
  1399. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1400. if ($imapemail->hasHTMLBody()) {
  1401. $htmlmsg = $imapemail->getHTMLBody();
  1402. }
  1403. if ($imapemail->hasTextBody()) {
  1404. $plainmsg = $imapemail->getTextBody();
  1405. }
  1406. if ($imapemail->hasAttachments()) {
  1407. $attachments = $imapemail->getAttachments()->all();
  1408. } else {
  1409. $attachments = [];
  1410. }
  1411. } else {
  1412. $this->getmsg($connection, $imapemail);
  1413. }
  1414. //print $plainmsg;
  1415. //var_dump($plainmsg); exit;
  1416. //$htmlmsg,$plainmsg,$charset,$attachments
  1417. $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag($htmlmsg, 0);
  1418. // Removed emojis
  1419. $messagetext = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $messagetext);
  1420. //var_dump($plainmsg);
  1421. //var_dump($htmlmsg);
  1422. //var_dump($messagetext);
  1423. //var_dump($charset);
  1424. //var_dump($attachments);
  1425. //exit;
  1426. // Parse IMAP email structure
  1427. /*
  1428. $structure = imap_fetchstructure($connection, $imapemail, 0);
  1429. $partplain = $parthtml = -1;
  1430. $encodingplain = $encodinghtml = '';
  1431. $result = createPartArray($structure, '');
  1432. foreach($result as $part)
  1433. {
  1434. // $part['part_object']->type seems 0 for content
  1435. // $part['part_object']->type seems 5 for attachment
  1436. if (empty($part['part_object'])) continue;
  1437. if ($part['part_object']->subtype == 'HTML')
  1438. {
  1439. $parthtml=$part['part_number'];
  1440. if ($part['part_object']->encoding == 4)
  1441. {
  1442. $encodinghtml = 'aaa';
  1443. }
  1444. }
  1445. if ($part['part_object']->subtype == 'PLAIN')
  1446. {
  1447. $partplain=$part['part_number'];
  1448. if ($part['part_object']->encoding == 4)
  1449. {
  1450. $encodingplain = 'rr';
  1451. }
  1452. }
  1453. }
  1454. //var_dump($result);
  1455. //var_dump($partplain);
  1456. //var_dump($parthtml);
  1457. //var_dump($structure);
  1458. //var_dump($parthtml);
  1459. //var_dump($partplain);
  1460. $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK);
  1461. */
  1462. //var_dump($messagetext);
  1463. //var_dump($structure->parts[0]->parts);
  1464. //print $header;
  1465. //print $messagetext;
  1466. //exit;
  1467. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  1468. $fromstring = $overview['from'];
  1469. $sender = $overview['sender'];
  1470. $to = $overview['to'];
  1471. $sendtocc = empty($overview['cc']) ? '' : $overview['cc'];
  1472. $sendtobcc = empty($overview['bcc']) ? '' : $overview['bcc'];
  1473. $date = $overview['date'];
  1474. $msgid = str_replace(array('<', '>'), '', $overview['message_id']);
  1475. $subject = $overview['subject'];
  1476. } else {
  1477. $fromstring = $overview[0]->from;
  1478. $sender = $overview[0]->sender;
  1479. $to = $overview[0]->to;
  1480. $sendtocc = $overview[0]->cc;
  1481. $sendtobcc = $overview[0]->bcc;
  1482. $date = $overview[0]->udate;
  1483. $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id);
  1484. $subject = $overview[0]->subject;
  1485. //var_dump($msgid);exit;
  1486. }
  1487. $reg = array();
  1488. if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) {
  1489. $from = $reg[2];
  1490. $fromtext = $reg[1];
  1491. } else {
  1492. $from = $fromstring;
  1493. $fromtext = '';
  1494. }
  1495. $fk_element_id = 0; $fk_element_type = '';
  1496. $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
  1497. // Analyze TrackId in field References. For example:
  1498. // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e>
  1499. // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e>
  1500. // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e>
  1501. $trackid = '';
  1502. $objectid = 0;
  1503. $objectemail = null;
  1504. $reg = array();
  1505. if (!empty($headers['References'])) {
  1506. $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']);
  1507. // var_dump($headers['References']);
  1508. // var_dump($arrayofreferences);
  1509. foreach ($arrayofreferences as $reference) {
  1510. //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($date, 'dayhour').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."<br>\n";
  1511. if (!empty($trackidfoundintorecipienttype)) {
  1512. $resultsearchtrackid = -1;
  1513. $reg[1] = $trackidfoundintorecipienttype;
  1514. $reg[2] = $trackidfoundintorecipientid;
  1515. } else {
  1516. $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $reference, $reg);
  1517. if (empty($resultsearchtrackid) && getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
  1518. $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE'), '/').'/', $reference, $reg);
  1519. }
  1520. }
  1521. if (!empty($resultsearchtrackid)) {
  1522. // We found a tracker (in recipient email or into a Reference matching the Dolibarr server)
  1523. $trackid = $reg[1].$reg[2];
  1524. $objectid = $reg[2];
  1525. // See also list into interface_50_modAgenda_ActionsAuto
  1526. if ($reg[1] == 'thi') { // Third-party
  1527. $objectemail = new Societe($this->db);
  1528. }
  1529. if ($reg[1] == 'ctc') { // Contact
  1530. $objectemail = new Contact($this->db);
  1531. }
  1532. if ($reg[1] == 'inv') { // Customer Invoice
  1533. $objectemail = new Facture($this->db);
  1534. }
  1535. if ($reg[1] == 'sinv') { // Supplier Invoice
  1536. $objectemail = new FactureFournisseur($this->db);
  1537. }
  1538. if ($reg[1] == 'pro') { // Customer Proposal
  1539. $objectemail = new Propal($this->db);
  1540. }
  1541. if ($reg[1] == 'ord') { // Sale Order
  1542. $objectemail = new Commande($this->db);
  1543. }
  1544. if ($reg[1] == 'shi') { // Shipment
  1545. $objectemail = new Expedition($this->db);
  1546. }
  1547. if ($reg[1] == 'spro') { // Supplier Proposal
  1548. $objectemail = new SupplierProposal($this->db);
  1549. }
  1550. if ($reg[1] == 'sord') { // Supplier Order
  1551. $objectemail = new CommandeFournisseur($this->db);
  1552. }
  1553. if ($reg[1] == 'rec') { // Reception
  1554. $objectemail = new Reception($this->db);
  1555. }
  1556. if ($reg[1] == 'proj') { // Project
  1557. $objectemail = new Project($this->db);
  1558. }
  1559. if ($reg[1] == 'tas') { // Task
  1560. $objectemail = new Task($this->db);
  1561. }
  1562. if ($reg[1] == 'con') { // Contact
  1563. $objectemail = new Contact($this->db);
  1564. }
  1565. if ($reg[1] == 'use') { // User
  1566. $objectemail = new User($this->db);
  1567. }
  1568. if ($reg[1] == 'tic') { // Ticket
  1569. $objectemail = new Ticket($this->db);
  1570. }
  1571. if ($reg[1] == 'recruitmentcandidature') { // Recruiting Candidate
  1572. $objectemail = new RecruitmentCandidature($this->db);
  1573. }
  1574. if ($reg[1] == 'mem') { // Member
  1575. $objectemail = new Adherent($this->db);
  1576. }
  1577. /*if ($reg[1] == 'leav') { // Leave / Holiday
  1578. $objectemail = new Holiday($db);
  1579. }
  1580. if ($reg[1] == 'exp') { // ExpenseReport
  1581. $objectemail = new ExpenseReport($db);
  1582. }*/
  1583. } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) {
  1584. // This is an external reference, we check if we have it in our database
  1585. if (!is_object($objectemail)) {
  1586. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ticket where email_msgid = '".$this->db->escape($reg[1])."'";
  1587. $resql = $this->db->query($sql);
  1588. if ($resql) {
  1589. $obj = $this->db->fetch_object($resql);
  1590. if ($obj) {
  1591. $objectid = $obj->rowid;
  1592. $objectemail = new Ticket($this->db);
  1593. $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1594. }
  1595. } else {
  1596. $errorforemail++;
  1597. }
  1598. }
  1599. if (!is_object($objectemail)) {
  1600. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."projet where email_msgid = '".$this->db->escape($reg[1])."'";
  1601. $resql = $this->db->query($sql);
  1602. if ($resql) {
  1603. $obj = $this->db->fetch_object($resql);
  1604. if ($obj) {
  1605. $objectid = $obj->rowid;
  1606. $objectemail = new Project($this->db);
  1607. $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1608. }
  1609. } else {
  1610. $errorforemail++;
  1611. }
  1612. }
  1613. if (!is_object($objectemail)) {
  1614. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1])."'";
  1615. $resql = $this->db->query($sql);
  1616. if ($resql) {
  1617. $obj = $this->db->fetch_object($resql);
  1618. if ($obj) {
  1619. $objectid = $obj->rowid;
  1620. $objectemail = new RecruitmentCandidature($this->db);
  1621. $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
  1622. }
  1623. } else {
  1624. $errorforemail++;
  1625. }
  1626. }
  1627. }
  1628. // Load object linked to email
  1629. if (is_object($objectemail)) {
  1630. $result = $objectemail->fetch($objectid);
  1631. if ($result > 0) {
  1632. $fk_element_id = $objectemail->id;
  1633. $fk_element_type = $objectemail->element;
  1634. // Fix fk_element_type
  1635. if ($fk_element_type == 'facture') {
  1636. $fk_element_type = 'invoice';
  1637. }
  1638. if (get_class($objectemail) != 'Societe') {
  1639. $thirdpartyid = $objectemail->fk_soc;
  1640. } else {
  1641. $thirdpartyid = $objectemail->id;
  1642. }
  1643. if (get_class($objectemail) != 'Contact') {
  1644. $contactid = $objectemail->fk_socpeople;
  1645. } else {
  1646. $contactid = $objectemail->id;
  1647. }
  1648. if (get_class($objectemail) != 'Project') {
  1649. $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
  1650. } else {
  1651. $projectid = $objectemail->id;
  1652. }
  1653. }
  1654. }
  1655. // Project
  1656. if ($projectid > 0) {
  1657. $result = $projectstatic->fetch($projectid);
  1658. if ($result <= 0) {
  1659. $projectstatic->id = 0;
  1660. } else {
  1661. $projectid = $projectstatic->id;
  1662. if ($trackid) {
  1663. $projectfoundby = 'trackid ('.$trackid.')';
  1664. }
  1665. if (empty($contactid)) {
  1666. $contactid = $projectstatic->fk_contact;
  1667. }
  1668. if (empty($thirdpartyid)) {
  1669. $thirdpartyid = $projectstatic->fk_soc;
  1670. }
  1671. }
  1672. }
  1673. // Contact
  1674. if ($contactid > 0) {
  1675. $result = $contactstatic->fetch($contactid);
  1676. if ($result <= 0) {
  1677. $contactstatic->id = 0;
  1678. } else {
  1679. $contactid = $contactstatic->id;
  1680. if ($trackid) {
  1681. $contactfoundby = 'trackid ('.$trackid.')';
  1682. }
  1683. if (empty($thirdpartyid)) {
  1684. $thirdpartyid = $contactstatic->fk_soc;
  1685. }
  1686. }
  1687. }
  1688. // Thirdparty
  1689. if ($thirdpartyid > 0) {
  1690. $result = $thirdpartystatic->fetch($thirdpartyid);
  1691. if ($result <= 0) {
  1692. $thirdpartystatic->id = 0;
  1693. } else {
  1694. $thirdpartyid = $thirdpartystatic->id;
  1695. if ($trackid) {
  1696. $thirdpartyfoundby = 'trackid ('.$trackid.')';
  1697. }
  1698. }
  1699. }
  1700. if (is_object($objectemail)) {
  1701. break; // Exit loop of references. We already found an accurate reference
  1702. }
  1703. }
  1704. }
  1705. if (empty($contactid)) { // Try to find contact using email
  1706. $result = $contactstatic->fetch(0, null, '', $from);
  1707. if ($result > 0) {
  1708. $contactid = $contactstatic->id;
  1709. $contactfoundby = 'email of contact ('.$from.')';
  1710. if (empty($thirdpartyid) && $contactstatic->socid > 0) {
  1711. $result = $thirdpartystatic->fetch($contactstatic->socid);
  1712. if ($result > 0) {
  1713. $thirdpartyid = $thirdpartystatic->id;
  1714. $thirdpartyfoundby = 'email of contact ('.$from.')';
  1715. }
  1716. }
  1717. }
  1718. }
  1719. if (empty($thirdpartyid)) { // Try to find thirdparty using email
  1720. $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from);
  1721. if ($result > 0) {
  1722. $thirdpartyfoundby = 'email ('.$from.')';
  1723. }
  1724. }
  1725. // Do operations
  1726. if ($mode < 2) {
  1727. foreach ($this->actions as $operation) {
  1728. $errorforthisaction = 0;
  1729. if ($errorforactions) {
  1730. break;
  1731. }
  1732. if (empty($operation['status'])) {
  1733. continue;
  1734. }
  1735. // Make Operation
  1736. dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id);
  1737. 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
  1738. $actioncode = 'EMAIL_IN';
  1739. // If we scan the Sent box, we use the code for out email
  1740. if ($this->source_directory == 'Sent') {
  1741. $actioncode = 'EMAIL_OUT';
  1742. }
  1743. $description = $descriptiontitle = $descriptionmeta = $descriptionfull = '';
  1744. $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid);
  1745. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject));
  1746. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring));
  1747. if ($sender) {
  1748. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender));
  1749. }
  1750. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to));
  1751. if ($sendtocc) {
  1752. $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc));
  1753. }
  1754. // Search and create thirdparty
  1755. if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') {
  1756. if (empty($operation['actionparam'])) {
  1757. $errorforactions++;
  1758. $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;";
  1759. $this->errors[] = $this->error;
  1760. } else {
  1761. $actionparam = $operation['actionparam'];
  1762. $idtouseforthirdparty = '';
  1763. $nametouseforthirdparty = '';
  1764. $emailtouseforthirdparty = '';
  1765. // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....'
  1766. $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
  1767. foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
  1768. $sourcestring = '';
  1769. $sourcefield = '';
  1770. $regexstring = '';
  1771. $regforregex = array();
  1772. if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
  1773. $sourcefield = $regforregex[1];
  1774. $regexstring = $regforregex[2];
  1775. }
  1776. if (!empty($sourcefield) && !empty($regexstring)) {
  1777. if (strtolower($sourcefield) == 'body') {
  1778. $sourcestring = $messagetext;
  1779. } elseif (strtolower($sourcefield) == 'subject') {
  1780. $sourcestring = $subject;
  1781. } elseif (strtolower($sourcefield) == 'header') {
  1782. $sourcestring = $header;
  1783. }
  1784. if ($sourcestring) {
  1785. $regforval = array();
  1786. //var_dump($regexstring);var_dump($sourcestring);
  1787. if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) {
  1788. //var_dump($regforval[count($regforval)-1]);exit;
  1789. // Overwrite param $tmpproperty
  1790. if ($propertytooverwrite == 'id') {
  1791. $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1792. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtolower($sourcefield).' -> Found idtouseforthirdparty='.dol_escape_htmltag($idtouseforthirdparty);
  1793. } elseif ($propertytooverwrite == 'email') {
  1794. $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1795. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtolower($sourcefield).' -> Found propertytooverwrite='.dol_escape_htmltag($propertytooverwrite);
  1796. } else {
  1797. $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
  1798. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtolower($sourcefield).' -> Found nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
  1799. }
  1800. } else {
  1801. // Regex not found
  1802. $idtouseforthirdparty = null;
  1803. $nametouseforthirdparty = null;
  1804. $emailtouseforthirdparty = null;
  1805. $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtolower($sourcefield).' -> Not found';
  1806. }
  1807. //var_dump($object->$tmpproperty);exit;
  1808. } else {
  1809. // Nothing can be done for this param
  1810. $errorforactions++;
  1811. $this->error = 'The extract rule to use to load thirdparty has an unknown source (must be HEADER, SUBJECT or BODY)';
  1812. $this->errors[] = $this->error;
  1813. }
  1814. } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
  1815. //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1];
  1816. //else $object->$tmpproperty = $reg[1];
  1817. if ($propertytooverwrite == 'id') {
  1818. $idtouseforthirdparty = $reg[2];
  1819. $operationslog .= '<br>We set property idtouseforthrdparty='.dol_escape_htmltag($idtouseforthirdparty);
  1820. } elseif ($propertytooverwrite == 'email') {
  1821. $emailtouseforthirdparty = $reg[2];
  1822. $operationslog .= '<br>We set property emailtouseforthrdparty='.dol_escape_htmltag($emailtouseforthirdparty);
  1823. } else {
  1824. $nametouseforthirdparty = $reg[2];
  1825. $operationslog .= '<br>We set property nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
  1826. }
  1827. } else {
  1828. $errorforactions++;
  1829. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  1830. $this->errors[] = $this->error;
  1831. break;
  1832. }
  1833. }
  1834. if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty)) {
  1835. $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty);
  1836. if ($result < 0) {
  1837. $errorforactions++;
  1838. $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)';
  1839. $this->errors[] = $this->error;
  1840. break;
  1841. } elseif ($result == 0) {
  1842. if ($operation['type'] == 'loadthirdparty') {
  1843. dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found");
  1844. $errorforactions++;
  1845. $langs->load("errors");
  1846. $this->error = $langs->trans('ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty);
  1847. $this->errors[] = $this->error;
  1848. } elseif ($operation['type'] == 'loadandcreatethirdparty') {
  1849. dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found. We try to create it.");
  1850. // Create thirdparty
  1851. $thirdpartystatic->name = $nametouseforthirdparty;
  1852. if ($fromtext != $nametouseforthirdparty) {
  1853. $thirdpartystatic->name_alias = $fromtext;
  1854. }
  1855. $thirdpartystatic->email = ($emailtouseforthirdparty ? $emailtouseforthirdparty : $from);
  1856. // Overwrite values with values extracted from source email
  1857. $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  1858. if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
  1859. $thirdpartystatic->code_client = 'auto';
  1860. }
  1861. if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
  1862. $thirdpartystatic->code_fournisseur = 'auto';
  1863. }
  1864. if ($errorforthisaction) {
  1865. $errorforactions++;
  1866. } else {
  1867. $result = $thirdpartystatic->create($user);
  1868. if ($result <= 0) {
  1869. $errorforactions++;
  1870. $this->error = $thirdpartystatic->error;
  1871. $this->errors = $thirdpartystatic->errors;
  1872. } else {
  1873. $operationslog .= '<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
  1874. }
  1875. }
  1876. }
  1877. }
  1878. }
  1879. }
  1880. } elseif ($operation['type'] == 'recordevent') {
  1881. // Create event
  1882. $actioncomm = new ActionComm($this->db);
  1883. $alreadycreated = $actioncomm->fetch(0, '', '', $msgid);
  1884. if ($alreadycreated == 0) {
  1885. if ($projectstatic->id > 0) {
  1886. if ($projectfoundby) {
  1887. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby);
  1888. }
  1889. }
  1890. if ($thirdpartystatic->id > 0) {
  1891. if ($thirdpartyfoundby) {
  1892. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  1893. }
  1894. }
  1895. if ($contactstatic->id > 0) {
  1896. if ($contactfoundby) {
  1897. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  1898. }
  1899. }
  1900. $description = $descriptiontitle;
  1901. $description = dol_concatdesc($description, "-----");
  1902. $description = dol_concatdesc($description, $descriptionmeta);
  1903. $description = dol_concatdesc($description, "-----");
  1904. $description = dol_concatdesc($description, $messagetext);
  1905. $descriptionfull = $description;
  1906. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  1907. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  1908. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  1909. }
  1910. // Insert record of emails sent
  1911. $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
  1912. $actioncomm->code = 'AC_'.$actioncode;
  1913. $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$from;
  1914. $actioncomm->note_private = $descriptionfull;
  1915. $actioncomm->fk_project = $projectstatic->id;
  1916. $actioncomm->datep = $date; // date of email
  1917. $actioncomm->datef = $date; // date of email
  1918. $actioncomm->percentage = -1; // Not applicable
  1919. $actioncomm->socid = $thirdpartystatic->id;
  1920. $actioncomm->contact_id = $contactstatic->id;
  1921. $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id => '') : array());
  1922. $actioncomm->authorid = $user->id; // User saving action
  1923. $actioncomm->userownerid = $user->id; // Owner of action
  1924. // Fields when action is an email (content should be added into note)
  1925. $actioncomm->email_msgid = $msgid;
  1926. $actioncomm->email_from = $fromstring;
  1927. $actioncomm->email_sender = $sender;
  1928. $actioncomm->email_to = $to;
  1929. $actioncomm->email_tocc = $sendtocc;
  1930. $actioncomm->email_tobcc = $sendtobcc;
  1931. $actioncomm->email_subject = $subject;
  1932. $actioncomm->errors_to = '';
  1933. if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) {
  1934. $actioncomm->fk_element = $fk_element_id;
  1935. $actioncomm->elementid = $fk_element_id;
  1936. $actioncomm->elementtype = $fk_element_type;
  1937. if (is_object($objectemail) && $objectemail->module) {
  1938. $actioncomm->elementtype .= '@'.$objectemail->module;
  1939. }
  1940. }
  1941. //$actioncomm->extraparams = $extraparams;
  1942. // Overwrite values with values extracted from source email
  1943. $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  1944. //var_dump($fk_element_id);
  1945. //var_dump($fk_element_type);
  1946. //var_dump($alreadycreated);
  1947. //var_dump($operation['type']);
  1948. //var_dump($actioncomm);
  1949. //exit;
  1950. if ($errorforthisaction) {
  1951. $errorforactions++;
  1952. } else {
  1953. $result = $actioncomm->create($user);
  1954. if ($result <= 0) {
  1955. $errorforactions++;
  1956. $this->errors = $actioncomm->errors;
  1957. } else {
  1958. $operationslog .= '<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
  1959. }
  1960. }
  1961. }
  1962. } elseif ($operation['type'] == 'recordjoinpiece') {
  1963. $pj = getAttachments($imapemail, $connection);
  1964. foreach ($pj as $key => $val) {
  1965. $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection);
  1966. }
  1967. if (count($pj) > 0) {
  1968. $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."user WHERE email LIKE '%".$this->db->escape($from)."%'";
  1969. $resql = $this->db->query($sql);
  1970. if ($this->db->num_rows($resql) == 0) {
  1971. $this->errors[] = 'User Not allowed to add documents';
  1972. }
  1973. $arrayobject = array(
  1974. 'propale' => array('table' => 'propal',
  1975. 'fields' => array('ref'),
  1976. 'class' => 'comm/propal/class/propal.class.php',
  1977. 'object' => 'Propal'),
  1978. 'holiday' => array('table' => 'holiday',
  1979. 'fields' => array('ref'),
  1980. 'class' => 'holiday/class/holiday.class.php',
  1981. 'object' => 'Holiday'),
  1982. 'expensereport' => array('table' => 'expensereport',
  1983. 'fields' => array('ref'),
  1984. 'class' => 'expensereport/class/expensereport.class.php',
  1985. 'object' => 'ExpenseReport'),
  1986. 'recruitment/recruitmentjobposition' => array('table' => 'recruitment_recruitmentjobposition',
  1987. 'fields' => array('ref'),
  1988. 'class' => 'recruitment/class/recruitmentjobposition.class.php',
  1989. 'object' => 'RecruitmentJobPosition'),
  1990. 'recruitment/recruitmentjobposition' => array('table' => 'recruitment_recruitmentcandidature',
  1991. 'fields' => array('ref'),
  1992. 'class' => 'recruitment/class/recruitmentcandidature.class.php',
  1993. 'object' => ' RecruitmentCandidature'),
  1994. 'societe' => array('table' => 'societe',
  1995. 'fields' => array('code_client', 'code_fournisseur'),
  1996. 'class' => 'societe/class/societe.class.php',
  1997. 'object' => 'Societe'),
  1998. 'commande' => array('table' => 'commande',
  1999. 'fields' => array('ref'),
  2000. 'class' => 'commande/class/commande.class.php',
  2001. 'object' => 'Commande'),
  2002. 'expedition' => array('table' => 'expedition',
  2003. 'fields' => array('ref'),
  2004. 'class' => 'expedition/class/expedition.class.php',
  2005. 'object' => 'Expedition'),
  2006. 'contract' => array('table' => 'contrat',
  2007. 'fields' => array('ref'),
  2008. 'class' => 'contrat/class/contrat.class.php',
  2009. 'object' => 'Contrat'),
  2010. 'fichinter' => array('table' => 'fichinter',
  2011. 'fields' => array('ref'),
  2012. 'class' => 'fichinter/class/fichinter.class.php',
  2013. 'object' => 'Fichinter'),
  2014. 'ticket' => array('table' => 'ticket',
  2015. 'fields' => array('ref'),
  2016. 'class' => 'ticket/class/ticket.class.php',
  2017. 'object' => ' Ticket'),
  2018. 'knowledgemanagement' => array('table' => 'knowledgemanagement_knowledgerecord',
  2019. 'fields' => array('ref'),
  2020. 'class' => 'knowledgemanagement/class/knowledgemanagement.class.php',
  2021. 'object' => 'KnowledgeRecord'),
  2022. 'supplier_proposal' => array('table' => 'supplier_proposal',
  2023. 'fields' => array('ref'),
  2024. 'class' => 'supplier_proposal/class/supplier_proposal.class.php',
  2025. 'object' => 'SupplierProposal'),
  2026. 'fournisseur/commande' => array('table' => 'commande_fournisseur',
  2027. 'fields' => array('ref', 'ref_supplier'),
  2028. 'class' => 'fourn/class/fournisseur.commande.class.php',
  2029. 'object' => 'SupplierProposal'),
  2030. 'facture' => array('table' => 'facture',
  2031. 'fields' => array('ref'),
  2032. 'class' => 'compta/facture/class/facture.class.php',
  2033. 'object' => 'Facture'),
  2034. 'fournisseur/facture' => array('table' => 'facture_fourn',
  2035. 'fields' => array('ref', 'ref_client'),
  2036. 'class' => 'fourn/class/fournisseur.facture.class.php',
  2037. 'object' => 'FactureFournisseur'),
  2038. 'produit' => array('table' => 'product',
  2039. 'fields' => array('ref'),
  2040. 'class' => 'product/class/product.class.php',
  2041. 'object' => 'Product'),
  2042. 'productlot' => array('table' => 'product_lot',
  2043. 'fields' => array('batch'),
  2044. 'class' => 'product/stock/class/productlot.class.php',
  2045. 'object' => 'Productlot'),
  2046. 'projet' => array('table' => 'projet',
  2047. 'fields' => array('ref'),
  2048. 'class' => 'projet/class/projet.class.php',
  2049. 'object' => 'Project'),
  2050. 'projet_task' => array('table' => 'projet_task',
  2051. 'fields' => array('ref'),
  2052. 'class' => 'projet/class/task.class.php',
  2053. 'object' => 'Task'),
  2054. 'ressource' => array('table' => 'resource',
  2055. 'fields' => array('ref'),
  2056. 'class' => 'ressource/class/dolressource.class.php',
  2057. 'object' => 'Dolresource'),
  2058. 'bom' => array('table' => 'bom_bom',
  2059. 'fields' => array('ref'),
  2060. 'class' => 'bom/class/bom.class.php',
  2061. 'object' => 'BOM'),
  2062. 'mrp' => array('table' => 'mrp_mo',
  2063. 'fields' => array('ref'),
  2064. 'class' => 'mrp/class/mo.class.php',
  2065. 'object' => 'Mo'),
  2066. );
  2067. if (!is_object($hookmanager)) {
  2068. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  2069. $hookmanager = new HookManager($this->db);
  2070. }
  2071. $hookmanager->initHooks(array('emailcolector'));
  2072. $parameters = array('arrayobject' => $arrayobject);
  2073. $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks
  2074. if ($reshook > 0) {
  2075. $arrayobject = $hookmanager->resArray;
  2076. }
  2077. $resultobj = array();
  2078. foreach ($arrayobject as $key => $objectdesc) {
  2079. $sql = 'SELECT DISTINCT t.rowid ';
  2080. $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectdesc['table'] . ' AS t';
  2081. $sql .= ' WHERE ';
  2082. foreach ($objectdesc['fields'] as $field) {
  2083. $sql .= "'" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $field . ", '%') OR ";
  2084. }
  2085. $sql = substr($sql, 0, -4);
  2086. $ressqlobj = $this->db->query($sql);
  2087. if ($ressqlobj) {
  2088. while ($obj = $this->db->fetch_object($ressqlobj)) {
  2089. $resultobj[$key][] = $obj->rowid;
  2090. }
  2091. }
  2092. }
  2093. $dirs = array();
  2094. foreach ($resultobj as $mod => $ids) {
  2095. $moddesc = $arrayobject[$mod];
  2096. $elementpath = $mod;
  2097. dol_include_once($moddesc['class']);
  2098. $objectmanaged = new $moddesc['object']($this->db);
  2099. foreach ($ids as $val) {
  2100. $res = $objectmanaged->fetch($val);
  2101. if ($res) {
  2102. $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : '');
  2103. $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/';
  2104. } else {
  2105. $this->errors[] = 'object not found';
  2106. }
  2107. }
  2108. }
  2109. foreach ($dirs as $target) {
  2110. foreach ($data as $filename => $content) {
  2111. $prefix = $this->actions[$this->id]['actionparam'];
  2112. $resr = saveAttachment($target, $prefix . '_' . $filename, $content);
  2113. if ($resr == -1) {
  2114. $this->errors[] = 'Doc not saved';
  2115. }
  2116. }
  2117. }
  2118. $operationslog .= '<br>Save attachment files on disk';
  2119. } else {
  2120. $this->errors[] = 'no joined piece';
  2121. $operationslog .= '<br>No joinded files';
  2122. }
  2123. } elseif ($operation['type'] == 'project') {
  2124. // Create project / lead
  2125. $projecttocreate = new Project($this->db);
  2126. $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid);
  2127. if ($alreadycreated == 0) {
  2128. if ($thirdpartystatic->id > 0) {
  2129. $projecttocreate->socid = $thirdpartystatic->id;
  2130. if ($thirdpartyfoundby) {
  2131. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2132. }
  2133. }
  2134. if ($contactstatic->id > 0) {
  2135. $projecttocreate->contact_id = $contactstatic->id;
  2136. if ($contactfoundby) {
  2137. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2138. }
  2139. }
  2140. $description = $descriptiontitle;
  2141. $description = dol_concatdesc($description, "-----");
  2142. $description = dol_concatdesc($description, $descriptionmeta);
  2143. $description = dol_concatdesc($description, "-----");
  2144. $description = dol_concatdesc($description, $messagetext);
  2145. $descriptionfull = $description;
  2146. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2147. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2148. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2149. }
  2150. $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
  2151. $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
  2152. $projecttocreate->title = $subject;
  2153. $projecttocreate->date_start = $date; // date of email
  2154. $projecttocreate->date_end = '';
  2155. $projecttocreate->opp_status = $id_opp_status;
  2156. $projecttocreate->opp_percent = $percent_opp_status;
  2157. $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...');
  2158. $projecttocreate->note_private = $descriptionfull;
  2159. $projecttocreate->entity = $conf->entity;
  2160. $projecttocreate->email_msgid = $msgid;
  2161. $savesocid = $projecttocreate->socid;
  2162. // Overwrite values with values extracted from source email.
  2163. // This may overwrite any $projecttocreate->xxx properties.
  2164. $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2165. // Set project ref if not yet defined
  2166. if (empty($projecttocreate->ref)) {
  2167. // Get next Ref
  2168. $defaultref = '';
  2169. $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
  2170. // Search template files
  2171. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2172. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2173. foreach ($dirmodels as $reldir) {
  2174. $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0);
  2175. if (file_exists($file)) {
  2176. $filefound = 1;
  2177. $classname = $modele;
  2178. break;
  2179. }
  2180. }
  2181. if ($filefound) {
  2182. if ($savesocid > 0) {
  2183. if ($savesocid != $projecttocreate->socid) {
  2184. $errorforactions++;
  2185. 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');
  2186. }
  2187. } else {
  2188. if ($projecttocreate->socid > 0) {
  2189. $thirdpartystatic->fetch($projecttocreate->socid);
  2190. }
  2191. }
  2192. $result = dol_include_once($reldir."core/modules/project/".$modele.'.php');
  2193. $modModuleToUseForNextValue = new $classname;
  2194. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
  2195. }
  2196. $projecttocreate->ref = $defaultref;
  2197. }
  2198. if ($errorforthisaction) {
  2199. $errorforactions++;
  2200. } else {
  2201. if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
  2202. $errorforactions++;
  2203. $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
  2204. } else {
  2205. // Create project
  2206. $result = $projecttocreate->create($user);
  2207. if ($result <= 0) {
  2208. $errorforactions++;
  2209. $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
  2210. $this->errors = $projecttocreate->errors;
  2211. } else {
  2212. if ($attachments) {
  2213. $destdir = $conf->project->dir_output.'/'.$projecttocreate->ref;
  2214. if (!dol_is_dir($destdir)) {
  2215. dol_mkdir($destdir);
  2216. }
  2217. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2218. foreach ($attachments as $attachment) {
  2219. $attachment->save($destdir.'/');
  2220. }
  2221. } else {
  2222. $this->getmsg($connection, $imapemail, $destdir);
  2223. }
  2224. $operationslog .= '<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
  2225. } else {
  2226. $operationslog .= '<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
  2227. }
  2228. }
  2229. }
  2230. }
  2231. }
  2232. } elseif ($operation['type'] == 'ticket') {
  2233. // Create ticket
  2234. $tickettocreate = new Ticket($this->db);
  2235. $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid);
  2236. if ($alreadycreated == 0) {
  2237. if ($thirdpartystatic->id > 0) {
  2238. $tickettocreate->socid = $thirdpartystatic->id;
  2239. $tickettocreate->fk_soc = $thirdpartystatic->id;
  2240. if ($thirdpartyfoundby) {
  2241. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
  2242. }
  2243. }
  2244. if ($contactstatic->id > 0) {
  2245. $tickettocreate->contact_id = $contactstatic->id;
  2246. if ($contactfoundby) {
  2247. $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
  2248. }
  2249. }
  2250. $description = $descriptiontitle;
  2251. $description = dol_concatdesc($description, "-----");
  2252. $description = dol_concatdesc($description, $descriptionmeta);
  2253. $description = dol_concatdesc($description, "-----");
  2254. $description = dol_concatdesc($description, $messagetext);
  2255. $descriptionfull = $description;
  2256. if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
  2257. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2258. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2259. }
  2260. $tickettocreate->subject = $subject;
  2261. $tickettocreate->message = $description;
  2262. $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));
  2263. $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));
  2264. $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));
  2265. $tickettocreate->origin_email = $from;
  2266. $tickettocreate->fk_user_create = $user->id;
  2267. $tickettocreate->datec = dol_now();
  2268. $tickettocreate->fk_project = $projectstatic->id;
  2269. $tickettocreate->notify_tiers_at_create = 0;
  2270. $tickettocreate->note_private = $descriptionfull;
  2271. $tickettocreate->entity = $conf->entity;
  2272. $tickettocreate->email_msgid = $msgid;
  2273. $tickettocreate->email_date = $date;
  2274. //$tickettocreate->fk_contact = $contactstatic->id;
  2275. $savesocid = $tickettocreate->socid;
  2276. // Overwrite values with values extracted from source email.
  2277. // This may overwrite any $projecttocreate->xxx properties.
  2278. $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2279. // Set ticket ref if not yet defined
  2280. if (empty($tickettocreate->ref)) {
  2281. // Get next Ref
  2282. $defaultref = '';
  2283. $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON;
  2284. // Search template files
  2285. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2286. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2287. foreach ($dirmodels as $reldir) {
  2288. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2289. if (file_exists($file)) {
  2290. $filefound = 1;
  2291. $classname = $modele;
  2292. break;
  2293. }
  2294. }
  2295. if ($filefound) {
  2296. if ($savesocid > 0) {
  2297. if ($savesocid != $tickettocreate->socid) {
  2298. $errorforactions++;
  2299. 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');
  2300. }
  2301. } else {
  2302. if ($tickettocreate->socid > 0) {
  2303. $thirdpartystatic->fetch($tickettocreate->socid);
  2304. }
  2305. }
  2306. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2307. $modModuleToUseForNextValue = new $classname;
  2308. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
  2309. }
  2310. $tickettocreate->ref = $defaultref;
  2311. }
  2312. if ($errorforthisaction) {
  2313. $errorforactions++;
  2314. } else {
  2315. if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
  2316. $errorforactions++;
  2317. $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
  2318. } else {
  2319. // Create project
  2320. $result = $tickettocreate->create($user);
  2321. if ($result <= 0) {
  2322. $errorforactions++;
  2323. $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error);
  2324. $this->errors = $tickettocreate->errors;
  2325. } else {
  2326. if ($attachments) {
  2327. $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref;
  2328. if (!dol_is_dir($destdir)) {
  2329. dol_mkdir($destdir);
  2330. }
  2331. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2332. foreach ($attachments as $attachment) {
  2333. $attachment->save($destdir.'/');
  2334. }
  2335. } else {
  2336. $this->getmsg($connection, $imapemail, $destdir);
  2337. }
  2338. $operationslog .= '<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
  2339. } else {
  2340. $operationslog .= '<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
  2341. }
  2342. }
  2343. }
  2344. }
  2345. }
  2346. } elseif ($operation['type'] == 'candidature') {
  2347. // Create candidature
  2348. $candidaturetocreate = new RecruitmentCandidature($this->db);
  2349. $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid);
  2350. if ($alreadycreated == 0) {
  2351. $description = $descriptiontitle;
  2352. $description = dol_concatdesc($description, "-----");
  2353. $description = dol_concatdesc($description, $descriptionmeta);
  2354. $description = dol_concatdesc($description, "-----");
  2355. $description = dol_concatdesc($description, $messagetext);
  2356. $descriptionfull = $description;
  2357. $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
  2358. $descriptionfull = dol_concatdesc($descriptionfull, $header);
  2359. $candidaturetocreate->subject = $subject;
  2360. $candidaturetocreate->message = $description;
  2361. $candidaturetocreate->type_code = 0;
  2362. $candidaturetocreate->category_code = null;
  2363. $candidaturetocreate->severity_code = null;
  2364. $candidaturetocreate->email = $from;
  2365. //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$from;
  2366. $candidaturetocreate->fk_user_creat = $user->id;
  2367. $candidaturetocreate->date_creation = dol_now();
  2368. $candidaturetocreate->fk_project = $projectstatic->id;
  2369. $candidaturetocreate->description = $description;
  2370. $candidaturetocreate->note_private = $descriptionfull;
  2371. $candidaturetocreate->entity = $conf->entity;
  2372. $candidaturetocreate->email_msgid = $msgid;
  2373. $candidaturetocreate->email_date = $date; // date of email
  2374. $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
  2375. //$candidaturetocreate->fk_contact = $contactstatic->id;
  2376. // Overwrite values with values extracted from source email.
  2377. // This may overwrite any $projecttocreate->xxx properties.
  2378. $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
  2379. // Set candidature ref if not yet defined
  2380. /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status
  2381. {
  2382. // Get next Ref
  2383. $defaultref = '';
  2384. $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON;
  2385. // Search template files
  2386. $file = ''; $classname = ''; $filefound = 0; $reldir = '';
  2387. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  2388. foreach ($dirmodels as $reldir)
  2389. {
  2390. $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
  2391. if (file_exists($file)) {
  2392. $filefound = 1;
  2393. $classname = $modele;
  2394. break;
  2395. }
  2396. }
  2397. if ($filefound) {
  2398. if ($savesocid > 0) {
  2399. if ($savesocid != $candidaturetocreate->socid) {
  2400. $errorforactions++;
  2401. 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');
  2402. }
  2403. } else {
  2404. if ($candidaturetocreate->socid > 0)
  2405. {
  2406. $thirdpartystatic->fetch($candidaturetocreate->socid);
  2407. }
  2408. }
  2409. $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
  2410. $modModuleToUseForNextValue = new $classname;
  2411. $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
  2412. }
  2413. $candidaturetocreate->ref = $defaultref;
  2414. }*/
  2415. if ($errorforthisaction) {
  2416. $errorforactions++;
  2417. } else {
  2418. // Create project
  2419. $result = $candidaturetocreate->create($user);
  2420. if ($result <= 0) {
  2421. $errorforactions++;
  2422. $this->error = 'Failed to create ticket: '.join(', ', $candidaturetocreate->errors);
  2423. $this->errors = $candidaturetocreate->errors;
  2424. }
  2425. $operationslog .= '<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
  2426. }
  2427. }
  2428. } elseif (substr($operation['type'], 0, 4) == 'hook') {
  2429. // Create event specific on hook
  2430. // this code action is hook..... for support this call
  2431. if (!is_object($hookmanager)) {
  2432. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  2433. $hookmanager = new HookManager($this->db);
  2434. }
  2435. $parameters = array(
  2436. 'connection'=> $connection,
  2437. 'imapemail'=>$imapemail,
  2438. 'overview'=>$overview,
  2439. 'from' => $from,
  2440. 'fromtext' => $fromtext,
  2441. 'actionparam'=> $operation['actionparam'],
  2442. 'thirdpartyid' => $thirdpartyid,
  2443. 'objectid'=> $objectid,
  2444. 'objectemail'=> $objectemail,
  2445. 'messagetext'=>$messagetext,
  2446. 'subject'=>$subject,
  2447. 'header'=>$header,
  2448. 'attachments'=>$attachments,
  2449. );
  2450. $reshook = $hookmanager->executeHooks('doCollectImapOneCollector', $parameters, $this, $operation['type']);
  2451. if ($reshook < 0) {
  2452. $errorforthisaction++;
  2453. $this->error = $hookmanager->resPrint;
  2454. }
  2455. if ($errorforthisaction) {
  2456. $errorforactions++;
  2457. $operationslog .= '<br>Hook doCollectImapOneCollector executed with error';
  2458. } else {
  2459. $operationslog .= '<br>Hook doCollectImapOneCollector executed without error';
  2460. }
  2461. }
  2462. if (!$errorforactions) {
  2463. $nbactiondoneforemail++;
  2464. }
  2465. }
  2466. }
  2467. // Error for email or not ?
  2468. if (!$errorforactions) {
  2469. if ($targetdir && empty($mode)) {
  2470. if (empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2471. dol_syslog("EmailCollector::doCollectOneCollector move message ".$imapemail." to ".$connectstringtarget, LOG_DEBUG);
  2472. $res = imap_mail_move($connection, $imapemail, $targetdir, 0);
  2473. if ($res == false) {
  2474. $errorforemail++;
  2475. $this->error = imap_last_error();
  2476. $this->errors[] = $this->error;
  2477. dol_syslog(imap_last_error());
  2478. }
  2479. } else {
  2480. // TODO Move mail using PHP-IMAP
  2481. }
  2482. } else {
  2483. dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG);
  2484. }
  2485. } else {
  2486. $errorforemail++;
  2487. }
  2488. unset($objectemail);
  2489. unset($projectstatic);
  2490. unset($thirdpartystatic);
  2491. unset($contactstatic);
  2492. $nbemailprocessed++;
  2493. if (!$errorforemail) {
  2494. $nbactiondone += $nbactiondoneforemail;
  2495. $nbemailok++;
  2496. if (empty($mode)) {
  2497. $this->db->commit();
  2498. } else {
  2499. $this->db->rollback();
  2500. }
  2501. // Stop the loop to process email if we reach maximum collected per collect
  2502. if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
  2503. dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok." collected with success, so we stop this collector now.");
  2504. break;
  2505. }
  2506. } else {
  2507. $error++;
  2508. $this->db->rollback();
  2509. }
  2510. }
  2511. $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
  2512. dol_syslog("End of loop on emails", LOG_INFO, -1);
  2513. } else {
  2514. $output = $langs->trans('NoNewEmailToProcess');
  2515. }
  2516. if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
  2517. $client->disconnect();
  2518. } else {
  2519. if (empty($mode)) {
  2520. imap_expunge($connection); // To validate any move
  2521. }
  2522. imap_close($connection);
  2523. }
  2524. $this->datelastresult = $now;
  2525. $this->lastresult = $output;
  2526. $this->debuginfo .= 'IMAP search string used : '.$search;
  2527. if ($searchhead) {
  2528. $this->debuginfo .= '<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
  2529. }
  2530. if ($operationslog) {
  2531. $this->debuginfo .= $operationslog;
  2532. }
  2533. if (empty($error) && empty($mode)) {
  2534. $this->datelastok = $now;
  2535. }
  2536. if (!empty($this->errors)) {
  2537. $this->lastresult .= "<br>".join("<br>", $this->errors);
  2538. }
  2539. $this->codelastresult = ($error ? 'KO' : 'OK');
  2540. if (empty($mode)) {
  2541. $this->update($user);
  2542. }
  2543. dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG);
  2544. return $error ? -1 : 1;
  2545. }
  2546. // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation
  2547. /**
  2548. * getmsg
  2549. *
  2550. * @param Object $mbox Structure
  2551. * @param string $mid prefix
  2552. * @param string $destdir Target dir for attachments
  2553. * @return array Array with number and object
  2554. */
  2555. private function getmsg($mbox, $mid, $destdir = '')
  2556. {
  2557. // input $mbox = IMAP stream, $mid = message id
  2558. // output all the following:
  2559. global $charset, $htmlmsg, $plainmsg, $attachments;
  2560. $htmlmsg = $plainmsg = $charset = '';
  2561. $attachments = array();
  2562. // HEADER
  2563. //$h = imap_header($mbox,$mid);
  2564. // add code here to get date, from, to, cc, subject...
  2565. // BODY
  2566. $s = imap_fetchstructure($mbox, $mid);
  2567. if (!$s->parts) {
  2568. // simple
  2569. $this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number
  2570. } else {
  2571. // multipart: cycle through each part
  2572. foreach ($s->parts as $partno0 => $p) {
  2573. $this->getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
  2574. }
  2575. }
  2576. }
  2577. /* partno string
  2578. 0 multipart/mixed
  2579. 1 multipart/alternative
  2580. 1.1 text/plain
  2581. 1.2 text/html
  2582. 2 message/rfc822
  2583. 2 multipart/mixed
  2584. 2.1 multipart/alternative
  2585. 2.1.1 text/plain
  2586. 2.1.2 text/html
  2587. 2.2 message/rfc822
  2588. 2.2 multipart/alternative
  2589. 2.2.1 text/plain
  2590. 2.2.2 text/html
  2591. */
  2592. /**
  2593. * Sub function for getpart(). Only called by createPartArray() and itself.
  2594. *
  2595. * @param Object $mbox Structure
  2596. * @param string $mid Part no
  2597. * @param Object $p Object p
  2598. * @param string $partno Partno
  2599. * @param string $destdir Target dir for attachments
  2600. * @return void
  2601. */
  2602. private function getpart($mbox, $mid, $p, $partno, $destdir = '')
  2603. {
  2604. // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
  2605. global $htmlmsg, $plainmsg, $charset, $attachments;
  2606. // DECODE DATA
  2607. $data = ($partno) ?
  2608. imap_fetchbody($mbox, $mid, $partno) : // multipart
  2609. imap_body($mbox, $mid); // simple
  2610. // Any part may be encoded, even plain text messages, so check everything.
  2611. if ($p->encoding == 4) {
  2612. $data = quoted_printable_decode($data);
  2613. } elseif ($p->encoding == 3) {
  2614. $data = base64_decode($data);
  2615. }
  2616. // PARAMETERS
  2617. // get all parameters, like charset, filenames of attachments, etc.
  2618. $params = array();
  2619. if ($p->parameters) {
  2620. foreach ($p->parameters as $x) {
  2621. $params[strtolower($x->attribute)] = $x->value;
  2622. }
  2623. }
  2624. if ($p->dparameters) {
  2625. foreach ($p->dparameters as $x) {
  2626. $params[strtolower($x->attribute)] = $x->value;
  2627. }
  2628. }
  2629. // ATTACHMENT
  2630. // Any part with a filename is an attachment,
  2631. // so an attached text file (type 0) is not mistaken as the message.
  2632. if ($params['filename'] || $params['name']) {
  2633. // filename may be given as 'Filename' or 'Name' or both
  2634. $filename = ($params['filename']) ? $params['filename'] : $params['name'];
  2635. // filename may be encoded, so see imap_mime_header_decode()
  2636. $attachments[$filename] = $data; // this is a problem if two files have same name
  2637. // Get file name (with extension)
  2638. $file_name_complete = $params['filename'];
  2639. $destination = $destdir.'/'.$file_name_complete;
  2640. // Extract file extension
  2641. $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
  2642. // Extract file name without extension
  2643. $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
  2644. // Save an original file name variable to track while renaming if file already exists
  2645. $file_name_original = $file_name;
  2646. // Increment file name by 1
  2647. $num = 1;
  2648. /**
  2649. * Check if the same file name already exists in the upload folder,
  2650. * append increment number to the original filename
  2651. */
  2652. while (file_exists($destdir."/" . $file_name . "." . $extension)) {
  2653. $file_name = (string) $file_name_original . ' (' . $num . ')';
  2654. $file_name_complete = $file_name . "." . $extension;
  2655. $destination = $destdir.'/'.$file_name_complete;
  2656. $num++;
  2657. }
  2658. file_put_contents($destination, $data);
  2659. }
  2660. // TEXT
  2661. if ($p->type == 0 && $data) {
  2662. if (!empty($params['charset'])) {
  2663. $data = $this->convertStringEncoding($data, $params['charset']);
  2664. }
  2665. // Messages may be split in different parts because of inline attachments,
  2666. // so append parts together with blank row.
  2667. if (strtolower($p->subtype) == 'plain') {
  2668. $plainmsg .= trim($data)."\n\n";
  2669. } else {
  2670. $htmlmsg .= $data."<br><br>";
  2671. }
  2672. $charset = $params['charset']; // assume all parts are same charset
  2673. } elseif ($p->type == 2 && $data) {
  2674. // EMBEDDED MESSAGE
  2675. // Many bounce notifications embed the original message as type 2,
  2676. // but AOL uses type 1 (multipart), which is not handled here.
  2677. // There are no PHP functions to parse embedded messages,
  2678. // so this just appends the raw source to the main message.
  2679. if (!empty($params['charset'])) {
  2680. $data = $this->convertStringEncoding($data, $params['charset']);
  2681. }
  2682. $plainmsg .= $data."\n\n";
  2683. }
  2684. // SUBPART RECURSION
  2685. if ($p->parts) {
  2686. foreach ($p->parts as $partno0 => $p2) {
  2687. $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1)); // 1.2, 1.2.1, etc.
  2688. }
  2689. }
  2690. }
  2691. /**
  2692. * Converts a string from one encoding to another.
  2693. *
  2694. * @param string $string String to convert
  2695. * @param string $fromEncoding String encoding
  2696. * @param string $toEncoding String return encoding
  2697. * @return string Converted string if conversion was successful, or the original string if not
  2698. * @throws Exception
  2699. */
  2700. protected function convertStringEncoding($string, $fromEncoding, $toEncoding = 'UTF-8')
  2701. {
  2702. if (!$string || $fromEncoding == $toEncoding) {
  2703. return $string;
  2704. }
  2705. $convertedString = function_exists('iconv') ? @iconv($fromEncoding, $toEncoding.'//IGNORE', $string) : null;
  2706. if (!$convertedString && extension_loaded('mbstring')) {
  2707. $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
  2708. }
  2709. if (!$convertedString) {
  2710. throw new Exception('Mime string encoding conversion failed');
  2711. }
  2712. return $convertedString;
  2713. }
  2714. /**
  2715. * Decode a subject string according to RFC2047
  2716. * Example: '=?Windows-1252?Q?RE=A0:_ABC?=' => 'RE : ABC...'
  2717. * Example: '=?UTF-8?Q?A=C3=A9B?=' => 'AéB'
  2718. * Example: '=?UTF-8?B?2KLYstmF2KfbjNi0?=' =>
  2719. * Example: '=?utf-8?B?UkU6IG1vZHVsZSBkb2xpYmFyciBnZXN0aW9ubmFpcmUgZGUgZmljaGllcnMg?= =?utf-8?B?UsOpZsOpcmVuY2UgZGUgbGEgY29tbWFuZGUgVFVHRURJSklSIOKAkyBwYXNz?= =?utf-8?B?w6llIGxlIDIyLzA0LzIwMjA=?='
  2720. *
  2721. * @param string $subject Subject
  2722. * @return string Decoded subject (in UTF-8)
  2723. */
  2724. protected function decodeSMTPSubject($subject)
  2725. {
  2726. // Decode $overview[0]->subject according to RFC2047
  2727. // Can use also imap_mime_header_decode($str)
  2728. // Can use also mb_decode_mimeheader($str)
  2729. // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8')
  2730. if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) {
  2731. $elements = imap_mime_header_decode($subject);
  2732. $newstring = '';
  2733. if (!empty($elements)) {
  2734. $num = count($elements);
  2735. for ($i = 0; $i < $num; $i++) {
  2736. $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));
  2737. $newstring .= $stringinutf8;
  2738. }
  2739. $subject = $newstring;
  2740. }
  2741. } elseif (!function_exists('mb_decode_mimeheader')) {
  2742. $subject = mb_decode_mimeheader($subject);
  2743. } elseif (function_exists('iconv_mime_decode')) {
  2744. $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
  2745. }
  2746. return $subject;
  2747. }
  2748. }