emailcollector.class.php 118 KB

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