emailcollector.class.php 100 KB

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