emailcollector.class.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  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 <http://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 . '/contact/class/contact.class.php';
  25. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  26. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  27. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  28. /**
  29. * Class for EmailCollector
  30. */
  31. class EmailCollector extends CommonObject
  32. {
  33. /**
  34. * @var string ID to identify managed object
  35. */
  36. public $element = 'emailcollector';
  37. /**
  38. * @var string Name of table without prefix where object is stored
  39. */
  40. public $table_element = 'emailcollector_emailcollector';
  41. /**
  42. * @var int Does emailcollector support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  43. */
  44. public $ismultientitymanaged = 1;
  45. /**
  46. * @var int Does emailcollector support extrafields ? 0=No, 1=Yes
  47. */
  48. public $isextrafieldmanaged = 0;
  49. /**
  50. * @var string String with name of icon for emailcollector. Must be the part after the 'object_' into object_emailcollector.png
  51. */
  52. public $picto = 'generic';
  53. /**
  54. * @var int Field with ID of parent key if this field has a parent
  55. */
  56. public $fk_element = 'fk_emailcollector';
  57. /**
  58. * @var array Array of child tables (child tables to delete before deleting a record)
  59. */
  60. protected $childtables=array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction');
  61. /**
  62. * 'type' if the field format.
  63. * 'label' the translation key.
  64. * 'enabled' is a condition when the field must be managed.
  65. * '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)
  66. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  67. * 'default' is a default value for creation (can still be replaced by the global setup of default values)
  68. * 'index' if we want an index in database.
  69. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  70. * 'position' is the sort order of field.
  71. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  72. * '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).
  73. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  74. * 'help' is a string visible as a tooltip on field
  75. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  76. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  77. * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  78. */
  79. // BEGIN MODULEBUILDER PROPERTIES
  80. /**
  81. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  82. */
  83. public $fields=array(
  84. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID','visible'=>2, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1),
  85. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
  86. 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'help'=>'Example: MyCollector1'),
  87. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>'Example: My Email collector'),
  88. 'description' => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>60, 'notnull'=>-1),
  89. 'host' => array('type'=>'varchar(255)', 'label'=>'EMailHost', 'visible'=>1, 'enabled'=>1, 'position'=>100, 'notnull'=>1, 'searchall'=>1, 'comment'=>"IMAP server", 'help'=>'Example: imap.gmail.com'),
  90. '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'),
  91. 'password' => array('type'=>'password', 'label'=>'Password', 'visible'=>-1, 'enabled'=>1, 'position'=>102, 'notnull'=>-1, 'comment'=>"IMAP password"),
  92. 'source_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxSourceDirectory', 'visible'=>-1, 'enabled'=>1, 'position'=>103, 'notnull'=>1, 'default' => 'Inbox', 'help'=>'Example: INBOX'),
  93. //'filter' => array('type'=>'text', 'label'=>'Filter', 'visible'=>1, 'enabled'=>1, 'position'=>105),
  94. //'actiontodo' => array('type'=>'varchar(255)', 'label'=>'ActionToDo', 'visible'=>1, 'enabled'=>1, 'position'=>106),
  95. 'target_directory' => array('type'=>'varchar(255)', 'label'=>'MailboxTargetDirectory', 'visible'=>1, 'enabled'=>1, 'position'=>110, 'notnull'=>0, 'comment'=>"Where to store messages once processed"),
  96. 'datelastresult' => array('type'=>'datetime', 'label'=>'DateLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>121, 'notnull'=>-1,),
  97. 'codelastresult' => array('type'=>'varchar(16)', 'label'=>'CodeLastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>122, 'notnull'=>-1,),
  98. 'lastresult' => array('type'=>'varchar(255)', 'label'=>'LastResult', 'visible'=>1, 'enabled'=>'$action != "create" && $action != "edit"', 'position'=>123, 'notnull'=>-1,),
  99. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'visible'=>0, 'enabled'=>1, 'position'=>61, 'notnull'=>-1,),
  100. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'visible'=>0, 'enabled'=>1, 'position'=>62, 'notnull'=>-1,),
  101. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,),
  102. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1,),
  103. //'date_validation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
  104. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>510, 'notnull'=>1,),
  105. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>511, 'notnull'=>-1,),
  106. //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
  107. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1,),
  108. 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Inactive', '1'=>'Active'))
  109. );
  110. /**
  111. * @var int ID
  112. */
  113. public $rowid;
  114. /**
  115. * @var string Ref
  116. */
  117. public $ref;
  118. /**
  119. * @var int Entity
  120. */
  121. public $entity;
  122. /**
  123. * @var string label
  124. */
  125. public $label;
  126. /**
  127. * @var int Status
  128. */
  129. public $status;
  130. public $date_creation;
  131. public $tms;
  132. /**
  133. * @var int ID
  134. */
  135. public $fk_user_creat;
  136. /**
  137. * @var int ID
  138. */
  139. public $fk_user_modif;
  140. public $import_key;
  141. public $host;
  142. public $login;
  143. public $password;
  144. public $source_directory;
  145. public $target_directory;
  146. public $datelastresult;
  147. public $lastresult;
  148. // END MODULEBUILDER PROPERTIES
  149. public $filters;
  150. public $actions;
  151. /**
  152. * Constructor
  153. *
  154. * @param DoliDb $db Database handler
  155. */
  156. public function __construct(DoliDB $db)
  157. {
  158. global $conf, $langs, $user;
  159. $this->db = $db;
  160. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible']=0;
  161. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled']=0;
  162. // Unset fields that are disabled
  163. foreach($this->fields as $key => $val)
  164. {
  165. if (isset($val['enabled']) && empty($val['enabled']))
  166. {
  167. unset($this->fields[$key]);
  168. }
  169. }
  170. // Translate some data of arrayofkeyval
  171. foreach($this->fields as $key => $val)
  172. {
  173. if (is_array($this->fields['status']['arrayofkeyval']))
  174. {
  175. foreach($this->fields['status']['arrayofkeyval'] as $key2 => $val2)
  176. {
  177. $this->fields['status']['arrayofkeyval'][$key2]=$langs->trans($val2);
  178. }
  179. }
  180. }
  181. }
  182. /**
  183. * Create object into database
  184. *
  185. * @param User $user User that creates
  186. * @param bool $notrigger false=launch triggers after, true=disable triggers
  187. * @return int <0 if KO, Id of created object if OK
  188. */
  189. public function create(User $user, $notrigger = false)
  190. {
  191. return $this->createCommon($user, $notrigger);
  192. }
  193. /**
  194. * Clone and object into another one
  195. *
  196. * @param User $user User that creates
  197. * @param int $fromid Id of object to clone
  198. * @return mixed New object created, <0 if KO
  199. */
  200. public function createFromClone(User $user, $fromid)
  201. {
  202. global $langs, $hookmanager, $extrafields;
  203. $error = 0;
  204. dol_syslog(__METHOD__, LOG_DEBUG);
  205. $object = new self($this->db);
  206. $this->db->begin();
  207. // Load source object
  208. $object->fetchCommon($fromid);
  209. // Reset some properties
  210. unset($object->id);
  211. unset($object->fk_user_creat);
  212. unset($object->import_key);
  213. // Clear fields
  214. $object->ref = "copy_of_".$object->ref;
  215. $object->title = $langs->trans("CopyOf")." ".$object->title;
  216. // ...
  217. // Clear extrafields that are unique
  218. if (is_array($object->array_options) && count($object->array_options) > 0)
  219. {
  220. $extrafields->fetch_name_optionals_label($this->element);
  221. foreach($object->array_options as $key => $option)
  222. {
  223. $shortkey = preg_replace('/options_/', '', $key);
  224. if (! empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
  225. {
  226. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  227. unset($object->array_options[$key]);
  228. }
  229. }
  230. }
  231. // Create clone
  232. $object->context['createfromclone'] = 'createfromclone';
  233. $result = $object->createCommon($user);
  234. if ($result < 0) {
  235. $error++;
  236. $this->error = $object->error;
  237. $this->errors = $object->errors;
  238. }
  239. unset($object->context['createfromclone']);
  240. // End
  241. if (!$error) {
  242. $this->db->commit();
  243. return $object;
  244. } else {
  245. $this->db->rollback();
  246. return -1;
  247. }
  248. }
  249. /**
  250. * Load object in memory from the database
  251. *
  252. * @param int $id Id object
  253. * @param string $ref Ref
  254. * @return int <0 if KO, 0 if not found, >0 if OK
  255. */
  256. public function fetch($id, $ref = null)
  257. {
  258. $result = $this->fetchCommon($id, $ref);
  259. //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
  260. return $result;
  261. }
  262. /**
  263. * Load object lines in memory from the database
  264. *
  265. * @return int <0 if KO, 0 if not found, >0 if OK
  266. */
  267. /*public function fetchLines()
  268. {
  269. $this->lines=array();
  270. // Load lines with object EmailCollectorLine
  271. return count($this->lines)?1:0;
  272. }*/
  273. /**
  274. * Fetch all account and load objects into an array
  275. *
  276. * @param User $user User
  277. * @param int $activeOnly filter if active
  278. * @param string $sortfield field for sorting
  279. * @param string $sortorder sorting order
  280. * @param int $limit sort limit
  281. * @param int $page page to start on
  282. * @return array Array with key => EmailCollector object
  283. */
  284. public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0)
  285. {
  286. global $langs;
  287. $obj_ret = array();
  288. $socid = $user->societe_id ? $user->societe_id : '';
  289. $sql = "SELECT s.rowid";
  290. $sql.= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s";
  291. $sql.= ' WHERE s.entity IN ('.getEntity('emailcollector').')';
  292. if ($activeOnly) {
  293. $sql.= " AND s.status = 1";
  294. }
  295. $sql.= $this->db->order($sortfield, $sortorder);
  296. if ($limit) {
  297. if ($page < 0) {
  298. $page = 0;
  299. }
  300. $offset = $limit * $page;
  301. $sql.= $this->db->plimit($limit + 1, $offset);
  302. }
  303. $result = $this->db->query($sql);
  304. if ($result) {
  305. $num = $this->db->num_rows($result);
  306. while ($i < $num)
  307. {
  308. $obj = $this->db->fetch_object($result);
  309. $emailcollector_static = new EmailCollector($this->db);
  310. if ($emailcollector_static->fetch($obj->rowid)) {
  311. $obj_ret[] = $emailcollector_static;
  312. }
  313. $i++;
  314. }
  315. } else {
  316. $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list';
  317. dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
  318. $ret = -1;
  319. }
  320. if (! count($obj_ret)) {
  321. dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
  322. }
  323. return $obj_ret;
  324. }
  325. /**
  326. * Update object into database
  327. *
  328. * @param User $user User that modifies
  329. * @param bool $notrigger false=launch triggers after, true=disable triggers
  330. * @return int <0 if KO, >0 if OK
  331. */
  332. public function update(User $user, $notrigger = false)
  333. {
  334. return $this->updateCommon($user, $notrigger);
  335. }
  336. /**
  337. * Delete object in database
  338. *
  339. * @param User $user User that deletes
  340. * @param bool $notrigger false=launch triggers after, true=disable triggers
  341. * @return int <0 if KO, >0 if OK
  342. */
  343. public function delete(User $user, $notrigger = false)
  344. {
  345. return $this->deleteCommon($user, $notrigger, 1);
  346. }
  347. /**
  348. * Return a link to the object card (with optionaly the picto)
  349. *
  350. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  351. * @param string $option On what the link point to ('nolink', ...)
  352. * @param int $notooltip 1=Disable tooltip
  353. * @param string $morecss Add more css on link
  354. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  355. * @return string String with URL
  356. */
  357. function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
  358. {
  359. global $db, $conf, $langs, $hookmanager;
  360. global $dolibarr_main_authentication, $dolibarr_main_demo;
  361. global $menumanager;
  362. if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
  363. $result = '';
  364. $companylink = '';
  365. $label = '<u>' . $langs->trans("EmailCollector") . '</u>';
  366. $label.= '<br>';
  367. $label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
  368. $url = dol_buildpath('/admin/emailcollector_card.php', 1).'?id='.$this->id;
  369. if ($option != 'nolink')
  370. {
  371. // Add param to save lastsearch_values or not
  372. $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
  373. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  374. $add_save_lastsearch_values=1;
  375. }
  376. if ($add_save_lastsearch_values) {
  377. $url.='&save_lastsearch_values=1';
  378. }
  379. }
  380. $linkclose='';
  381. if (empty($notooltip))
  382. {
  383. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  384. {
  385. $label=$langs->trans("ShowEmailCollector");
  386. $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
  387. }
  388. $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
  389. $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
  390. /*
  391. $hookmanager->initHooks(array('myobjectdao'));
  392. $parameters=array('id'=>$this->id);
  393. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  394. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  395. */
  396. }
  397. else $linkclose = ($morecss?' class="'.$morecss.'"':'');
  398. $linkstart = '<a href="'.$url.'"';
  399. $linkstart.=$linkclose.'>';
  400. $linkend='</a>';
  401. $result .= $linkstart;
  402. if ($withpicto) $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);
  403. if ($withpicto != 2) $result.= $this->ref;
  404. $result .= $linkend;
  405. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  406. global $action,$hookmanager;
  407. $hookmanager->initHooks(array('emailcollectordao'));
  408. $parameters=array('id'=>$this->id, 'getnomurl'=>$result);
  409. $reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  410. if ($reshook > 0) $result = $hookmanager->resPrint;
  411. else $result .= $hookmanager->resPrint;
  412. return $result;
  413. }
  414. /**
  415. * Return label of the status
  416. *
  417. * @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
  418. * @return string Label of status
  419. */
  420. public function getLibStatut($mode=0)
  421. {
  422. return $this->LibStatut($this->status, $mode);
  423. }
  424. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  425. /**
  426. * Return the status
  427. *
  428. * @param int $status Id status
  429. * @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
  430. * @return string Label of status
  431. */
  432. public function LibStatut($status, $mode=0)
  433. {
  434. // phpcs:enable
  435. if (empty($this->labelstatus))
  436. {
  437. global $langs;
  438. //$langs->load("mymodule");
  439. $this->labelstatus[1] = $langs->trans('Enabled');
  440. $this->labelstatus[0] = $langs->trans('Disabled');
  441. }
  442. if ($mode == 0)
  443. {
  444. return $this->labelstatus[$status];
  445. }
  446. elseif ($mode == 1)
  447. {
  448. return $this->labelstatus[$status];
  449. }
  450. elseif ($mode == 2)
  451. {
  452. if ($status == 1) return img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
  453. elseif ($status == 0) return img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
  454. }
  455. elseif ($mode == 3)
  456. {
  457. if ($status == 1) return img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle');
  458. elseif ($status == 0) return img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle');
  459. }
  460. elseif ($mode == 4)
  461. {
  462. if ($status == 1) return img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
  463. elseif ($status == 0) return img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
  464. }
  465. elseif ($mode == 5)
  466. {
  467. if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle');
  468. elseif ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle');
  469. }
  470. elseif ($mode == 6)
  471. {
  472. if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut4', '', false, 0, 0, '', 'valignmiddle');
  473. elseif ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut5', '', false, 0, 0, '', 'valignmiddle');
  474. }
  475. }
  476. /**
  477. * Charge les informations d'ordre info dans l'objet commande
  478. *
  479. * @param int $id Id of order
  480. * @return void
  481. */
  482. public function info($id)
  483. {
  484. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  485. $sql.= ' fk_user_creat, fk_user_modif';
  486. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  487. $sql.= ' WHERE t.rowid = '.$id;
  488. $result=$this->db->query($sql);
  489. if ($result)
  490. {
  491. if ($this->db->num_rows($result))
  492. {
  493. $obj = $this->db->fetch_object($result);
  494. $this->id = $obj->rowid;
  495. if ($obj->fk_user_author)
  496. {
  497. $cuser = new User($this->db);
  498. $cuser->fetch($obj->fk_user_author);
  499. $this->user_creation = $cuser;
  500. }
  501. if ($obj->fk_user_valid)
  502. {
  503. $vuser = new User($this->db);
  504. $vuser->fetch($obj->fk_user_valid);
  505. $this->user_validation = $vuser;
  506. }
  507. if ($obj->fk_user_cloture)
  508. {
  509. $cluser = new User($this->db);
  510. $cluser->fetch($obj->fk_user_cloture);
  511. $this->user_cloture = $cluser;
  512. }
  513. $this->date_creation = $this->db->jdate($obj->datec);
  514. $this->date_modification = $this->db->jdate($obj->datem);
  515. $this->date_validation = $this->db->jdate($obj->datev);
  516. }
  517. $this->db->free($result);
  518. }
  519. else
  520. {
  521. dol_print_error($this->db);
  522. }
  523. }
  524. /**
  525. * Initialise object with example values
  526. * Id must be 0 if object instance is a specimen
  527. *
  528. * @return void
  529. */
  530. public function initAsSpecimen()
  531. {
  532. $this->initAsSpecimenCommon();
  533. }
  534. /**
  535. * Fetch filters
  536. *
  537. * @return int <0 if KO, >0 if OK
  538. */
  539. public function fetchFilters()
  540. {
  541. $this->filters = array();
  542. $sql = 'SELECT rowid, type, rulevalue, status';
  543. $sql.= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter';
  544. $sql.= ' WHERE fk_emailcollector = '.$this->id;
  545. //$sql.= ' ORDER BY position';
  546. $resql = $this->db->query($sql);
  547. if ($resql)
  548. {
  549. $num=$this->db->num_rows($resql);
  550. $i = 0;
  551. while($i < $num)
  552. {
  553. $obj=$this->db->fetch_object($resql);
  554. $this->filters[$obj->rowid]=array('id'=>$obj->rowid, 'type'=>$obj->type, 'rulevalue'=>$obj->rulevalue, 'status'=>$obj->status);
  555. $i++;
  556. }
  557. $this->db->free($resql);
  558. }
  559. else dol_print_error($this->db);
  560. return 1;
  561. }
  562. /**
  563. * Fetch actions
  564. *
  565. * @return int <0 if KO, >0 if OK
  566. */
  567. public function fetchActions()
  568. {
  569. $this->actions = array();
  570. $sql = 'SELECT rowid, type, actionparam, status';
  571. $sql.= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectoraction';
  572. $sql.= ' WHERE fk_emailcollector = '.$this->id;
  573. $sql.= ' ORDER BY position';
  574. $resql = $this->db->query($sql);
  575. if ($resql)
  576. {
  577. $num=$this->db->num_rows($resql);
  578. $i = 0;
  579. while($i < $num)
  580. {
  581. $obj=$this->db->fetch_object($resql);
  582. $this->actions[$obj->rowid]=array('id'=>$obj->rowid, 'type'=>$obj->type, 'actionparam'=>$obj->actionparam, 'status'=>$obj->status);
  583. $i++;
  584. }
  585. $this->db->free($resql);
  586. }
  587. else dol_print_error($this->db);
  588. }
  589. /**
  590. * Return the connectstring to use with IMAP connection function
  591. *
  592. * @return string
  593. */
  594. function getConnectStringIMAP()
  595. {
  596. // Connect to IMAP
  597. $flags ='/service=imap'; // IMAP
  598. $flags.='/ssl'; // '/tls'
  599. $flags.='/novalidate-cert';
  600. //$flags.='/readonly';
  601. //$flags.='/debug';
  602. $connectstringserver = '{'.$this->host.':993'.$flags.'}';
  603. return $connectstringserver;
  604. }
  605. /**
  606. * Action executed by scheduler
  607. * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters'
  608. *
  609. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  610. */
  611. public function doCollect()
  612. {
  613. global $user;
  614. $nberror = 0;
  615. $arrayofcollectors = $this->fetchAll($user, 1);
  616. // Loop on each collector
  617. foreach($arrayofcollectors as $emailcollector)
  618. {
  619. $result = $emailcollector->doCollectOneCollector();
  620. dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id);
  621. $this->error.='EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'<br>';
  622. if (! empty($emailcollector->errors)) $this->error.=join('<br>', $emailcollector->errors);
  623. $this->output.='EmailCollector ID '.$emailcollector->id.': '.$emailcollector->lastresult.'<br>';
  624. }
  625. return $nberror;
  626. }
  627. /**
  628. * overwitePropertiesOfObject
  629. *
  630. * @return int 0=OK, Nb of error if error
  631. */
  632. /**
  633. * overwitePropertiesOfObject
  634. *
  635. * @param object $object Current object
  636. * @param string $actionparam Action parameters
  637. * @param string $messagetext Body
  638. * @param string $subject Subject
  639. * @return int 0=OK, Nb of error if error
  640. */
  641. private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject)
  642. {
  643. $errorforthisaction = 0;
  644. // Overwrite values with values extracted from source email
  645. // $this->actionparam = 'opportunity_status=123;abc=REGEX:BODY:....'
  646. $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
  647. foreach($arrayvaluetouse as $propertytooverwrite => $valueforproperty)
  648. {
  649. $tmpclass=''; $tmpproperty='';
  650. $tmparray=explode('.', $propertytooverwrite);
  651. if (count($tmparray) == 2)
  652. {
  653. $tmpclass=$tmparray[0];
  654. $tmpproperty=$tmparray[1];
  655. }
  656. else
  657. {
  658. $tmpproperty=$tmparray[0];
  659. }
  660. if ($tmpclass && ($tmpclass != $object->element)) continue; // Property is for another type of object
  661. if (property_exists($object, $tmpproperty))
  662. {
  663. $sourcestring='';
  664. $sourcefield='';
  665. $regexstring='';
  666. //$transformationstring='';
  667. $regforregex=array();
  668. if (preg_match('/^REGEX:([a-zA-Z0-9]+):(.*):([^:])$/', $valueforproperty, $regforregex))
  669. {
  670. $sourcefield=$regforregex[1];
  671. $regexstring=$regforregex[2];
  672. //$transofrmationstring=$regforregex[3];
  673. }
  674. elseif (preg_match('/^REGEX:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex))
  675. {
  676. $sourcefield=$regforregex[1];
  677. $regexstring=$regforregex[2];
  678. }
  679. if (! empty($sourcefield) && ! empty($regexstring))
  680. {
  681. if (strtolower($sourcefield) == 'body') $sourcestring=$messagetext;
  682. elseif (strtolower($sourcefield) == 'subject') $sourcestring=$subject;
  683. $regforval=array();
  684. if (preg_match('/'.preg_quote($regexstring, '/').'/', $sourcestring, $regforval))
  685. {
  686. // Overwrite param $tmpproperty
  687. $object->$tmpproperty = $regforval[1];
  688. }
  689. else
  690. {
  691. // Nothing can be done for this param
  692. }
  693. }
  694. elseif (preg_match('/^VALUE:(.*)$/', $valueforproperty, $reg))
  695. {
  696. $object->$tmpproperty = $reg[1];
  697. }
  698. else
  699. {
  700. $errorforthisaction++;
  701. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  702. $this->errors[] = $this->error;
  703. }
  704. }
  705. }
  706. return $errorforthisaction;
  707. }
  708. /**
  709. * Execute collect for current collector loaded previously with fetch.
  710. *
  711. * @return int <0 if KO, >0 if OK
  712. */
  713. public function doCollectOneCollector()
  714. {
  715. global $conf, $langs, $user;
  716. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  717. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  718. dol_syslog("EmailCollector::doCollectOneCollector start", LOG_DEBUG);
  719. $langs->loadLangs(array("project", "companies", "mails", "errors"));
  720. $error = 0;
  721. $this->output = '';
  722. $this->error='';
  723. $now = dol_now();
  724. if (empty($this->host))
  725. {
  726. $this->error=$langs->trans('ErrorFieldRequired', 'EMailHost');
  727. return -1;
  728. }
  729. if (empty($this->login))
  730. {
  731. $this->error=$langs->trans('ErrorFieldRequired', 'Login');
  732. return -1;
  733. }
  734. if (empty($this->source_directory))
  735. {
  736. $this->error=$langs->trans('ErrorFieldRequired', 'MailboxSourceDirectory');
  737. return -1;
  738. }
  739. if (! function_exists('imap_open'))
  740. {
  741. $this->error='IMAP function not enabled on your PHP';
  742. return -2;
  743. }
  744. $this->fetchFilters();
  745. $this->fetchActions();
  746. $sourcedir = $this->source_directory;
  747. $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
  748. $connectstringserver = $this->getConnectStringIMAP();
  749. $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
  750. $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
  751. $connection = imap_open($connectstringsource, $this->login, $this->password);
  752. if (! $connection)
  753. {
  754. $this->error = 'Failed to open IMAP connection '.$connectstringsource;
  755. return -3;
  756. }
  757. //$search='ALL';
  758. $search='UNDELETED';
  759. $searchfilterdoltrackid=0;
  760. $searchfilternodoltrackid=0;
  761. foreach($this->filters as $rule)
  762. {
  763. if (empty($rule['status'])) continue;
  764. if ($rule['type'] == 'to') $search.=($search?' ':'').'TO "'.str_replace('"', '', $rule['rulevalue']).'"';
  765. if ($rule['type'] == 'bcc') $search.=($search?' ':'').'BCC';
  766. if ($rule['type'] == 'cc') $search.=($search?' ':'').'CC';
  767. if ($rule['type'] == 'from') $search.=($search?' ':'').'FROM "'.str_replace('"', '', $rule['rulevalue']).'"';
  768. if ($rule['type'] == 'subject') $search.=($search?' ':'').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
  769. if ($rule['type'] == 'body') $search.=($search?' ':'').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
  770. if ($rule['type'] == 'seen') $search.=($search?' ':'').'SEEN';
  771. if ($rule['type'] == 'unseen') $search.=($search?' ':'').'UNSEEN';
  772. if ($rule['type'] == 'withtrackingid') $searchfilterdoltrackid++;
  773. if ($rule['type'] == 'withouttrackingid') $searchfilternodoltrackid++;
  774. }
  775. if (empty($targetdir)) // Use last date as filter if there is no targetdir defined.
  776. {
  777. $fromdate=0;
  778. if ($this->datelastresult && $this->codelastresult == 'OK') $fromdate = $this->datelastresult;
  779. if ($fromdate > 0) $search.=($search?' ':'').'SINCE '.dol_print_date($fromdate - 1,'dayhourrfc');
  780. }
  781. dol_syslog("IMAP search string = ".$search);
  782. //var_dump($search);
  783. $nbemailprocessed=0;
  784. $nbemailok=0;
  785. $nbactiondone=0;
  786. // Scan IMAP inbox
  787. $arrayofemail= imap_search($connection, $search);
  788. //var_dump($arrayofemail);exit;
  789. // Loop on each email found
  790. if (! empty($arrayofemail) && count($arrayofemail) > 0)
  791. {
  792. foreach($arrayofemail as $imapemail)
  793. {
  794. if ($nbemailprocessed > 100) break; // Do not process more than 100 email per launch
  795. $header = imap_fetchheader($connection, $imapemail, 0);
  796. $matches=array();
  797. preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
  798. $headers = array_combine($matches[1], $matches[2]);
  799. //var_dump($headers);
  800. // $conf->global->MAIL_PREFIX_FOR_EMAIL_ID must be defined
  801. $host=dol_getprefix('email');
  802. // If there is a filter on trackid
  803. //var_dump($host);exit;
  804. if ($searchfilterdoltrackid > 0)
  805. {
  806. //if (empty($headers['X-Dolibarr-TRACKID'])) continue;
  807. if (empty($headers['References']) || ! preg_match('/@'.preg_quote($host,'/').'/', $headers['References']))
  808. {
  809. $nbemailprocessed++;
  810. continue;
  811. }
  812. }
  813. if ($searchfilternodoltrackid > 0)
  814. {
  815. if (! empty($headers['References']) && preg_match('/@'.preg_quote($host,'/').'/', $headers['References']))
  816. {
  817. $nbemailprocessed++;
  818. continue;
  819. }
  820. //if (! empty($headers['X-Dolibarr-TRACKID']) continue;
  821. }
  822. $thirdpartystatic=new Societe($this->db);
  823. $contactstatic=new Contact($this->db);
  824. $projectstatic=new Project($this->db);
  825. $nbactiondoneforemail = 0;
  826. $errorforemail = 0;
  827. $errorforactions = 0;
  828. $thirdpartyfoundby = '';
  829. $contactfoundby = '';
  830. $projectfoundby = '';
  831. $this->db->begin();
  832. //$message = imap_body($connection, $imapemail, 0);
  833. $overview = imap_fetch_overview($connection, $imapemail, 0);
  834. $structure = imap_fetchstructure($connection, $imapemail, 0);
  835. $partplain = $parthtml = -1;
  836. // Loop to get part html and plain
  837. /*
  838. 0 multipart/mixed
  839. 1 multipart/alternative
  840. 1.1 text/plain
  841. 1.2 text/html
  842. 2 message/rfc822
  843. 2 multipart/mixed
  844. 2.1 multipart/alternative
  845. 2.1.1 text/plain
  846. 2.1.2 text/html
  847. 2.2 message/rfc822
  848. 2.2 multipart/alternative
  849. 2.2.1 text/plain
  850. 2.2.2 text/html
  851. */
  852. /**
  853. * create_part_array
  854. *
  855. * @param Object $structure Structure
  856. * @param string $prefix prefix
  857. * @return array Array with number and object
  858. */
  859. function createPartArray($structure, $prefix="")
  860. {
  861. //print_r($structure);
  862. if (count($structure->parts) > 0) { // There some sub parts
  863. foreach ($structure->parts as $count => $part) {
  864. add_part_to_array($part, $prefix.($count+1), $part_array);
  865. }
  866. }else{ // Email does not have a seperate mime attachment for text
  867. $part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
  868. }
  869. return $part_array;
  870. }
  871. /**
  872. * Sub function for createPartArray(). Only called by createPartArray() and itself.
  873. *
  874. * @param Object $obj Structure
  875. * @param string $partno Part no
  876. * @param array $part_array array
  877. * @return void
  878. */
  879. function addPartToArray($obj, $partno, &$part_array)
  880. {
  881. $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
  882. if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
  883. //print_r($obj);
  884. if (array_key_exists('parts',$obj)) { // Check to see if the email has parts
  885. foreach ($obj->parts as $count => $part) {
  886. // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
  887. if (count($part->parts) > 0) {
  888. foreach ($part->parts as $count2 => $part2) {
  889. addPartToArray($part2, $partno.".".($count2+1), $part_array);
  890. }
  891. }else{ // Attached email does not have a seperate mime attachment for text
  892. $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
  893. }
  894. }
  895. }else{ // Not sure if this is possible
  896. $part_array[] = array('part_number' => $partno.'.1', 'part_object' => $obj);
  897. }
  898. }else{ // If there are more sub-parts, expand them out.
  899. if (array_key_exists('parts',$obj)) {
  900. foreach ($obj->parts as $count => $p) {
  901. addPartToArray($p, $partno.".".($count+1), $part_array);
  902. }
  903. }
  904. }
  905. }
  906. $result = createPartArray($structure, '');
  907. //var_dump($result);exit;
  908. foreach($result as $part)
  909. {
  910. if ($part['part_object']->subtype == 'HTML') $parthtml=$part['part_number'];
  911. if ($part['part_object']->subtype == 'PLAIN') $partplain=$part['part_number'];
  912. }
  913. /* OLD CODE to get parthtml and partplain
  914. if (count($structure->parts) > 0) { // There some sub parts
  915. foreach($structure->parts as $key => $part)
  916. {
  917. if ($part->subtype == 'HTML') $parthtml=($key+1); // For example: $parthtml = 1 or 2
  918. if ($part->subtype == 'PLAIN') $partplain=($key+1);
  919. if ($part->subtype == 'ALTERNATIVE')
  920. {
  921. if (count($part->parts) > 0)
  922. {
  923. foreach($part->parts as $key2 => $part2)
  924. {
  925. if ($part2->subtype == 'HTML') $parthtml=($key+1).'.'.($key2+1); // For example: $parthtml = 1.1 or 1.2
  926. if ($part2->subtype == 'PLAIN') $partplain=($key+1).'.'.($key2+1);
  927. }
  928. }
  929. else
  930. {
  931. $partplain=($key+1).'.1';
  932. }
  933. }
  934. }
  935. }
  936. else
  937. {
  938. $partplain=1;
  939. }*/
  940. //var_dump($structure);
  941. //var_dump($parthtml);var_dump($partplain);
  942. $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 0)), FT_PEEK);
  943. //var_dump($overview);
  944. //var_dump($header);
  945. //var_dump($message);
  946. //var_dump($structure->parts[0]->parts);
  947. //var_dump($messagetext);exit;
  948. $fromstring=$overview[0]->from;
  949. $sender=$overview[0]->sender;
  950. $to=$overview[0]->to;
  951. $sendtocc=$overview[0]->cc;
  952. $sendtobcc=$overview[0]->bcc;
  953. $date=$overview[0]->udate;
  954. $msgid=str_replace(array('<','>'), '', $overview[0]->message_id);
  955. $subject=$overview[0]->subject;
  956. //var_dump($msgid);exit;
  957. $reg=array();
  958. if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg))
  959. {
  960. $from=$reg[2];
  961. $fromtext=$reg[1];
  962. }
  963. else
  964. {
  965. $from = $fromstring;
  966. $fromtext='';
  967. }
  968. $fk_element_id = 0; $fk_element_type = '';
  969. $contactid = 0; $thirdpartyid = 0; $projectid = 0;
  970. // Analyze TrackId in field References
  971. // For example: References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e>
  972. $trackid = '';
  973. $reg=array();
  974. if (! empty($headers['References']) && preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,'/').'/', $headers['References'], $reg))
  975. {
  976. $trackid = $reg[1].$reg[2];
  977. $objectid = 0;
  978. $objectemail = null;
  979. if ($reg[0] == 'inv')
  980. {
  981. $objectid = $reg[1];
  982. $objectemail = new Facture($this->db);
  983. }
  984. if ($reg[0] == 'proj')
  985. {
  986. $objectid = $reg[1];
  987. $objectemail = new Project($this->db);
  988. }
  989. if ($reg[0] == 'con')
  990. {
  991. $objectid = $reg[1];
  992. $objectemail = new Contact($this->db);
  993. }
  994. if ($reg[0] == 'thi')
  995. {
  996. $objectid = $reg[1];
  997. $objectemail = new Societe($this->db);
  998. }
  999. if ($reg[0] == 'use')
  1000. {
  1001. $objectid = $reg[1];
  1002. $objectemail = new User($this->db);
  1003. }
  1004. if (is_object($objectemail))
  1005. {
  1006. $result = $objectemail->fetch($objectid);
  1007. if ($result > 0)
  1008. {
  1009. $fk_element_id = $objectemail->id;
  1010. $fk_element_type = $objectemail->element;
  1011. // Fix fk_element_type
  1012. if ($fk_element_type == 'facture') $fk_element_type = 'invoice';
  1013. $thirdpartyid = $objectemail->fk_soc;
  1014. $contactid = $objectemail->fk_socpeople;
  1015. $projectid = isset($objectemail->fk_project)?$objectemail->fk_project:$objectemail->fk_projet;
  1016. }
  1017. }
  1018. // Project
  1019. if ($projectid > 0)
  1020. {
  1021. $result = $projectstatic->fetch($projectid);
  1022. if ($result <= 0) $projectstatic->id = 0;
  1023. else
  1024. {
  1025. $projectid = $projectstatic->id;
  1026. $projectfoundby = 'trackid ('.$trackid.')';
  1027. if (empty($contactid)) $contactid = $projectstatic->fk_contact;
  1028. if (empty($thirdpartyid)) $thirdpartyid = $projectstatic->fk_soc;
  1029. }
  1030. }
  1031. // Contact
  1032. if ($contactid > 0)
  1033. {
  1034. $result = $contactstatic->fetch($contactid);
  1035. if ($result <= 0) $contactstatic->id = 0;
  1036. else
  1037. {
  1038. $contactid = $contactstatic->id;
  1039. $contactfoundby = 'trackid ('.$trackid.')';
  1040. if (empty($thirdpartyid)) $thirdpartyid = $contactstatic->fk_soc;
  1041. }
  1042. }
  1043. // Thirdparty
  1044. if ($thirdpartyid > 0)
  1045. {
  1046. $result = $thirdpartystatic->fetch($thirdpartyid);
  1047. if ($result <= 0) $thirdpartystatic->id = 0;
  1048. else
  1049. {
  1050. $thirdpartyid = $thirdpartystatic->id;
  1051. $thirdpartyfoundby = 'trackid ('.$trackid.')';
  1052. }
  1053. }
  1054. }
  1055. if (empty($contactid)) // Try to find contact using email
  1056. {
  1057. $result = $contactstatic->fetch(0, null, '', $from);
  1058. if ($result > 0)
  1059. {
  1060. $contactid = $contactstatic->id;
  1061. $contactfoundby = 'email of contact ('.$from.')';
  1062. if ($contactstatic->fk_soc > 0)
  1063. {
  1064. $result = $thirdpartystatic->fetch($contactstatic->fk_soc);
  1065. if ($result > 0)
  1066. {
  1067. $thirdpartyid = $thirdpartystatic->id;
  1068. $thirdpartyfoundby = 'email of contact ('.$from.')';
  1069. }
  1070. }
  1071. }
  1072. }
  1073. if (empty($thirdpartyid)) // Try to find thirdparty using email
  1074. {
  1075. $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from);
  1076. if ($result > 0) $thirdpartyfoundby = 'email ('.$from.')';
  1077. }
  1078. // Do operations
  1079. foreach($this->actions as $operation)
  1080. {
  1081. if ($errorforactions) break;
  1082. if (empty($operation['status'])) continue;
  1083. // Make Operation
  1084. dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id);
  1085. // Search and create thirdparty
  1086. if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty')
  1087. {
  1088. if (empty($operation['actionparam']))
  1089. {
  1090. $errorforactions++;
  1091. $this->error = "Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be 'VALUE:xxx' or 'REGEX:(body|subject):regex' to define how to extract data";
  1092. $this->errors[] = $this->error;
  1093. }
  1094. else
  1095. {
  1096. $actionparam = $operation['actionparam'];
  1097. $nametouseforthirdparty='';
  1098. // $this->actionparam = 'VALUE:aaa' or 'REGEX:BODY:....'
  1099. $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
  1100. foreach($arrayvaluetouse as $propertytooverwrite => $valueforproperty)
  1101. {
  1102. $sourcestring='';
  1103. $sourcefield='';
  1104. $regexstring='';
  1105. $regforregex=array();
  1106. if (preg_match('/^REGEX:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex))
  1107. {
  1108. $sourcefield=$regforregex[1];
  1109. $regexstring=$regforregex[2];
  1110. }
  1111. if (! empty($sourcefield) && ! empty($regexstring))
  1112. {
  1113. if (strtolower($sourcefield) == 'body') $sourcestring=$messagetext;
  1114. elseif (strtolower($sourcefield) == 'subject') $sourcestring=$subject;
  1115. $regforval=array();
  1116. if (preg_match('/'.$regexstring.'/', $sourcestring, $regforval)) // Do not use preg_quote here, string is already a regex syntax, for example string is 'Name:\s([^\s]*)'
  1117. {
  1118. // Overwrite param $tmpproperty
  1119. $nametouseforthirdparty = $regforval[1];
  1120. }
  1121. else
  1122. {
  1123. // Nothing can be done for this param
  1124. }
  1125. //var_dump($sourcestring); var_dump($regexstring);var_dump($nametouseforthirdparty);exit;
  1126. }
  1127. elseif (preg_match('/^VALUE:(.*)$/', $valueforproperty, $reg))
  1128. {
  1129. $nametouseforthirdparty = $reg[1];
  1130. }
  1131. else
  1132. {
  1133. $errorforactions++;
  1134. $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
  1135. $this->errors[] = $this->error;
  1136. break;
  1137. }
  1138. }
  1139. if (! $errorforactions && $nametouseforthirdparty)
  1140. {
  1141. $result = $thirdpartystatic->fetch(0, $nametouseforthirdparty);
  1142. if ($result < 0)
  1143. {
  1144. $errorforactions++;
  1145. $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)';
  1146. $this->errors[] = $this->error;
  1147. break;
  1148. }
  1149. elseif ($result == 0)
  1150. {
  1151. if ($operation['type'] == 'loadandcreatethirdparty')
  1152. {
  1153. dol_syslog("Third party with name ".$nametouseforthirdparty." was not found. We try to create it.");
  1154. // Create thirdparty
  1155. $thirdpartystatic->name = $nametouseforthirdparty;
  1156. if ($fromtext != $nametouseforthirdparty) $thirdpartystatic->name_alias = $fromtext;
  1157. $thirdpartystatic->email = $from;
  1158. // Overwrite values with values extracted from source email
  1159. $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject);
  1160. if ($errorforthisaction)
  1161. {
  1162. $errorforactions++;
  1163. }
  1164. else
  1165. {
  1166. $result = $thirdpartystatic->create($user);
  1167. if ($result <= 0)
  1168. {
  1169. $errorforactions++;
  1170. $this->error = $thirdpartystatic->error;
  1171. $this->errors = $thirdpartystatic->errors;
  1172. }
  1173. }
  1174. }
  1175. else
  1176. {
  1177. dol_syslog("Third party with name ".$nametouseforthirdparty." was not found");
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. // Create event
  1184. elseif ($operation['type'] == 'recordevent')
  1185. {
  1186. $actioncode = 'EMAIL_IN';
  1187. // Insert record of emails sent
  1188. $actioncomm = new ActionComm($this->db);
  1189. $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
  1190. $actioncomm->code = 'AC_'.$actioncode;
  1191. $actioncomm->label = $langs->trans("ActionAC_EMAIL_IN").' - '.$langs->trans("MailFrom").' '.$from;
  1192. $actioncomm->note = $messagetext;
  1193. $actioncomm->fk_project = $projectstatic->id;
  1194. $actioncomm->datep = $date;
  1195. $actioncomm->datef = $date;
  1196. $actioncomm->percentage = -1; // Not applicable
  1197. $actioncomm->socid = $thirdpartystatic->id;
  1198. $actioncomm->contactid = $contactstatic->id;
  1199. $actioncomm->authorid = $user->id; // User saving action
  1200. $actioncomm->userownerid = $user->id; // Owner of action
  1201. // Fields when action is an email (content should be added into note)
  1202. $actioncomm->email_msgid = $msgid;
  1203. $actioncomm->email_from = $fromstring;
  1204. $actioncomm->email_sender= $sender;
  1205. $actioncomm->email_to = $to;
  1206. $actioncomm->email_tocc = $sendtocc;
  1207. $actioncomm->email_tobcc = $sendtobcc;
  1208. $actioncomm->email_subject = $subject;
  1209. $actioncomm->errors_to = '';
  1210. if (! in_array($fk_element_type, array('societe','contact','project','user')))
  1211. {
  1212. $actioncomm->fk_element = $fk_element_id;
  1213. $actioncomm->elementtype = $fk_element_type;
  1214. }
  1215. //$actioncomm->extraparams = $extraparams;
  1216. // Overwrite values with values extracted from source email
  1217. $errorforthisaction = $this->overwritePropertiesOfObject($actioncommn, $operation['actionparam'], $messagetext, $subject);
  1218. if ($errorforthisaction)
  1219. {
  1220. $errorforactions++;
  1221. }
  1222. else
  1223. {
  1224. $result = $actioncomm->create($user);
  1225. if ($result <= 0)
  1226. {
  1227. $errorforactions++;
  1228. $this->errors = $actioncomm->errors;
  1229. }
  1230. }
  1231. }
  1232. // Create event
  1233. elseif ($operation['type'] == 'project')
  1234. {
  1235. $note_private = $langs->trans("ProjectCreatedByEmailCollector", $msgid);
  1236. $projecttocreate = new Project($this->db);
  1237. if ($thirdpartystatic->id > 0)
  1238. {
  1239. $projecttocreate->socid = $thirdpartystatic->id;
  1240. if ($thirdpartyfoundby) $note_private .= ' - Third party found from '.$thirdpartyfoundby;
  1241. }
  1242. if ($contactstatic->id > 0)
  1243. {
  1244. $projecttocreate->contact_id = $contactstatic->id;
  1245. if ($contactfoundby) $note_private .= ' - Contact/address found from '.$contactfoundby;
  1246. }
  1247. $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
  1248. $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
  1249. $projecttocreate->title = $subject;
  1250. $projecttocreate->date_start = $now;
  1251. $projecttocreate->date_end = '';
  1252. $projecttocreate->opp_status = $id_opp_status;
  1253. $projecttocreate->opp_percent = $percent_opp_status;
  1254. $projecttocreate->description = dol_concatdesc(dol_concatdesc($note_private, dolGetFirstLineOfText(dol_string_nohtmltag($messagetext, 2), 3)), '...'.$langs->transnoentities("SeePrivateNote").'...');
  1255. $projecttocreate->note_private = dol_concatdesc($note_private, dol_string_nohtmltag($messagetext, 2));
  1256. $projecttocreate->entity = $conf->entity;
  1257. // Get next project Ref
  1258. $defaultref='';
  1259. $modele = empty($conf->global->PROJECT_ADDON)?'mod_project_simple':$conf->global->PROJECT_ADDON;
  1260. // Search template files
  1261. $file=''; $classname=''; $filefound=0; $reldir='';
  1262. $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']);
  1263. foreach($dirmodels as $reldir)
  1264. {
  1265. $file=dol_buildpath($reldir."core/modules/project/".$modele.'.php',0);
  1266. if (file_exists($file))
  1267. {
  1268. $filefound=1;
  1269. $classname = $modele;
  1270. break;
  1271. }
  1272. }
  1273. if ($filefound)
  1274. {
  1275. $result=dol_include_once($reldir."core/modules/project/".$modele.'.php');
  1276. $modProject = new $classname;
  1277. $defaultref = $modProject->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
  1278. }
  1279. $projecttocreate->ref = $defaultref;
  1280. // Overwrite values with values extracted from source email
  1281. $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject);
  1282. if ($errorforthisaction)
  1283. {
  1284. $errorforactions++;
  1285. }
  1286. else
  1287. {
  1288. if (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)
  1289. {
  1290. $errorforactions++;
  1291. $this->error = 'Failed to create project: Can\'t get a valid value for project Ref';
  1292. }
  1293. else
  1294. {
  1295. // Create project
  1296. $result = $projecttocreate->create($user);
  1297. if ($result <= 0)
  1298. {
  1299. $errorforactions++;
  1300. $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
  1301. $this->errors = $projecttocreate->errors;
  1302. }
  1303. }
  1304. }
  1305. }
  1306. if (! $errorforactions)
  1307. {
  1308. $nbactiondoneforemail++;
  1309. }
  1310. }
  1311. // Error for email or not ?
  1312. if (! $errorforactions)
  1313. {
  1314. if ($targetdir)
  1315. {
  1316. dol_syslog("EmailCollector::doCollectOneCollector move message ".$imapemail." to ".$connectstringtarget, LOG_DEBUG);
  1317. $res = imap_mail_move($connection, $imapemail, $targetdir, 0);
  1318. if ($res == false) {
  1319. $errorforemail++;
  1320. $this->error = imap_last_error();
  1321. $this->errors[] = $this->error;
  1322. dol_syslog(imap_last_error());
  1323. }
  1324. }
  1325. else
  1326. {
  1327. dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG);
  1328. }
  1329. }
  1330. else
  1331. {
  1332. $errorforemail++;
  1333. }
  1334. if (! $errorforemail)
  1335. {
  1336. $nbactiondone += $nbactiondoneforemail;
  1337. $nbemailok++;
  1338. $this->db->commit();
  1339. }
  1340. else
  1341. {
  1342. $error++;
  1343. $this->db->rollback();
  1344. }
  1345. $nbemailprocessed++;
  1346. unset($objectemail);
  1347. unset($projectstatic);
  1348. unset($thirdpartystatic);
  1349. unset($contactstatic);
  1350. }
  1351. $output=$langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
  1352. }
  1353. else
  1354. {
  1355. $output=$langs->trans('NoNewEmailToProcess');
  1356. }
  1357. imap_expunge($connection); // To validate any move
  1358. imap_close($connection);
  1359. $this->datelastresult = $now;
  1360. $this->lastresult = $output;
  1361. if (! empty($this->errors)) $this->lastresult.= " - ".join(" - ", $this->errors);
  1362. $this->codelastresult = ($error ? 'KO' : 'OK');
  1363. $this->update($user);
  1364. dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG);
  1365. return $error?-1:1;
  1366. }
  1367. }