advtargetemailing.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 <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++; $this->errors[] = "Error ".$this->db->lasterror();
  170. }
  171. if (!$error) {
  172. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."mailing_advtarget");
  173. }
  174. // Commit or rollback
  175. if ($error) {
  176. foreach ($this->errors as $errmsg) {
  177. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  178. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  179. }
  180. $this->db->rollback();
  181. return -1 * $error;
  182. } else {
  183. $this->db->commit();
  184. return $this->id;
  185. }
  186. }
  187. /**
  188. * Load object in memory from the database
  189. *
  190. * @param int $id Id object
  191. * @return int <0 if KO, >0 if OK
  192. */
  193. public function fetch($id)
  194. {
  195. global $langs;
  196. $sql = "SELECT";
  197. $sql .= " t.rowid,";
  198. $sql .= " t.name,";
  199. $sql .= " t.entity,";
  200. $sql .= " t.fk_element,";
  201. $sql .= " t.type_element,";
  202. $sql .= " t.filtervalue,";
  203. $sql .= " t.fk_user_author,";
  204. $sql .= " t.datec,";
  205. $sql .= " t.fk_user_mod,";
  206. $sql .= " t.tms";
  207. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_advtarget as t";
  208. $sql .= " WHERE t.rowid = ".((int) $id);
  209. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  210. $resql = $this->db->query($sql);
  211. if ($resql) {
  212. if ($this->db->num_rows($resql)) {
  213. $obj = $this->db->fetch_object($resql);
  214. $this->id = $obj->rowid;
  215. $this->name = $obj->name;
  216. $this->entity = $obj->entity;
  217. $this->fk_element = $obj->fk_element;
  218. $this->type_element = $obj->type_element;
  219. $this->filtervalue = $obj->filtervalue;
  220. $this->fk_user_author = $obj->fk_user_author;
  221. $this->datec = $this->db->jdate($obj->datec);
  222. $this->fk_user_mod = $obj->fk_user_mod;
  223. $this->tms = $this->db->jdate($obj->tms);
  224. }
  225. $this->db->free($resql);
  226. return 1;
  227. } else {
  228. $this->error = "Error ".$this->db->lasterror();
  229. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  230. return -1;
  231. }
  232. }
  233. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  234. /**
  235. * Load object in memory from the database
  236. *
  237. * @param int $id Id object
  238. * @return int <0 if KO, >0 if OK
  239. */
  240. public function fetch_by_mailing($id = 0)
  241. {
  242. // phpcs:enable
  243. global $langs;
  244. $sql = "SELECT";
  245. $sql .= " t.rowid,";
  246. $sql .= " t.name,";
  247. $sql .= " t.entity,";
  248. $sql .= " t.fk_element,";
  249. $sql .= " t.type_element,";
  250. $sql .= " t.filtervalue,";
  251. $sql .= " t.fk_user_author,";
  252. $sql .= " t.datec,";
  253. $sql .= " t.fk_user_mod,";
  254. $sql .= " t.tms";
  255. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_advtarget as t";
  256. if (!empty($id)) {
  257. $sql .= " WHERE t.fk_element = ".((int) $id)." AND type_element = 'mailing'";
  258. } else {
  259. $sql .= " WHERE t.fk_element = ".((int) $this->fk_element)." AND type_element = 'mailing'";
  260. }
  261. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  262. $resql = $this->db->query($sql);
  263. if ($resql) {
  264. if ($this->db->num_rows($resql)) {
  265. $obj = $this->db->fetch_object($resql);
  266. $this->id = $obj->rowid;
  267. $this->name = $obj->name;
  268. $this->entity = $obj->entity;
  269. $this->fk_element = $obj->fk_element;
  270. $this->type_element = $obj->type_element;
  271. $this->filtervalue = $obj->filtervalue;
  272. $this->fk_user_author = $obj->fk_user_author;
  273. $this->datec = $this->db->jdate($obj->datec);
  274. $this->fk_user_mod = $obj->fk_user_mod;
  275. $this->tms = $this->db->jdate($obj->tms);
  276. }
  277. $this->db->free($resql);
  278. return 1;
  279. } else {
  280. $this->error = "Error ".$this->db->lasterror();
  281. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  282. return -1;
  283. }
  284. }
  285. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  286. /**
  287. * Load object in memory from the database
  288. *
  289. * @param int $id Id object
  290. * @param string $type_element Type target
  291. * @return int <0 if KO, >0 if OK
  292. */
  293. public function fetch_by_element($id = 0, $type_element = 'mailing')
  294. {
  295. // phpcs:enable
  296. global $langs;
  297. $sql = "SELECT";
  298. $sql .= " t.rowid,";
  299. $sql .= " t.name,";
  300. $sql .= " t.entity,";
  301. $sql .= " t.fk_element,";
  302. $sql .= " t.type_element,";
  303. $sql .= " t.filtervalue,";
  304. $sql .= " t.fk_user_author,";
  305. $sql .= " t.datec,";
  306. $sql .= " t.fk_user_mod,";
  307. $sql .= " t.tms";
  308. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_advtarget as t";
  309. if (!empty($id)) {
  310. $sql .= " WHERE t.fk_element = ".((int) $id)." AND type_element = '".$this->db->escape($type_element)."'";
  311. } else {
  312. $sql .= " WHERE t.fk_element = ".((int) $this->fk_element)." AND type_element = '".$this->db->escape($type_element)."'";
  313. }
  314. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  315. $resql = $this->db->query($sql);
  316. if ($resql) {
  317. if ($this->db->num_rows($resql)) {
  318. $obj = $this->db->fetch_object($resql);
  319. $this->id = $obj->rowid;
  320. $this->name = $obj->name;
  321. $this->entity = $obj->entity;
  322. $this->fk_element = $obj->fk_element;
  323. $this->type_element = $obj->type_element;
  324. $this->filtervalue = $obj->filtervalue;
  325. $this->fk_user_author = $obj->fk_user_author;
  326. $this->datec = $this->db->jdate($obj->datec);
  327. $this->fk_user_mod = $obj->fk_user_mod;
  328. $this->tms = $this->db->jdate($obj->tms);
  329. }
  330. $this->db->free($resql);
  331. return 1;
  332. } else {
  333. $this->error = "Error ".$this->db->lasterror();
  334. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  335. return -1;
  336. }
  337. }
  338. /**
  339. * Update object into database
  340. *
  341. * @param User $user User that modifies
  342. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  343. * @return int <0 if KO, >0 if OK
  344. */
  345. public function update($user, $notrigger = 0)
  346. {
  347. global $conf, $langs;
  348. $error = 0;
  349. // Clean parameters
  350. if (isset($this->fk_element)) {
  351. $this->fk_element = (int) $this->fk_element;
  352. }
  353. if (isset($this->type_element)) {
  354. $this->type_element = trim($this->type_element);
  355. }
  356. if (isset($this->name)) {
  357. $this->name = trim($this->name);
  358. }
  359. if (isset($this->filtervalue)) {
  360. $this->filtervalue = trim($this->filtervalue);
  361. }
  362. // Check parameters
  363. // Put here code to add a control on parameters values
  364. // Update request
  365. $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_advtarget SET";
  366. $sql .= " name=".(isset($this->name) ? "'".$this->db->escape($this->name)."'" : "''").",";
  367. $sql .= " entity=".$conf->entity.",";
  368. $sql .= " fk_element=".(isset($this->fk_element) ? $this->fk_element : "null").",";
  369. $sql .= " type_element=".(isset($this->type_element) ? "'".$this->db->escape($this->type_element)."'" : "null").",";
  370. $sql .= " filtervalue=".(isset($this->filtervalue) ? "'".$this->db->escape($this->filtervalue)."'" : "null").",";
  371. $sql .= " fk_user_mod=".$user->id;
  372. $sql .= " WHERE rowid=".((int) $this->id);
  373. $this->db->begin();
  374. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  375. $resql = $this->db->query($sql);
  376. if (!$resql) {
  377. $error++;
  378. $this->errors[] = "Error ".$this->db->lasterror();
  379. }
  380. // Commit or rollback
  381. if ($error) {
  382. foreach ($this->errors as $errmsg) {
  383. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  384. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  385. }
  386. $this->db->rollback();
  387. return -1 * $error;
  388. } else {
  389. $this->db->commit();
  390. return 1;
  391. }
  392. }
  393. /**
  394. * Delete object in database
  395. *
  396. * @param User $user User that deletes
  397. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  398. * @return int <0 if KO, >0 if OK
  399. */
  400. public function delete($user, $notrigger = 0)
  401. {
  402. global $conf, $langs;
  403. $error = 0;
  404. $this->db->begin();
  405. if (!$error) {
  406. $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_advtarget";
  407. $sql .= " WHERE rowid=".((int) $this->id);
  408. dol_syslog(get_class($this)."::delete sql=".$sql);
  409. $resql = $this->db->query($sql);
  410. if (!$resql) {
  411. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  412. }
  413. }
  414. // Commit or rollback
  415. if ($error) {
  416. foreach ($this->errors as $errmsg) {
  417. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  418. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  419. }
  420. $this->db->rollback();
  421. return -1 * $error;
  422. } else {
  423. $this->db->commit();
  424. return 1;
  425. }
  426. }
  427. /**
  428. * Save query in database to retrieve it
  429. *
  430. * @param User $user User that deletes
  431. * @param array $arrayquery All element to Query
  432. * @return int <0 if KO, >0 if OK
  433. */
  434. public function savequery($user, $arrayquery)
  435. {
  436. global $langs, $conf;
  437. if (!empty($arrayquery)) {
  438. $result = $this->fetch_by_mailing($this->fk_element);
  439. $this->filtervalue = json_encode($arrayquery);
  440. if ($result < 0) {
  441. return -1;
  442. }
  443. if (!empty($this->id)) {
  444. $this->update($user);
  445. } else {
  446. $this->create($user);
  447. }
  448. }
  449. return -1;
  450. }
  451. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  452. /**
  453. * Load object in memory from database
  454. *
  455. * @param array $arrayquery All element to Query
  456. * @return int <0 if KO, >0 if OK
  457. */
  458. public function query_thirdparty($arrayquery)
  459. {
  460. // phpcs:enable
  461. global $langs, $conf, $extrafields;
  462. $sql = "SELECT";
  463. $sql .= " t.rowid";
  464. $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
  465. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_extrafields as te ON te.fk_object=t.rowid ";
  466. $sqlwhere = array();
  467. $sqlwhere[] = 't.entity IN ('.getEntity('societe').')';
  468. if (count($arrayquery) > 0) {
  469. if (array_key_exists('cust_saleman', $arrayquery)) {
  470. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as saleman ON saleman.fk_soc=t.rowid ";
  471. }
  472. if (array_key_exists('cust_categ', $arrayquery)) {
  473. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as custcateg ON custcateg.fk_soc=t.rowid ";
  474. }
  475. if (!empty($arrayquery['cust_name'])) {
  476. $sqlwhere[] = $this->transformToSQL('t.nom', $arrayquery['cust_name']);
  477. }
  478. if (!empty($arrayquery['cust_code'])) {
  479. $sqlwhere[] = $this->transformToSQL('t.code_client', $arrayquery['cust_code']);
  480. }
  481. if (!empty($arrayquery['cust_adress'])) {
  482. $sqlwhere[] = $this->transformToSQL('t.address', $arrayquery['cust_adress']);
  483. }
  484. if (!empty($arrayquery['cust_zip'])) {
  485. $sqlwhere[] = $this->transformToSQL('t.zip', $arrayquery['cust_zip']);
  486. }
  487. if (!empty($arrayquery['cust_city'])) {
  488. $sqlwhere[] = $this->transformToSQL('t.town', $arrayquery['cust_city']);
  489. }
  490. if (!empty($arrayquery['cust_mothercompany'])) {
  491. $str = $this->transformToSQL('nom', $arrayquery['cust_mothercompany']);
  492. $sqlwhere[] = " (t.parent IN (SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE (".$str.")))";
  493. }
  494. if (!empty($arrayquery['cust_status']) && count($arrayquery['cust_status']) > 0) {
  495. $sqlwhere[] = " (t.status IN (".$this->db->sanitize(implode(',', $arrayquery['cust_status']))."))";
  496. }
  497. if (!empty($arrayquery['cust_typecust']) && count($arrayquery['cust_typecust']) > 0) {
  498. $sqlwhere[] = " (t.client IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typecust']))."))";
  499. }
  500. if (!empty($arrayquery['cust_comm_status']) && count($arrayquery['cust_comm_status']) > 0) {
  501. $sqlwhere[] = " (t.fk_stcomm IN (".$this->db->sanitize(implode(',', $arrayquery['cust_comm_status']))."))";
  502. }
  503. if (!empty($arrayquery['cust_prospect_status']) && count($arrayquery['cust_prospect_status']) > 0) {
  504. $sqlwhere[] = " (t.fk_prospectlevel IN (".$this->db->sanitize("'".implode("','", $arrayquery['cust_prospect_status'])."'", 1)."))";
  505. }
  506. if (!empty($arrayquery['cust_typeent']) && count($arrayquery['cust_typeent']) > 0) {
  507. $sqlwhere[] = " (t.fk_typent IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typeent']))."))";
  508. }
  509. if (!empty($arrayquery['cust_saleman']) && count($arrayquery['cust_saleman']) > 0) {
  510. $sqlwhere[] = " (saleman.fk_user IN (".$this->db->sanitize(implode(',', $arrayquery['cust_saleman']))."))";
  511. }
  512. if (!empty($arrayquery['cust_country']) && count($arrayquery['cust_country']) > 0) {
  513. $sqlwhere[] = " (t.fk_pays IN (".$this->db->sanitize(implode(',', $arrayquery['cust_country']))."))";
  514. }
  515. if (!empty($arrayquery['cust_effectif_id']) && count($arrayquery['cust_effectif_id']) > 0) {
  516. $sqlwhere[] = " (t.fk_effectif IN (".$this->db->sanitize(implode(',', $arrayquery['cust_effectif_id']))."))";
  517. }
  518. if (!empty($arrayquery['cust_categ']) && count($arrayquery['cust_categ']) > 0) {
  519. $sqlwhere[] = " (custcateg.fk_categorie IN (".$this->db->sanitize(implode(',', $arrayquery['cust_categ']))."))";
  520. }
  521. if (!empty($arrayquery['cust_language']) && count($arrayquery['cust_language']) > 0) {
  522. $sqlwhere[] = " (t.default_lang IN (".$this->db->sanitize("'".implode("','", $arrayquery['cust_language'])."'", 1)."))";
  523. }
  524. //Standard Extrafield feature
  525. if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
  526. $socstatic = new Societe($this->db);
  527. $elementtype = $socstatic->table_element;
  528. $extrafields->fetch_name_optionals_label($elementtype);
  529. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  530. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  531. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  532. if (!empty($arrayquery['options_'.$key])) {
  533. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  534. }
  535. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  536. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  537. if (!empty($arrayquery['options_'.$key.'_max'])) {
  538. $sqlwhere[] = " (te.".$key." >= ".((float) $arrayquery["options_".$key."_max"])." AND te.".$key." <= ".((float) $arrayquery["options_".$key.'_min']).")";
  539. }
  540. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  541. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  542. if (!empty($arrayquery['options_'.$key.'_end_dt'])) {
  543. $sqlwhere[] = " (te.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt"])."' AND te.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt"])."')";
  544. }
  545. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  546. if ($arrayquery['options_'.$key] != '') {
  547. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key]).")";
  548. }
  549. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'link') {
  550. if ($arrayquery['options_'.$key] > 0) {
  551. $sqlwhere[]= " (te.".$key." = ".((int) $arrayquery["options_".$key]).")";
  552. }
  553. } else {
  554. if (is_array($arrayquery['options_'.$key])) {
  555. $sqlwhere[] = " (te.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key])."'", 1)."))";
  556. } elseif (!empty($arrayquery['options_'.$key])) {
  557. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  558. }
  559. }
  560. }
  561. }
  562. if (count($sqlwhere) > 0) {
  563. $sql .= " WHERE ".implode(" AND ", $sqlwhere);
  564. }
  565. }
  566. dol_syslog(get_class($this)."::query_thirdparty", LOG_DEBUG);
  567. $resql = $this->db->query($sql);
  568. if ($resql) {
  569. $this->thirdparty_lines = array();
  570. $num = $this->db->num_rows($resql);
  571. $i = 0;
  572. if ($num) {
  573. while ($i < $num) {
  574. $obj = $this->db->fetch_object($resql);
  575. $this->thirdparty_lines[$i] = $obj->rowid;
  576. $i++;
  577. }
  578. }
  579. $this->db->free($resql);
  580. return $num;
  581. } else {
  582. $this->error = "Error ".$this->db->lasterror();
  583. dol_syslog(get_class($this)."::query_thirdparty ".$this->error, LOG_ERR);
  584. return -1;
  585. }
  586. }
  587. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  588. /**
  589. * Load object in memory from database
  590. *
  591. * @param array $arrayquery All element to Query
  592. * @param int $withThirdpartyFilter add contact with tridparty filter
  593. * @return int <0 if KO, >0 if OK
  594. */
  595. public function query_contact($arrayquery, $withThirdpartyFilter = 0)
  596. {
  597. // phpcs:enable
  598. global $langs, $conf;
  599. $sql = "SELECT";
  600. $sql .= " t.rowid";
  601. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
  602. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object=t.rowid ";
  603. if (!empty($withThirdpartyFilter)) {
  604. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as ts ON ts.rowid=t.fk_soc";
  605. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_extrafields as tse ON tse.fk_object=ts.rowid ";
  606. }
  607. $sqlwhere = array();
  608. $sqlwhere[] = 't.entity IN ('.getEntity('contact').')';
  609. if (count($arrayquery) > 0) {
  610. if (array_key_exists('contact_categ', $arrayquery)) {
  611. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_contact as contactcateg ON contactcateg.fk_socpeople=t.rowid ";
  612. }
  613. if (!empty($arrayquery['contact_lastname'])) {
  614. $sqlwhere[] = $this->transformToSQL('t.lastname', $arrayquery['contact_lastname']);
  615. }
  616. if (!empty($arrayquery['contact_firstname'])) {
  617. $sqlwhere[] = $this->transformToSQL('t.firstname', $arrayquery['contact_firstname']);
  618. }
  619. if (!empty($arrayquery['contact_country']) && count($arrayquery['contact_country'])) {
  620. $sqlwhere[] = " (t.fk_pays IN (".$this->db->sanitize($this->db->escape(implode(',', $arrayquery['contact_country'])))."))";
  621. }
  622. if (!empty($arrayquery['contact_status']) && count($arrayquery['contact_status']) > 0) {
  623. $sqlwhere[] = " (t.statut IN (".$this->db->sanitize($this->db->escape(implode(',', $arrayquery['contact_status'])))."))";
  624. }
  625. if (!empty($arrayquery['contact_civility']) && count($arrayquery['contact_civility']) > 0) {
  626. $sqlwhere[] = " (t.civility IN (".$this->db->sanitize("'".implode("','", $arrayquery['contact_civility'])."'", 1)."))";
  627. }
  628. if ($arrayquery['contact_no_email'] != '') {
  629. $tmpwhere = '';
  630. if (!empty($arrayquery['contact_no_email'])) {
  631. $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'])."'))";
  632. } else {
  633. $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'])."'))";
  634. }
  635. $sqlwhere[] = $tmpwhere;
  636. }
  637. if ($arrayquery['contact_update_st_dt'] != '') {
  638. $sqlwhere[] = " (t.tms >= '".$this->db->idate($arrayquery['contact_update_st_dt'])."' AND t.tms <= '".$this->db->idate($arrayquery['contact_update_end_dt'])."')";
  639. }
  640. if ($arrayquery['contact_create_st_dt'] != '') {
  641. $sqlwhere[] = " (t.datec >= '".$this->db->idate($arrayquery['contact_create_st_dt'])."' AND t.datec <= '".$this->db->idate($arrayquery['contact_create_end_dt'])."')";
  642. }
  643. if (!empty($arrayquery['contact_categ']) && count($arrayquery['contact_categ']) > 0) {
  644. $sqlwhere[] = " (contactcateg.fk_categorie IN (".$this->db->escape(implode(",", $arrayquery['contact_categ']))."))";
  645. }
  646. //Standard Extrafield feature
  647. if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
  648. $contactstatic = new Contact($this->db);
  649. $elementtype = $contactstatic->table_element;
  650. // fetch optionals attributes and labels
  651. dol_include_once('/core/class/extrafields.class.php');
  652. $extrafields = new ExtraFields($this->db);
  653. $extrafields->fetch_name_optionals_label($elementtype);
  654. $extrafields->fetch_name_optionals_label($elementtype);
  655. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  656. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  657. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  658. if (!empty($arrayquery['options_'.$key.'_cnct'])) {
  659. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key."_cnct"])."')";
  660. }
  661. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  662. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  663. if (!empty($arrayquery['options_'.$key.'_max_cnct'])) {
  664. $sqlwhere[] = " (te.".$key." >= ".((float) $arrayquery["options_".$key."_max_cnct"])." AND te.".$key." <= ".((float) $arrayquery["options_".$key."_min_cnct"]).")";
  665. }
  666. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  667. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  668. if (!empty($arrayquery['options_'.$key.'_end_dt_cnct'])) {
  669. $sqlwhere[] = " (te.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt_cnct"])."' AND te.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt_cnct"])."')";
  670. }
  671. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  672. if ($arrayquery['options_'.$key.'_cnct'] != '') {
  673. if ($arrayquery['options_'.$key.'_cnct'] == 0) {
  674. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key."_cnct"])." OR ((te.".$key." IS NULL) AND (te.fk_object IS NOT NULL)))";
  675. } else {
  676. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key."_cnct"]).")";
  677. }
  678. }
  679. } else {
  680. if (is_array($arrayquery['options_'.$key.'_cnct'])) {
  681. $sqlwhere[] = " (te.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key."_cnct"])."'", 1)."))";
  682. } elseif (!empty($arrayquery['options_'.$key.'_cnct'])) {
  683. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key."_cnct"])."')";
  684. }
  685. }
  686. }
  687. if (!empty($withThirdpartyFilter)) {
  688. if (array_key_exists('cust_saleman', $arrayquery)) {
  689. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as saleman ON saleman.fk_soc=ts.rowid ";
  690. }
  691. if (array_key_exists('cust_categ', $arrayquery)) {
  692. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as custcateg ON custcateg.fk_soc=ts.rowid ";
  693. }
  694. if (!empty($arrayquery['cust_name'])) {
  695. $sqlwhere[] = $this->transformToSQL('ts.nom', $arrayquery['cust_name']);
  696. }
  697. if (!empty($arrayquery['cust_code'])) {
  698. $sqlwhere[] = $this->transformToSQL('ts.code_client', $arrayquery['cust_code']);
  699. }
  700. if (!empty($arrayquery['cust_adress'])) {
  701. $sqlwhere[] = $this->transformToSQL('ts.address', $arrayquery['cust_adress']);
  702. }
  703. if (!empty($arrayquery['cust_zip'])) {
  704. $sqlwhere[] = $this->transformToSQL('ts.zip', $arrayquery['cust_zip']);
  705. }
  706. if (!empty($arrayquery['cust_city'])) {
  707. $sqlwhere[] = $this->transformToSQL('ts.town', $arrayquery['cust_city']);
  708. }
  709. if (!empty($arrayquery['cust_mothercompany'])) {
  710. $str = $this->transformToSQL('nom', $arrayquery['cust_mothercompany']);
  711. $sqlwhere[] = " (ts.parent IN (SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE (".$str.")))";
  712. }
  713. if (!empty($arrayquery['cust_status']) && count($arrayquery['cust_status']) > 0) {
  714. $sqlwhere[] = " (ts.status IN (".$this->db->sanitize(implode(',', $arrayquery['cust_status']))."))";
  715. }
  716. if (!empty($arrayquery['cust_typecust']) && count($arrayquery['cust_typecust']) > 0) {
  717. $sqlwhere[] = " (ts.client IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typecust']))."))";
  718. }
  719. if (!empty($arrayquery['cust_comm_status']) && count($arrayquery['cust_comm_status']) > 0) {
  720. $sqlwhere[] = " (ts.fk_stcomm IN (".$this->db->sanitize(implode(',', $arrayquery['cust_comm_status']))."))";
  721. }
  722. if (!empty($arrayquery['cust_prospect_status']) && count($arrayquery['cust_prospect_status']) > 0) {
  723. $sqlwhere[] = " (ts.fk_prospectlevel IN ('".$this->db->sanitize(implode("','", $arrayquery['cust_prospect_status']))."'))";
  724. }
  725. if (!empty($arrayquery['cust_typeent']) && count($arrayquery['cust_typeent']) > 0) {
  726. $sqlwhere[] = " (ts.fk_typent IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typeent']))."))";
  727. }
  728. if (!empty($arrayquery['cust_saleman']) && count($arrayquery['cust_saleman']) > 0) {
  729. $sqlwhere[] = " (saleman.fk_user IN (".$this->db->sanitize(implode(',', $arrayquery['cust_saleman']))."))";
  730. }
  731. if (!empty($arrayquery['cust_country']) && count($arrayquery['cust_country']) > 0) {
  732. $sqlwhere[] = " (ts.fk_pays IN (".$this->db->sanitize(implode(',', $arrayquery['cust_country']))."))";
  733. }
  734. if (!empty($arrayquery['cust_effectif_id']) && count($arrayquery['cust_effectif_id']) > 0) {
  735. $sqlwhere[] = " (ts.fk_effectif IN (".$this->db->sanitize(implode(',', $arrayquery['cust_effectif_id']))."))";
  736. }
  737. if (!empty($arrayquery['cust_categ']) && count($arrayquery['cust_categ']) > 0) {
  738. $sqlwhere[] = " (custcateg.fk_categorie IN (".$this->db->sanitize(implode(',', $arrayquery['cust_categ']))."))";
  739. }
  740. if (!empty($arrayquery['cust_language']) && count($arrayquery['cust_language']) > 0) {
  741. $sqlwhere[] = " (ts.default_lang IN ('".$this->db->sanitize(implode("','", $arrayquery['cust_language']))."'))";
  742. }
  743. //Standard Extrafield feature
  744. if (!getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
  745. $socstatic = new Societe($this->db);
  746. $elementtype = $socstatic->table_element;
  747. // fetch optionals attributes and labels
  748. dol_include_once('/core/class/extrafields.class.php');
  749. $extrafields = new ExtraFields($this->db);
  750. $extrafields->fetch_name_optionals_label($elementtype);
  751. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  752. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  753. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  754. if (!empty($arrayquery['options_'.$key])) {
  755. $sqlwhere[] = " (tse.".$key." LIKE '".$this->db->escape($arrayquery['options_'.$key])."')";
  756. }
  757. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  758. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  759. if (!empty($arrayquery['options_'.$key.'_max'])) {
  760. $sqlwhere[] = " (tse.".$key." >= ".((float) $arrayquery["options_".$key."_max"])." AND tse.".$key." <= ".((float) $arrayquery["options_".$key."_min"]).")";
  761. }
  762. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  763. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  764. if (!empty($arrayquery['options_'.$key.'_end_dt'])) {
  765. $sqlwhere[] = " (tse.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt"])."' AND tse.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt"])."')";
  766. }
  767. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  768. if ($arrayquery['options_'.$key] != '') {
  769. $sqlwhere[] = " (tse.".$key." = ".((int) $arrayquery["options_".$key]).")";
  770. }
  771. } else {
  772. if (is_array($arrayquery['options_'.$key])) {
  773. $sqlwhere[] = " (tse.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key])."'", 1)."))";
  774. } elseif (!empty($arrayquery['options_'.$key])) {
  775. $sqlwhere[] = " (tse.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  776. }
  777. }
  778. }
  779. }
  780. }
  781. }
  782. if (count($sqlwhere) > 0) {
  783. $sql .= " WHERE ".implode(" AND ", $sqlwhere);
  784. }
  785. }
  786. dol_syslog(get_class($this)."::query_contact", LOG_DEBUG);
  787. $resql = $this->db->query($sql);
  788. if ($resql) {
  789. $this->contact_lines = array();
  790. $num = $this->db->num_rows($resql);
  791. $i = 0;
  792. if ($num) {
  793. while ($i < $num) {
  794. $obj = $this->db->fetch_object($resql);
  795. $this->contact_lines[$i] = $obj->rowid;
  796. $i++;
  797. }
  798. }
  799. $this->db->free($resql);
  800. return $num;
  801. } else {
  802. $this->error = "Error ".$this->db->lasterror();
  803. dol_syslog(get_class($this)."::query_contact ".$this->error, LOG_ERR);
  804. return -1;
  805. }
  806. }
  807. /**
  808. * Parse criteria to return a SQL qury formated
  809. *
  810. * @param string $column_to_test column to test
  811. * @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,
  812. * and use ! for except this value.
  813. * 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
  814. * @return string Sql to use for the where condition
  815. */
  816. public function transformToSQL($column_to_test, $criteria)
  817. {
  818. $return_sql_criteria = '(';
  819. //This is a multiple value test
  820. if (preg_match('/;/', $criteria)) {
  821. $return_sql_not_like = array();
  822. $return_sql_like = array();
  823. $criteria_array = explode(';', $criteria);
  824. foreach ($criteria_array as $inter_criteria) {
  825. if (preg_match('/!/', $inter_criteria)) {
  826. $return_sql_not_like[] = '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')';
  827. } else {
  828. $return_sql_like[] = '('.$column_to_test.' LIKE \''.$inter_criteria.'\')';
  829. }
  830. }
  831. if (count($return_sql_like) > 0) {
  832. $return_sql_criteria .= '('.implode(' OR ', $return_sql_like).')';
  833. }
  834. if (count($return_sql_not_like) > 0) {
  835. $return_sql_criteria .= ' AND ('.implode(' AND ', $return_sql_not_like).')';
  836. }
  837. } else {
  838. $return_sql_criteria .= $column_to_test.' LIKE \''.$this->db->escape($criteria).'\'';
  839. }
  840. $return_sql_criteria .= ')';
  841. return $return_sql_criteria;
  842. }
  843. }