advtargetemailing.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. <?php
  2. /* Advance Targeting Emailling for mass emailing module
  3. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file comm/mailing/class/advtargetemailing.class.php
  20. * \ingroup mailing
  21. * \brief This file is an example CRUD class file (Create/Read/Update/Delete)
  22. */
  23. /**
  24. * Class to manage advanced emailing target selector
  25. */
  26. class AdvanceTargetingMailing extends CommonObject
  27. {
  28. /**
  29. * @var DoliDB Database handler.
  30. */
  31. public $db;
  32. /**
  33. * @var string ID to identify managed object
  34. */
  35. public $element = 'advtargetemailing';
  36. /**
  37. * @var string Name of table without prefix where object is stored
  38. */
  39. public $table_element = 'mailing_advtarget';
  40. /**
  41. * @var int ID
  42. */
  43. public $id;
  44. /**
  45. * @var string name
  46. */
  47. public $name;
  48. /**
  49. * @var int element id (it's not the name of a field)
  50. */
  51. public $fk_element;
  52. /**
  53. * @var string type element
  54. */
  55. public $type_element;
  56. /**
  57. * @var string filter value
  58. */
  59. public $filtervalue;
  60. /**
  61. * @var int user author id
  62. */
  63. public $fk_user_author;
  64. /**
  65. * @var int|string datec
  66. */
  67. public $datec = '';
  68. /**
  69. * @var int user mod id
  70. */
  71. public $fk_user_mod;
  72. /**
  73. * @var int|string tms
  74. */
  75. public $tms = '';
  76. /**
  77. * @var array select target type
  78. */
  79. public $select_target_type = array();
  80. /**
  81. * @var array type status comm prospect
  82. */
  83. public $type_statuscommprospect = array();
  84. public $thirdparty_lines;
  85. public $contact_lines;
  86. /**
  87. * Constructor
  88. *
  89. * @param DoliDb $db Database handler
  90. */
  91. public function __construct($db)
  92. {
  93. global $langs;
  94. $langs->load('customers');
  95. $this->db = $db;
  96. $this->select_target_type = array(
  97. '2' => $langs->trans('Contacts'),
  98. '1' => $langs->trans('Contacts').'+'.$langs->trans('ThirdParty'),
  99. '3' => $langs->trans('ThirdParty'),
  100. '4' => $langs->trans('ContactsWithThirdpartyFilter')
  101. );
  102. require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
  103. $customerStatic = new Client($this->db);
  104. $customerStatic->loadCacheOfProspStatus();
  105. if (!empty($customerStatic->cacheprospectstatus)) {
  106. foreach ($customerStatic->cacheprospectstatus as $dataProspectSt) {
  107. $this->type_statuscommprospect[$dataProspectSt['id']]=$dataProspectSt['label'];
  108. }
  109. } else {
  110. $this->type_statuscommprospect = array(
  111. -1 => $langs->trans("StatusProspect-1"),
  112. 0 => $langs->trans("StatusProspect0"),
  113. 1 => $langs->trans("StatusProspect1"),
  114. 2 => $langs->trans("StatusProspect2"),
  115. 3 => $langs->trans("StatusProspect3")
  116. );
  117. }
  118. }
  119. /**
  120. * Create object into database
  121. *
  122. * @param User $user User that creates
  123. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  124. * @return int Return integer <0 if KO, Id of created object if OK
  125. */
  126. public function create($user, $notrigger = 0)
  127. {
  128. global $conf, $langs;
  129. $error = 0;
  130. // Clean parameters
  131. if (isset($this->fk_element)) {
  132. $this->fk_element = (int) $this->fk_element;
  133. }
  134. if (isset($this->type_element)) {
  135. $this->type_element = trim($this->type_element);
  136. }
  137. if (isset($this->name)) {
  138. $this->name = trim($this->name);
  139. }
  140. if (isset($this->filtervalue)) {
  141. $this->filtervalue = trim($this->filtervalue);
  142. }
  143. // Check parameters
  144. // Put here code to add control on parameters values
  145. // Insert request
  146. $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_advtarget(";
  147. $sql .= "name,";
  148. $sql .= "entity,";
  149. $sql .= "fk_element,";
  150. $sql .= "type_element,";
  151. $sql .= "filtervalue,";
  152. $sql .= "fk_user_author,";
  153. $sql .= "datec,";
  154. $sql .= "fk_user_mod";
  155. $sql .= ") VALUES (";
  156. $sql .= " ".(!isset($this->name) ? 'NULL' : "'".$this->db->escape($this->name)."'").",";
  157. $sql .= " ".$conf->entity.",";
  158. $sql .= " ".(!isset($this->fk_element) ? 'NULL' : "'".$this->db->escape($this->fk_element)."'").",";
  159. $sql .= " ".(!isset($this->type_element) ? 'NULL' : "'".$this->db->escape($this->type_element)."'").",";
  160. $sql .= " ".(!isset($this->filtervalue) ? 'NULL' : "'".$this->db->escape($this->filtervalue)."'").",";
  161. $sql .= " ".$user->id.",";
  162. $sql .= " '".$this->db->idate(dol_now())."',";
  163. $sql .= " ".$user->id;
  164. $sql .= ")";
  165. $this->db->begin();
  166. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  167. $resql = $this->db->query($sql);
  168. if (!$resql) {
  169. $error++;
  170. $this->errors[] = "Error ".$this->db->lasterror();
  171. }
  172. if (!$error) {
  173. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."mailing_advtarget");
  174. }
  175. // Commit or rollback
  176. if ($error) {
  177. foreach ($this->errors as $errmsg) {
  178. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  179. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  180. }
  181. $this->db->rollback();
  182. return -1 * $error;
  183. } else {
  184. $this->db->commit();
  185. return $this->id;
  186. }
  187. }
  188. /**
  189. * Load object in memory from the database
  190. *
  191. * @param int $id Id object
  192. * @return int Return integer <0 if KO, >0 if OK
  193. */
  194. public function fetch($id)
  195. {
  196. global $langs;
  197. $sql = "SELECT";
  198. $sql .= " t.rowid,";
  199. $sql .= " t.name,";
  200. $sql .= " t.entity,";
  201. $sql .= " t.fk_element,";
  202. $sql .= " t.type_element,";
  203. $sql .= " t.filtervalue,";
  204. $sql .= " t.fk_user_author,";
  205. $sql .= " t.datec,";
  206. $sql .= " t.fk_user_mod,";
  207. $sql .= " t.tms";
  208. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_advtarget as t";
  209. $sql .= " WHERE t.rowid = ".((int) $id);
  210. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  211. $resql = $this->db->query($sql);
  212. if ($resql) {
  213. if ($this->db->num_rows($resql)) {
  214. $obj = $this->db->fetch_object($resql);
  215. $this->id = $obj->rowid;
  216. $this->name = $obj->name;
  217. $this->entity = $obj->entity;
  218. $this->fk_element = $obj->fk_element;
  219. $this->type_element = $obj->type_element;
  220. $this->filtervalue = $obj->filtervalue;
  221. $this->fk_user_author = $obj->fk_user_author;
  222. $this->datec = $this->db->jdate($obj->datec);
  223. $this->fk_user_mod = $obj->fk_user_mod;
  224. $this->tms = $this->db->jdate($obj->tms);
  225. }
  226. $this->db->free($resql);
  227. return 1;
  228. } else {
  229. $this->error = "Error ".$this->db->lasterror();
  230. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  231. return -1;
  232. }
  233. }
  234. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  235. /**
  236. * Load object in memory from the database
  237. *
  238. * @param int $id Id object
  239. * @return int Return integer <0 if KO, >0 if OK
  240. */
  241. public function fetch_by_mailing($id = 0)
  242. {
  243. // phpcs:enable
  244. global $langs;
  245. $sql = "SELECT";
  246. $sql .= " t.rowid,";
  247. $sql .= " t.name,";
  248. $sql .= " t.entity,";
  249. $sql .= " t.fk_element,";
  250. $sql .= " t.type_element,";
  251. $sql .= " t.filtervalue,";
  252. $sql .= " t.fk_user_author,";
  253. $sql .= " t.datec,";
  254. $sql .= " t.fk_user_mod,";
  255. $sql .= " t.tms";
  256. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_advtarget as t";
  257. if (!empty($id)) {
  258. $sql .= " WHERE t.fk_element = ".((int) $id)." AND type_element = 'mailing'";
  259. } else {
  260. $sql .= " WHERE t.fk_element = ".((int) $this->fk_element)." AND type_element = 'mailing'";
  261. }
  262. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  263. $resql = $this->db->query($sql);
  264. if ($resql) {
  265. if ($this->db->num_rows($resql)) {
  266. $obj = $this->db->fetch_object($resql);
  267. $this->id = $obj->rowid;
  268. $this->name = $obj->name;
  269. $this->entity = $obj->entity;
  270. $this->fk_element = $obj->fk_element;
  271. $this->type_element = $obj->type_element;
  272. $this->filtervalue = $obj->filtervalue;
  273. $this->fk_user_author = $obj->fk_user_author;
  274. $this->datec = $this->db->jdate($obj->datec);
  275. $this->fk_user_mod = $obj->fk_user_mod;
  276. $this->tms = $this->db->jdate($obj->tms);
  277. }
  278. $this->db->free($resql);
  279. return 1;
  280. } else {
  281. $this->error = "Error ".$this->db->lasterror();
  282. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  283. return -1;
  284. }
  285. }
  286. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  287. /**
  288. * Load object in memory from the database
  289. *
  290. * @param int $id Id object
  291. * @param string $type_element Type target
  292. * @return int Return integer <0 if KO, >0 if OK
  293. */
  294. public function fetch_by_element($id = 0, $type_element = 'mailing')
  295. {
  296. // phpcs:enable
  297. global $langs;
  298. $sql = "SELECT";
  299. $sql .= " t.rowid,";
  300. $sql .= " t.name,";
  301. $sql .= " t.entity,";
  302. $sql .= " t.fk_element,";
  303. $sql .= " t.type_element,";
  304. $sql .= " t.filtervalue,";
  305. $sql .= " t.fk_user_author,";
  306. $sql .= " t.datec,";
  307. $sql .= " t.fk_user_mod,";
  308. $sql .= " t.tms";
  309. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_advtarget as t";
  310. if (!empty($id)) {
  311. $sql .= " WHERE t.fk_element = ".((int) $id)." AND type_element = '".$this->db->escape($type_element)."'";
  312. } else {
  313. $sql .= " WHERE t.fk_element = ".((int) $this->fk_element)." AND type_element = '".$this->db->escape($type_element)."'";
  314. }
  315. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  316. $resql = $this->db->query($sql);
  317. if ($resql) {
  318. if ($this->db->num_rows($resql)) {
  319. $obj = $this->db->fetch_object($resql);
  320. $this->id = $obj->rowid;
  321. $this->name = $obj->name;
  322. $this->entity = $obj->entity;
  323. $this->fk_element = $obj->fk_element;
  324. $this->type_element = $obj->type_element;
  325. $this->filtervalue = $obj->filtervalue;
  326. $this->fk_user_author = $obj->fk_user_author;
  327. $this->datec = $this->db->jdate($obj->datec);
  328. $this->fk_user_mod = $obj->fk_user_mod;
  329. $this->tms = $this->db->jdate($obj->tms);
  330. }
  331. $this->db->free($resql);
  332. return 1;
  333. } else {
  334. $this->error = "Error ".$this->db->lasterror();
  335. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  336. return -1;
  337. }
  338. }
  339. /**
  340. * Update object into database
  341. *
  342. * @param User $user User that modifies
  343. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  344. * @return int Return integer <0 if KO, >0 if OK
  345. */
  346. public function update($user, $notrigger = 0)
  347. {
  348. global $conf, $langs;
  349. $error = 0;
  350. // Clean parameters
  351. if (isset($this->fk_element)) {
  352. $this->fk_element = (int) $this->fk_element;
  353. }
  354. if (isset($this->type_element)) {
  355. $this->type_element = trim($this->type_element);
  356. }
  357. if (isset($this->name)) {
  358. $this->name = trim($this->name);
  359. }
  360. if (isset($this->filtervalue)) {
  361. $this->filtervalue = trim($this->filtervalue);
  362. }
  363. // Check parameters
  364. // Put here code to add a control on parameters values
  365. // Update request
  366. $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_advtarget SET";
  367. $sql .= " name=".(isset($this->name) ? "'".$this->db->escape($this->name)."'" : "''").",";
  368. $sql .= " entity=".$conf->entity.",";
  369. $sql .= " fk_element=".(isset($this->fk_element) ? $this->fk_element : "null").",";
  370. $sql .= " type_element=".(isset($this->type_element) ? "'".$this->db->escape($this->type_element)."'" : "null").",";
  371. $sql .= " filtervalue=".(isset($this->filtervalue) ? "'".$this->db->escape($this->filtervalue)."'" : "null").",";
  372. $sql .= " fk_user_mod=".$user->id;
  373. $sql .= " WHERE rowid=".((int) $this->id);
  374. $this->db->begin();
  375. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  376. $resql = $this->db->query($sql);
  377. if (!$resql) {
  378. $error++;
  379. $this->errors[] = "Error ".$this->db->lasterror();
  380. }
  381. // Commit or rollback
  382. if ($error) {
  383. foreach ($this->errors as $errmsg) {
  384. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  385. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  386. }
  387. $this->db->rollback();
  388. return -1 * $error;
  389. } else {
  390. $this->db->commit();
  391. return 1;
  392. }
  393. }
  394. /**
  395. * Delete object in database
  396. *
  397. * @param User $user User that deletes
  398. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  399. * @return int Return integer <0 if KO, >0 if OK
  400. */
  401. public function delete($user, $notrigger = 0)
  402. {
  403. global $conf, $langs;
  404. $error = 0;
  405. $this->db->begin();
  406. if (!$error) {
  407. $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_advtarget";
  408. $sql .= " WHERE rowid=".((int) $this->id);
  409. dol_syslog(get_class($this)."::delete sql=".$sql);
  410. $resql = $this->db->query($sql);
  411. if (!$resql) {
  412. $error++;
  413. $this->errors[] = "Error ".$this->db->lasterror();
  414. }
  415. }
  416. // Commit or rollback
  417. if ($error) {
  418. foreach ($this->errors as $errmsg) {
  419. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  420. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  421. }
  422. $this->db->rollback();
  423. return -1 * $error;
  424. } else {
  425. $this->db->commit();
  426. return 1;
  427. }
  428. }
  429. /**
  430. * Save query in database to retrieve it
  431. *
  432. * @param User $user User that deletes
  433. * @param array $arrayquery All element to Query
  434. * @return int Return integer <0 if KO, >0 if OK
  435. */
  436. public function savequery($user, $arrayquery)
  437. {
  438. global $langs, $conf;
  439. if (!empty($arrayquery)) {
  440. $result = $this->fetch_by_mailing($this->fk_element);
  441. $this->filtervalue = json_encode($arrayquery);
  442. if ($result < 0) {
  443. return -1;
  444. }
  445. if (!empty($this->id)) {
  446. $this->update($user);
  447. } else {
  448. $this->create($user);
  449. }
  450. }
  451. return -1;
  452. }
  453. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  454. /**
  455. * Load object in memory from database
  456. *
  457. * @param array $arrayquery All element to Query
  458. * @return int Return integer <0 if KO, >0 if OK
  459. */
  460. public function query_thirdparty($arrayquery)
  461. {
  462. // phpcs:enable
  463. global $langs, $conf, $extrafields;
  464. $sql = "SELECT";
  465. $sql .= " t.rowid";
  466. $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
  467. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_extrafields as te ON te.fk_object=t.rowid ";
  468. $sqlwhere = array();
  469. $sqlwhere[] = 't.entity IN ('.getEntity('societe').')';
  470. if (count($arrayquery) > 0) {
  471. if (array_key_exists('cust_saleman', $arrayquery)) {
  472. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as saleman ON saleman.fk_soc=t.rowid ";
  473. }
  474. if (array_key_exists('cust_categ', $arrayquery)) {
  475. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as custcateg ON custcateg.fk_soc=t.rowid ";
  476. }
  477. if (!empty($arrayquery['cust_name'])) {
  478. $sqlwhere[] = $this->transformToSQL('t.nom', $arrayquery['cust_name']);
  479. }
  480. if (!empty($arrayquery['cust_code'])) {
  481. $sqlwhere[] = $this->transformToSQL('t.code_client', $arrayquery['cust_code']);
  482. }
  483. if (!empty($arrayquery['cust_adress'])) {
  484. $sqlwhere[] = $this->transformToSQL('t.address', $arrayquery['cust_adress']);
  485. }
  486. if (!empty($arrayquery['cust_zip'])) {
  487. $sqlwhere[] = $this->transformToSQL('t.zip', $arrayquery['cust_zip']);
  488. }
  489. if (!empty($arrayquery['cust_city'])) {
  490. $sqlwhere[] = $this->transformToSQL('t.town', $arrayquery['cust_city']);
  491. }
  492. if (!empty($arrayquery['cust_mothercompany'])) {
  493. $str = $this->transformToSQL('nom', $arrayquery['cust_mothercompany']);
  494. $sqlwhere[] = " (t.parent IN (SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE (".$str.")))";
  495. }
  496. if (!empty($arrayquery['cust_status']) && count($arrayquery['cust_status']) > 0) {
  497. $sqlwhere[] = " (t.status IN (".$this->db->sanitize(implode(',', $arrayquery['cust_status']))."))";
  498. }
  499. if (!empty($arrayquery['cust_typecust']) && count($arrayquery['cust_typecust']) > 0) {
  500. $sqlwhere[] = " (t.client IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typecust']))."))";
  501. }
  502. if (!empty($arrayquery['cust_comm_status']) && count($arrayquery['cust_comm_status']) > 0) {
  503. $sqlwhere[] = " (t.fk_stcomm IN (".$this->db->sanitize(implode(',', $arrayquery['cust_comm_status']))."))";
  504. }
  505. if (!empty($arrayquery['cust_prospect_status']) && count($arrayquery['cust_prospect_status']) > 0) {
  506. $sqlwhere[] = " (t.fk_prospectlevel IN (".$this->db->sanitize("'".implode("','", $arrayquery['cust_prospect_status'])."'", 1)."))";
  507. }
  508. if (!empty($arrayquery['cust_typeent']) && count($arrayquery['cust_typeent']) > 0) {
  509. $sqlwhere[] = " (t.fk_typent IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typeent']))."))";
  510. }
  511. if (!empty($arrayquery['cust_saleman']) && count($arrayquery['cust_saleman']) > 0) {
  512. $sqlwhere[] = " (saleman.fk_user IN (".$this->db->sanitize(implode(',', $arrayquery['cust_saleman']))."))";
  513. }
  514. if (!empty($arrayquery['cust_country']) && count($arrayquery['cust_country']) > 0) {
  515. $sqlwhere[] = " (t.fk_pays IN (".$this->db->sanitize(implode(',', $arrayquery['cust_country']))."))";
  516. }
  517. if (!empty($arrayquery['cust_effectif_id']) && count($arrayquery['cust_effectif_id']) > 0) {
  518. $sqlwhere[] = " (t.fk_effectif IN (".$this->db->sanitize(implode(',', $arrayquery['cust_effectif_id']))."))";
  519. }
  520. if (!empty($arrayquery['cust_categ']) && count($arrayquery['cust_categ']) > 0) {
  521. $sqlwhere[] = " (custcateg.fk_categorie IN (".$this->db->sanitize(implode(',', $arrayquery['cust_categ']))."))";
  522. }
  523. if (!empty($arrayquery['cust_language']) && count($arrayquery['cust_language']) > 0) {
  524. $sqlwhere[] = " (t.default_lang IN (".$this->db->sanitize("'".implode("','", $arrayquery['cust_language'])."'", 1)."))";
  525. }
  526. //Standard Extrafield feature
  527. if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
  528. $socstatic = new Societe($this->db);
  529. $elementtype = $socstatic->table_element;
  530. $extrafields->fetch_name_optionals_label($elementtype);
  531. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  532. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  533. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  534. if (!empty($arrayquery['options_'.$key])) {
  535. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  536. }
  537. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  538. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  539. if (!empty($arrayquery['options_'.$key.'_max'])) {
  540. $sqlwhere[] = " (te.".$key." >= ".((float) $arrayquery["options_".$key."_max"])." AND te.".$key." <= ".((float) $arrayquery["options_".$key.'_min']).")";
  541. }
  542. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  543. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  544. if (!empty($arrayquery['options_'.$key.'_end_dt'])) {
  545. $sqlwhere[] = " (te.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt"])."' AND te.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt"])."')";
  546. }
  547. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  548. if ($arrayquery['options_'.$key] != '') {
  549. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key]).")";
  550. }
  551. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'link') {
  552. if ($arrayquery['options_'.$key] > 0) {
  553. $sqlwhere[]= " (te.".$key." = ".((int) $arrayquery["options_".$key]).")";
  554. }
  555. } else {
  556. if (is_array($arrayquery['options_'.$key])) {
  557. $sqlwhere[] = " (te.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key])."'", 1)."))";
  558. } elseif (!empty($arrayquery['options_'.$key])) {
  559. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  560. }
  561. }
  562. }
  563. }
  564. if (count($sqlwhere) > 0) {
  565. $sql .= " WHERE ".implode(" AND ", $sqlwhere);
  566. }
  567. }
  568. dol_syslog(get_class($this)."::query_thirdparty", LOG_DEBUG);
  569. $resql = $this->db->query($sql);
  570. if ($resql) {
  571. $this->thirdparty_lines = array();
  572. $num = $this->db->num_rows($resql);
  573. $i = 0;
  574. if ($num) {
  575. while ($i < $num) {
  576. $obj = $this->db->fetch_object($resql);
  577. $this->thirdparty_lines[$i] = $obj->rowid;
  578. $i++;
  579. }
  580. }
  581. $this->db->free($resql);
  582. return $num;
  583. } else {
  584. $this->error = "Error ".$this->db->lasterror();
  585. dol_syslog(get_class($this)."::query_thirdparty ".$this->error, LOG_ERR);
  586. return -1;
  587. }
  588. }
  589. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  590. /**
  591. * Load object in memory from database
  592. *
  593. * @param array $arrayquery All element to Query
  594. * @param int $withThirdpartyFilter add contact with tridparty filter
  595. * @return int Return integer <0 if KO, >0 if OK
  596. */
  597. public function query_contact($arrayquery, $withThirdpartyFilter = 0)
  598. {
  599. // phpcs:enable
  600. global $langs, $conf;
  601. $sql = "SELECT";
  602. $sql .= " t.rowid";
  603. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
  604. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object=t.rowid ";
  605. if (!empty($withThirdpartyFilter)) {
  606. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as ts ON ts.rowid=t.fk_soc";
  607. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_extrafields as tse ON tse.fk_object=ts.rowid ";
  608. }
  609. $sqlwhere = array();
  610. $sqlwhere[] = 't.entity IN ('.getEntity('contact').')';
  611. if (count($arrayquery) > 0) {
  612. if (array_key_exists('contact_categ', $arrayquery)) {
  613. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_contact as contactcateg ON contactcateg.fk_socpeople=t.rowid ";
  614. }
  615. if (!empty($arrayquery['contact_lastname'])) {
  616. $sqlwhere[] = $this->transformToSQL('t.lastname', $arrayquery['contact_lastname']);
  617. }
  618. if (!empty($arrayquery['contact_firstname'])) {
  619. $sqlwhere[] = $this->transformToSQL('t.firstname', $arrayquery['contact_firstname']);
  620. }
  621. if (!empty($arrayquery['contact_country']) && count($arrayquery['contact_country'])) {
  622. $sqlwhere[] = " (t.fk_pays IN (".$this->db->sanitize($this->db->escape(implode(',', $arrayquery['contact_country'])))."))";
  623. }
  624. if (!empty($arrayquery['contact_status']) && count($arrayquery['contact_status']) > 0) {
  625. $sqlwhere[] = " (t.statut IN (".$this->db->sanitize($this->db->escape(implode(',', $arrayquery['contact_status'])))."))";
  626. }
  627. if (!empty($arrayquery['contact_civility']) && count($arrayquery['contact_civility']) > 0) {
  628. $sqlwhere[] = " (t.civility IN (".$this->db->sanitize("'".implode("','", $arrayquery['contact_civility'])."'", 1)."))";
  629. }
  630. if ($arrayquery['contact_no_email'] != '') {
  631. $tmpwhere = '';
  632. if (!empty($arrayquery['contact_no_email'])) {
  633. $tmpwhere .= "(t.email IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE t.entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($arrayquery['contact_no_email'])."'))";
  634. } else {
  635. $tmpwhere .= "(t.email NOT IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE t.entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($arrayquery['contact_no_email'])."'))";
  636. }
  637. $sqlwhere[] = $tmpwhere;
  638. }
  639. if ($arrayquery['contact_update_st_dt'] != '') {
  640. $sqlwhere[] = " (t.tms >= '".$this->db->idate($arrayquery['contact_update_st_dt'])."' AND t.tms <= '".$this->db->idate($arrayquery['contact_update_end_dt'])."')";
  641. }
  642. if ($arrayquery['contact_create_st_dt'] != '') {
  643. $sqlwhere[] = " (t.datec >= '".$this->db->idate($arrayquery['contact_create_st_dt'])."' AND t.datec <= '".$this->db->idate($arrayquery['contact_create_end_dt'])."')";
  644. }
  645. if (!empty($arrayquery['contact_categ']) && count($arrayquery['contact_categ']) > 0) {
  646. $sqlwhere[] = " (contactcateg.fk_categorie IN (".$this->db->escape(implode(",", $arrayquery['contact_categ']))."))";
  647. }
  648. //Standard Extrafield feature
  649. if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
  650. $contactstatic = new Contact($this->db);
  651. $elementtype = $contactstatic->table_element;
  652. // fetch optionals attributes and labels
  653. dol_include_once('/core/class/extrafields.class.php');
  654. $extrafields = new ExtraFields($this->db);
  655. $extrafields->fetch_name_optionals_label($elementtype);
  656. $extrafields->fetch_name_optionals_label($elementtype);
  657. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  658. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  659. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  660. if (!empty($arrayquery['options_'.$key.'_cnct'])) {
  661. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key."_cnct"])."')";
  662. }
  663. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  664. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  665. if (!empty($arrayquery['options_'.$key.'_max_cnct'])) {
  666. $sqlwhere[] = " (te.".$key." >= ".((float) $arrayquery["options_".$key."_max_cnct"])." AND te.".$key." <= ".((float) $arrayquery["options_".$key."_min_cnct"]).")";
  667. }
  668. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  669. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  670. if (!empty($arrayquery['options_'.$key.'_end_dt_cnct'])) {
  671. $sqlwhere[] = " (te.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt_cnct"])."' AND te.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt_cnct"])."')";
  672. }
  673. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  674. if ($arrayquery['options_'.$key.'_cnct'] != '') {
  675. if ($arrayquery['options_'.$key.'_cnct'] == 0) {
  676. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key."_cnct"])." OR ((te.".$key." IS NULL) AND (te.fk_object IS NOT NULL)))";
  677. } else {
  678. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key."_cnct"]).")";
  679. }
  680. }
  681. } else {
  682. if (is_array($arrayquery['options_'.$key.'_cnct'])) {
  683. $sqlwhere[] = " (te.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key."_cnct"])."'", 1)."))";
  684. } elseif (!empty($arrayquery['options_'.$key.'_cnct'])) {
  685. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key."_cnct"])."')";
  686. }
  687. }
  688. }
  689. if (!empty($withThirdpartyFilter)) {
  690. if (array_key_exists('cust_saleman', $arrayquery)) {
  691. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as saleman ON saleman.fk_soc=ts.rowid ";
  692. }
  693. if (array_key_exists('cust_categ', $arrayquery)) {
  694. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as custcateg ON custcateg.fk_soc=ts.rowid ";
  695. }
  696. if (!empty($arrayquery['cust_name'])) {
  697. $sqlwhere[] = $this->transformToSQL('ts.nom', $arrayquery['cust_name']);
  698. }
  699. if (!empty($arrayquery['cust_code'])) {
  700. $sqlwhere[] = $this->transformToSQL('ts.code_client', $arrayquery['cust_code']);
  701. }
  702. if (!empty($arrayquery['cust_adress'])) {
  703. $sqlwhere[] = $this->transformToSQL('ts.address', $arrayquery['cust_adress']);
  704. }
  705. if (!empty($arrayquery['cust_zip'])) {
  706. $sqlwhere[] = $this->transformToSQL('ts.zip', $arrayquery['cust_zip']);
  707. }
  708. if (!empty($arrayquery['cust_city'])) {
  709. $sqlwhere[] = $this->transformToSQL('ts.town', $arrayquery['cust_city']);
  710. }
  711. if (!empty($arrayquery['cust_mothercompany'])) {
  712. $str = $this->transformToSQL('nom', $arrayquery['cust_mothercompany']);
  713. $sqlwhere[] = " (ts.parent IN (SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE (".$str.")))";
  714. }
  715. if (!empty($arrayquery['cust_status']) && count($arrayquery['cust_status']) > 0) {
  716. $sqlwhere[] = " (ts.status IN (".$this->db->sanitize(implode(',', $arrayquery['cust_status']))."))";
  717. }
  718. if (!empty($arrayquery['cust_typecust']) && count($arrayquery['cust_typecust']) > 0) {
  719. $sqlwhere[] = " (ts.client IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typecust']))."))";
  720. }
  721. if (!empty($arrayquery['cust_comm_status']) && count($arrayquery['cust_comm_status']) > 0) {
  722. $sqlwhere[] = " (ts.fk_stcomm IN (".$this->db->sanitize(implode(',', $arrayquery['cust_comm_status']))."))";
  723. }
  724. if (!empty($arrayquery['cust_prospect_status']) && count($arrayquery['cust_prospect_status']) > 0) {
  725. $sqlwhere[] = " (ts.fk_prospectlevel IN ('".$this->db->sanitize(implode("','", $arrayquery['cust_prospect_status']))."'))";
  726. }
  727. if (!empty($arrayquery['cust_typeent']) && count($arrayquery['cust_typeent']) > 0) {
  728. $sqlwhere[] = " (ts.fk_typent IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typeent']))."))";
  729. }
  730. if (!empty($arrayquery['cust_saleman']) && count($arrayquery['cust_saleman']) > 0) {
  731. $sqlwhere[] = " (saleman.fk_user IN (".$this->db->sanitize(implode(',', $arrayquery['cust_saleman']))."))";
  732. }
  733. if (!empty($arrayquery['cust_country']) && count($arrayquery['cust_country']) > 0) {
  734. $sqlwhere[] = " (ts.fk_pays IN (".$this->db->sanitize(implode(',', $arrayquery['cust_country']))."))";
  735. }
  736. if (!empty($arrayquery['cust_effectif_id']) && count($arrayquery['cust_effectif_id']) > 0) {
  737. $sqlwhere[] = " (ts.fk_effectif IN (".$this->db->sanitize(implode(',', $arrayquery['cust_effectif_id']))."))";
  738. }
  739. if (!empty($arrayquery['cust_categ']) && count($arrayquery['cust_categ']) > 0) {
  740. $sqlwhere[] = " (custcateg.fk_categorie IN (".$this->db->sanitize(implode(',', $arrayquery['cust_categ']))."))";
  741. }
  742. if (!empty($arrayquery['cust_language']) && count($arrayquery['cust_language']) > 0) {
  743. $sqlwhere[] = " (ts.default_lang IN ('".$this->db->sanitize(implode("','", $arrayquery['cust_language']))."'))";
  744. }
  745. //Standard Extrafield feature
  746. if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
  747. $socstatic = new Societe($this->db);
  748. $elementtype = $socstatic->table_element;
  749. // fetch optionals attributes and labels
  750. dol_include_once('/core/class/extrafields.class.php');
  751. $extrafields = new ExtraFields($this->db);
  752. $extrafields->fetch_name_optionals_label($elementtype);
  753. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  754. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  755. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  756. if (!empty($arrayquery['options_'.$key])) {
  757. $sqlwhere[] = " (tse.".$key." LIKE '".$this->db->escape($arrayquery['options_'.$key])."')";
  758. }
  759. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  760. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  761. if (!empty($arrayquery['options_'.$key.'_max'])) {
  762. $sqlwhere[] = " (tse.".$key." >= ".((float) $arrayquery["options_".$key."_max"])." AND tse.".$key." <= ".((float) $arrayquery["options_".$key."_min"]).")";
  763. }
  764. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  765. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  766. if (!empty($arrayquery['options_'.$key.'_end_dt'])) {
  767. $sqlwhere[] = " (tse.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt"])."' AND tse.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt"])."')";
  768. }
  769. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  770. if ($arrayquery['options_'.$key] != '') {
  771. $sqlwhere[] = " (tse.".$key." = ".((int) $arrayquery["options_".$key]).")";
  772. }
  773. } else {
  774. if (is_array($arrayquery['options_'.$key])) {
  775. $sqlwhere[] = " (tse.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key])."'", 1)."))";
  776. } elseif (!empty($arrayquery['options_'.$key])) {
  777. $sqlwhere[] = " (tse.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  778. }
  779. }
  780. }
  781. }
  782. }
  783. }
  784. if (count($sqlwhere) > 0) {
  785. $sql .= " WHERE ".implode(" AND ", $sqlwhere);
  786. }
  787. }
  788. dol_syslog(get_class($this)."::query_contact", LOG_DEBUG);
  789. $resql = $this->db->query($sql);
  790. if ($resql) {
  791. $this->contact_lines = array();
  792. $num = $this->db->num_rows($resql);
  793. $i = 0;
  794. if ($num) {
  795. while ($i < $num) {
  796. $obj = $this->db->fetch_object($resql);
  797. $this->contact_lines[$i] = $obj->rowid;
  798. $i++;
  799. }
  800. }
  801. $this->db->free($resql);
  802. return $num;
  803. } else {
  804. $this->error = "Error ".$this->db->lasterror();
  805. dol_syslog(get_class($this)."::query_contact ".$this->error, LOG_ERR);
  806. return -1;
  807. }
  808. }
  809. /**
  810. * Parse criteria to return a SQL qury formated
  811. *
  812. * @param string $column_to_test column to test
  813. * @param string $criteria Use %% as magic caracters. For exemple to find all item like <b>jean, joe, jim</b>, you can input <b>j%%</b>, you can also use ; as separator for value,
  814. * and use ! for except this value.
  815. * For exemple jean;joe;jim%%;!jimo;!jima%> will target all jean, joe, start with jim but not jimo and not everythnig taht start by jima
  816. * @return string Sql to use for the where condition
  817. */
  818. public function transformToSQL($column_to_test, $criteria)
  819. {
  820. $return_sql_criteria = '(';
  821. //This is a multiple value test
  822. if (preg_match('/;/', $criteria)) {
  823. $return_sql_not_like = array();
  824. $return_sql_like = array();
  825. $criteria_array = explode(';', $criteria);
  826. foreach ($criteria_array as $inter_criteria) {
  827. if (preg_match('/!/', $inter_criteria)) {
  828. $return_sql_not_like[] = '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')';
  829. } else {
  830. $return_sql_like[] = '('.$column_to_test.' LIKE \''.$inter_criteria.'\')';
  831. }
  832. }
  833. if (count($return_sql_like) > 0) {
  834. $return_sql_criteria .= '('.implode(' OR ', $return_sql_like).')';
  835. }
  836. if (count($return_sql_not_like) > 0) {
  837. $return_sql_criteria .= ' AND ('.implode(' AND ', $return_sql_not_like).')';
  838. }
  839. } else {
  840. $return_sql_criteria .= $column_to_test.' LIKE \''.$this->db->escape($criteria).'\'';
  841. }
  842. $return_sql_criteria .= ')';
  843. return $return_sql_criteria;
  844. }
  845. }