advtargetemailing.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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. }
  450. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  451. /**
  452. * Load object in memory from database
  453. *
  454. * @param array $arrayquery All element to Query
  455. * @return int <0 if KO, >0 if OK
  456. */
  457. public function query_thirdparty($arrayquery)
  458. {
  459. // phpcs:enable
  460. global $langs, $conf, $extrafields;
  461. $sql = "SELECT";
  462. $sql .= " t.rowid";
  463. $sql .= " FROM ".MAIN_DB_PREFIX."societe as t";
  464. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_extrafields as te ON te.fk_object=t.rowid ";
  465. $sqlwhere = array();
  466. $sqlwhere[] = 't.entity IN ('.getEntity('societe').')';
  467. if (count($arrayquery) > 0) {
  468. if (array_key_exists('cust_saleman', $arrayquery)) {
  469. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as saleman ON saleman.fk_soc=t.rowid ";
  470. }
  471. if (array_key_exists('cust_categ', $arrayquery)) {
  472. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as custcateg ON custcateg.fk_soc=t.rowid ";
  473. }
  474. if (!empty($arrayquery['cust_name'])) {
  475. $sqlwhere[] = $this->transformToSQL('t.nom', $arrayquery['cust_name']);
  476. }
  477. if (!empty($arrayquery['cust_code'])) {
  478. $sqlwhere[] = $this->transformToSQL('t.code_client', $arrayquery['cust_code']);
  479. }
  480. if (!empty($arrayquery['cust_adress'])) {
  481. $sqlwhere[] = $this->transformToSQL('t.address', $arrayquery['cust_adress']);
  482. }
  483. if (!empty($arrayquery['cust_zip'])) {
  484. $sqlwhere[] = $this->transformToSQL('t.zip', $arrayquery['cust_zip']);
  485. }
  486. if (!empty($arrayquery['cust_city'])) {
  487. $sqlwhere[] = $this->transformToSQL('t.town', $arrayquery['cust_city']);
  488. }
  489. if (!empty($arrayquery['cust_mothercompany'])) {
  490. $str = $this->transformToSQL('nom', $arrayquery['cust_mothercompany']);
  491. $sqlwhere[] = " (t.parent IN (SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE (".$str.")))";
  492. }
  493. if (!empty($arrayquery['cust_status']) && count($arrayquery['cust_status']) > 0) {
  494. $sqlwhere[] = " (t.status IN (".$this->db->sanitize(implode(',', $arrayquery['cust_status']))."))";
  495. }
  496. if (!empty($arrayquery['cust_typecust']) && count($arrayquery['cust_typecust']) > 0) {
  497. $sqlwhere[] = " (t.client IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typecust']))."))";
  498. }
  499. if (!empty($arrayquery['cust_comm_status']) && count($arrayquery['cust_comm_status'] > 0)) {
  500. $sqlwhere[] = " (t.fk_stcomm IN (".$this->db->sanitize(implode(',', $arrayquery['cust_comm_status']))."))";
  501. }
  502. if (!empty($arrayquery['cust_prospect_status']) && count($arrayquery['cust_prospect_status']) > 0) {
  503. $sqlwhere[] = " (t.fk_prospectlevel IN (".$this->db->sanitize("'".implode("','", $arrayquery['cust_prospect_status'])."'", 1)."))";
  504. }
  505. if (!empty($arrayquery['cust_typeent']) && count($arrayquery['cust_typeent']) > 0) {
  506. $sqlwhere[] = " (t.fk_typent IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typeent']))."))";
  507. }
  508. if (!empty($arrayquery['cust_saleman']) && count($arrayquery['cust_saleman']) > 0) {
  509. $sqlwhere[] = " (saleman.fk_user IN (".$this->db->sanitize(implode(',', $arrayquery['cust_saleman']))."))";
  510. }
  511. if (!empty($arrayquery['cust_country']) && count($arrayquery['cust_country']) > 0) {
  512. $sqlwhere[] = " (t.fk_pays IN (".$this->db->sanitize(implode(',', $arrayquery['cust_country']))."))";
  513. }
  514. if (!empty($arrayquery['cust_effectif_id']) && count($arrayquery['cust_effectif_id']) > 0) {
  515. $sqlwhere[] = " (t.fk_effectif IN (".$this->db->sanitize(implode(',', $arrayquery['cust_effectif_id']))."))";
  516. }
  517. if (!empty($arrayquery['cust_categ']) && count($arrayquery['cust_categ']) > 0) {
  518. $sqlwhere[] = " (custcateg.fk_categorie IN (".$this->db->sanitize(implode(',', $arrayquery['cust_categ']))."))";
  519. }
  520. if (!empty($arrayquery['cust_language']) && count($arrayquery['cust_language']) > 0) {
  521. $sqlwhere[] = " (t.default_lang IN (".$this->db->sanitize("'".implode("','", $arrayquery['cust_language'])."'", 1)."))";
  522. }
  523. //Standard Extrafield feature
  524. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  525. $socstatic = new Societe($this->db);
  526. $elementtype = $socstatic->table_element;
  527. $extrafields->fetch_name_optionals_label($elementtype);
  528. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  529. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  530. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  531. if (!empty($arrayquery['options_'.$key])) {
  532. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  533. }
  534. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  535. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  536. if (!empty($arrayquery['options_'.$key.'_max'])) {
  537. $sqlwhere[] = " (te.".$key." >= ".((float) $arrayquery["options_".$key."_max"])." AND te.".$key." <= ".((float) $arrayquery["options_".$key.'_min']).")";
  538. }
  539. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  540. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  541. if (!empty($arrayquery['options_'.$key.'_end_dt'])) {
  542. $sqlwhere[] = " (te.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt"])."' AND te.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt"])."')";
  543. }
  544. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  545. if ($arrayquery['options_'.$key] != '') {
  546. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key]).")";
  547. }
  548. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'link') {
  549. if ($arrayquery['options_'.$key] > 0) {
  550. $sqlwhere[]= " (te.".$key." = ".((int) $arrayquery["options_".$key]).")";
  551. }
  552. } else {
  553. if (is_array($arrayquery['options_'.$key])) {
  554. $sqlwhere[] = " (te.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key])."'", 1)."))";
  555. } elseif (!empty($arrayquery['options_'.$key])) {
  556. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  557. }
  558. }
  559. }
  560. }
  561. if (count($sqlwhere) > 0) {
  562. $sql .= " WHERE ".implode(" AND ", $sqlwhere);
  563. }
  564. }
  565. dol_syslog(get_class($this)."::query_thirdparty", LOG_DEBUG);
  566. $resql = $this->db->query($sql);
  567. if ($resql) {
  568. $this->thirdparty_lines = array();
  569. $num = $this->db->num_rows($resql);
  570. $i = 0;
  571. if ($num) {
  572. while ($i < $num) {
  573. $obj = $this->db->fetch_object($resql);
  574. $this->thirdparty_lines[$i] = $obj->rowid;
  575. $i++;
  576. }
  577. }
  578. $this->db->free($resql);
  579. return $num;
  580. } else {
  581. $this->error = "Error ".$this->db->lasterror();
  582. dol_syslog(get_class($this)."::query_thirdparty ".$this->error, LOG_ERR);
  583. return -1;
  584. }
  585. }
  586. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  587. /**
  588. * Load object in memory from database
  589. *
  590. * @param array $arrayquery All element to Query
  591. * @param int $withThirdpartyFilter add contact with tridparty filter
  592. * @return int <0 if KO, >0 if OK
  593. */
  594. public function query_contact($arrayquery, $withThirdpartyFilter = 0)
  595. {
  596. // phpcs:enable
  597. global $langs, $conf;
  598. $sql = "SELECT";
  599. $sql .= " t.rowid";
  600. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
  601. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object=t.rowid ";
  602. if (!empty($withThirdpartyFilter)) {
  603. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as ts ON ts.rowid=t.fk_soc";
  604. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_extrafields as tse ON tse.fk_object=ts.rowid ";
  605. }
  606. $sqlwhere = array();
  607. $sqlwhere[] = 't.entity IN ('.getEntity('contact').')';
  608. if (count($arrayquery) > 0) {
  609. if (array_key_exists('contact_categ', $arrayquery)) {
  610. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_contact as contactcateg ON contactcateg.fk_socpeople=t.rowid ";
  611. }
  612. if (!empty($arrayquery['contact_lastname'])) {
  613. $sqlwhere[] = $this->transformToSQL('t.lastname', $arrayquery['contact_lastname']);
  614. }
  615. if (!empty($arrayquery['contact_firstname'])) {
  616. $sqlwhere[] = $this->transformToSQL('t.firstname', $arrayquery['contact_firstname']);
  617. }
  618. if (!empty($arrayquery['contact_country']) && count($arrayquery['contact_country'])) {
  619. $sqlwhere[] = " (t.fk_pays IN (".$this->db->sanitize($this->db->escape(implode(',', $arrayquery['contact_country'])))."))";
  620. }
  621. if (!empty($arrayquery['contact_status']) && count($arrayquery['contact_status']) > 0) {
  622. $sqlwhere[] = " (t.statut IN (".$this->db->sanitize($this->db->escape(implode(',', $arrayquery['contact_status'])))."))";
  623. }
  624. if (!empty($arrayquery['contact_civility']) && count($arrayquery['contact_civility']) > 0) {
  625. $sqlwhere[] = " (t.civility IN (".$this->db->sanitize("'".implode("','", $arrayquery['contact_civility'])."'", 1)."))";
  626. }
  627. if ($arrayquery['contact_no_email'] != '') {
  628. $tmpwhere = '';
  629. if (!empty($arrayquery['contact_no_email'])) {
  630. $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'])."'))";
  631. } else {
  632. $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'])."'))";
  633. }
  634. $sqlwhere[] = $tmpwhere;
  635. }
  636. if ($arrayquery['contact_update_st_dt'] != '') {
  637. $sqlwhere[] = " (t.tms >= '".$this->db->idate($arrayquery['contact_update_st_dt'])."' AND t.tms <= '".$this->db->idate($arrayquery['contact_update_end_dt'])."')";
  638. }
  639. if ($arrayquery['contact_create_st_dt'] != '') {
  640. $sqlwhere[] = " (t.datec >= '".$this->db->idate($arrayquery['contact_create_st_dt'])."' AND t.datec <= '".$this->db->idate($arrayquery['contact_create_end_dt'])."')";
  641. }
  642. if (!empty($arrayquery['contact_categ']) && count($arrayquery['contact_categ']) > 0) {
  643. $sqlwhere[] = " (contactcateg.fk_categorie IN (".$this->db->escape(implode(",", $arrayquery['contact_categ']))."))";
  644. }
  645. //Standard Extrafield feature
  646. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  647. $contactstatic = new Contact($this->db);
  648. $elementtype = $contactstatic->table_element;
  649. // fetch optionals attributes and labels
  650. dol_include_once('/core/class/extrafields.class.php');
  651. $extrafields = new ExtraFields($this->db);
  652. $extrafields->fetch_name_optionals_label($elementtype);
  653. $extrafields->fetch_name_optionals_label($elementtype);
  654. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  655. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  656. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  657. if (!empty($arrayquery['options_'.$key.'_cnct'])) {
  658. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key."_cnct"])."')";
  659. }
  660. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  661. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  662. if (!empty($arrayquery['options_'.$key.'_max_cnct'])) {
  663. $sqlwhere[] = " (te.".$key." >= ".((float) $arrayquery["options_".$key."_max_cnct"])." AND te.".$key." <= ".((float) $arrayquery["options_".$key."_min_cnct"]).")";
  664. }
  665. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  666. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  667. if (!empty($arrayquery['options_'.$key.'_end_dt_cnct'])) {
  668. $sqlwhere[] = " (te.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt_cnct"])."' AND te.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt_cnct"])."')";
  669. }
  670. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  671. if ($arrayquery['options_'.$key.'_cnct'] != '') {
  672. if ($arrayquery['options_'.$key.'_cnct'] == 0) {
  673. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key."_cnct"])." OR ((te.".$key." IS NULL) AND (te.fk_object IS NOT NULL)))";
  674. } else {
  675. $sqlwhere[] = " (te.".$key." = ".((int) $arrayquery["options_".$key."_cnct"]).")";
  676. }
  677. }
  678. } else {
  679. if (is_array($arrayquery['options_'.$key.'_cnct'])) {
  680. $sqlwhere[] = " (te.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key."_cnct"])."'", 1)."))";
  681. } elseif (!empty($arrayquery['options_'.$key.'_cnct'])) {
  682. $sqlwhere[] = " (te.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key."_cnct"])."')";
  683. }
  684. }
  685. }
  686. if (!empty($withThirdpartyFilter)) {
  687. if (array_key_exists('cust_saleman', $arrayquery)) {
  688. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as saleman ON saleman.fk_soc=ts.rowid ";
  689. }
  690. if (array_key_exists('cust_categ', $arrayquery)) {
  691. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as custcateg ON custcateg.fk_soc=ts.rowid ";
  692. }
  693. if (!empty($arrayquery['cust_name'])) {
  694. $sqlwhere[] = $this->transformToSQL('ts.nom', $arrayquery['cust_name']);
  695. }
  696. if (!empty($arrayquery['cust_code'])) {
  697. $sqlwhere[] = $this->transformToSQL('ts.code_client', $arrayquery['cust_code']);
  698. }
  699. if (!empty($arrayquery['cust_adress'])) {
  700. $sqlwhere[] = $this->transformToSQL('ts.address', $arrayquery['cust_adress']);
  701. }
  702. if (!empty($arrayquery['cust_zip'])) {
  703. $sqlwhere[] = $this->transformToSQL('ts.zip', $arrayquery['cust_zip']);
  704. }
  705. if (!empty($arrayquery['cust_city'])) {
  706. $sqlwhere[] = $this->transformToSQL('ts.town', $arrayquery['cust_city']);
  707. }
  708. if (!empty($arrayquery['cust_mothercompany'])) {
  709. $str = $this->transformToSQL('nom', $arrayquery['cust_mothercompany']);
  710. $sqlwhere[] = " (ts.parent IN (SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE (".$str.")))";
  711. }
  712. if (!empty($arrayquery['cust_status']) && count($arrayquery['cust_status']) > 0) {
  713. $sqlwhere[] = " (ts.status IN (".$this->db->sanitize(implode(',', $arrayquery['cust_status']))."))";
  714. }
  715. if (!empty($arrayquery['cust_typecust']) && count($arrayquery['cust_typecust']) > 0) {
  716. $sqlwhere[] = " (ts.client IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typecust']))."))";
  717. }
  718. if (!empty($arrayquery['cust_comm_status']) && count($arrayquery['cust_comm_status'] > 0)) {
  719. $sqlwhere[] = " (ts.fk_stcomm IN (".$this->db->sanitize(implode(',', $arrayquery['cust_comm_status']))."))";
  720. }
  721. if (!empty($arrayquery['cust_prospect_status']) && count($arrayquery['cust_prospect_status']) > 0) {
  722. $sqlwhere[] = " (ts.fk_prospectlevel IN ('".$this->db->sanitize(implode("','", $arrayquery['cust_prospect_status']))."'))";
  723. }
  724. if (!empty($arrayquery['cust_typeent']) && count($arrayquery['cust_typeent']) > 0) {
  725. $sqlwhere[] = " (ts.fk_typent IN (".$this->db->sanitize(implode(',', $arrayquery['cust_typeent']))."))";
  726. }
  727. if (!empty($arrayquery['cust_saleman']) && count($arrayquery['cust_saleman']) > 0) {
  728. $sqlwhere[] = " (saleman.fk_user IN (".$this->db->sanitize(implode(',', $arrayquery['cust_saleman']))."))";
  729. }
  730. if (!empty($arrayquery['cust_country']) && count($arrayquery['cust_country']) > 0) {
  731. $sqlwhere[] = " (ts.fk_pays IN (".$this->db->sanitize(implode(',', $arrayquery['cust_country']))."))";
  732. }
  733. if (!empty($arrayquery['cust_effectif_id']) && count($arrayquery['cust_effectif_id']) > 0) {
  734. $sqlwhere[] = " (ts.fk_effectif IN (".$this->db->sanitize(implode(',', $arrayquery['cust_effectif_id']))."))";
  735. }
  736. if (!empty($arrayquery['cust_categ']) && count($arrayquery['cust_categ']) > 0) {
  737. $sqlwhere[] = " (custcateg.fk_categorie IN (".$this->db->sanitize(implode(',', $arrayquery['cust_categ']))."))";
  738. }
  739. if (!empty($arrayquery['cust_language']) && count($arrayquery['cust_language']) > 0) {
  740. $sqlwhere[] = " (ts.default_lang IN ('".$this->db->sanitize(implode("','", $arrayquery['cust_language']))."'))";
  741. }
  742. //Standard Extrafield feature
  743. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
  744. $socstatic = new Societe($this->db);
  745. $elementtype = $socstatic->table_element;
  746. // fetch optionals attributes and labels
  747. dol_include_once('/core/class/extrafields.class.php');
  748. $extrafields = new ExtraFields($this->db);
  749. $extrafields->fetch_name_optionals_label($elementtype);
  750. foreach ($extrafields->attributes[$elementtype]['label'] as $key => $val) {
  751. if (($extrafields->attributes[$elementtype]['type'][$key] == 'varchar') ||
  752. ($extrafields->attributes[$elementtype]['type'][$key] == 'text')) {
  753. if (!empty($arrayquery['options_'.$key])) {
  754. $sqlwhere[] = " (tse.".$key." LIKE '".$this->db->escape($arrayquery['options_'.$key])."')";
  755. }
  756. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'int') ||
  757. ($extrafields->attributes[$elementtype]['type'][$key] == 'double')) {
  758. if (!empty($arrayquery['options_'.$key.'_max'])) {
  759. $sqlwhere[] = " (tse.".$key." >= ".((float) $arrayquery["options_".$key."_max"])." AND tse.".$key." <= ".((float) $arrayquery["options_".$key."_min"]).")";
  760. }
  761. } elseif (($extrafields->attributes[$elementtype]['type'][$key] == 'date') ||
  762. ($extrafields->attributes[$elementtype]['type'][$key] == 'datetime')) {
  763. if (!empty($arrayquery['options_'.$key.'_end_dt'])) {
  764. $sqlwhere[] = " (tse.".$key." >= '".$this->db->idate($arrayquery["options_".$key."_st_dt"])."' AND tse.".$key." <= '".$this->db->idate($arrayquery["options_".$key."_end_dt"])."')";
  765. }
  766. } elseif ($extrafields->attributes[$elementtype]['type'][$key] == 'boolean') {
  767. if ($arrayquery['options_'.$key] != '') {
  768. $sqlwhere[] = " (tse.".$key." = ".((int) $arrayquery["options_".$key]).")";
  769. }
  770. } else {
  771. if (is_array($arrayquery['options_'.$key])) {
  772. $sqlwhere[] = " (tse.".$key." IN (".$this->db->sanitize("'".implode("','", $arrayquery["options_".$key])."'", 1)."))";
  773. } elseif (!empty($arrayquery['options_'.$key])) {
  774. $sqlwhere[] = " (tse.".$key." LIKE '".$this->db->escape($arrayquery["options_".$key])."')";
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. if (count($sqlwhere) > 0) {
  782. $sql .= " WHERE ".implode(" AND ", $sqlwhere);
  783. }
  784. }
  785. dol_syslog(get_class($this)."::query_contact", LOG_DEBUG);
  786. $resql = $this->db->query($sql);
  787. if ($resql) {
  788. $this->contact_lines = array();
  789. $num = $this->db->num_rows($resql);
  790. $i = 0;
  791. if ($num) {
  792. while ($i < $num) {
  793. $obj = $this->db->fetch_object($resql);
  794. $this->contact_lines[$i] = $obj->rowid;
  795. $i++;
  796. }
  797. }
  798. $this->db->free($resql);
  799. return $num;
  800. } else {
  801. $this->error = "Error ".$this->db->lasterror();
  802. dol_syslog(get_class($this)."::query_contact ".$this->error, LOG_ERR);
  803. return -1;
  804. }
  805. }
  806. /**
  807. * Parse criteria to return a SQL qury formated
  808. *
  809. * @param string $column_to_test column to test
  810. * @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,
  811. * and use ! for except this value.
  812. * 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
  813. * @return string Sql to use for the where condition
  814. */
  815. public function transformToSQL($column_to_test, $criteria)
  816. {
  817. $return_sql_criteria = '(';
  818. //This is a multiple value test
  819. if (preg_match('/;/', $criteria)) {
  820. $return_sql_not_like = array();
  821. $return_sql_like = array();
  822. $criteria_array = explode(';', $criteria);
  823. foreach ($criteria_array as $inter_criteria) {
  824. if (preg_match('/!/', $inter_criteria)) {
  825. $return_sql_not_like[] = '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')';
  826. } else {
  827. $return_sql_like[] = '('.$column_to_test.' LIKE \''.$inter_criteria.'\')';
  828. }
  829. }
  830. if (count($return_sql_like) > 0) {
  831. $return_sql_criteria .= '('.implode(' OR ', $return_sql_like).')';
  832. }
  833. if (count($return_sql_not_like) > 0) {
  834. $return_sql_criteria .= ' AND ('.implode(' AND ', $return_sql_not_like).')';
  835. }
  836. } else {
  837. $return_sql_criteria .= $column_to_test.' LIKE \''.$this->db->escape($criteria).'\'';
  838. }
  839. $return_sql_criteria .= ')';
  840. return $return_sql_criteria;
  841. }
  842. }