contact.class.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120
  1. <?php
  2. /* Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  4. * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  7. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  8. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  9. * Copyright (C) 2013 Alexandre Spangaro <aspangaro@open-dsi.fr>
  10. * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  12. * Copyright (C) 2019 Nicolas ZABOURI <info@inovea-conseil.com>
  13. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 3 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  27. */
  28. /**
  29. * \file htdocs/contact/class/contact.class.php
  30. * \ingroup societe
  31. * \brief File of contacts class
  32. */
  33. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  34. /**
  35. * Class to manage contact/addresses
  36. */
  37. class Contact extends CommonObject
  38. {
  39. /**
  40. * @var string ID to identify managed object
  41. */
  42. public $element = 'contact';
  43. /**
  44. * @var string Name of table without prefix where object is stored
  45. */
  46. public $table_element = 'socpeople';
  47. /**
  48. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  49. * @var int
  50. */
  51. public $ismultientitymanaged = 1;
  52. /**
  53. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  54. */
  55. public $picto = 'contact';
  56. /**
  57. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  58. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  59. * 'label' the translation key.
  60. * 'enabled' is a condition when the field must be managed.
  61. * 'position' is the sort order of field.
  62. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  63. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  64. * 'noteditable' says if field is not editable (1 or 0)
  65. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  66. * 'index' if we want an index in database.
  67. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  68. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  69. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  70. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  71. * 'help' is a string visible as a tooltip on field
  72. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  73. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  74. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  75. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  76. *
  77. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  78. */
  79. // BEGIN MODULEBUILDER PROPERTIES
  80. /**
  81. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  82. */
  83. public $fields = array(
  84. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  85. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>30, 'index'=>1),
  86. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>3, 'position'=>35),
  87. 'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>3, 'position'=>40),
  88. 'lastname' =>array('type'=>'varchar(50)', 'label'=>'Lastname', 'enabled'=>1, 'visible'=>1, 'position'=>45, 'showoncombobox'=>1, 'searchall'=>1),
  89. 'firstname' =>array('type'=>'varchar(50)', 'label'=>'Firstname', 'enabled'=>1, 'visible'=>1, 'position'=>50, 'showoncombobox'=>1, 'searchall'=>1),
  90. 'poste' =>array('type'=>'varchar(80)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>-1, 'position'=>52),
  91. 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  92. 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>1, 'position'=>60),
  93. 'town' =>array('type'=>'text', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
  94. 'fk_departement' =>array('type'=>'integer', 'label'=>'Fk departement', 'enabled'=>1, 'visible'=>3, 'position'=>70),
  95. 'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>3, 'position'=>75),
  96. 'fk_soc' =>array('type'=>'integer', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>1, 'position'=>77, 'searchall'=>1),
  97. 'birthday' =>array('type'=>'date', 'label'=>'Birthday', 'enabled'=>1, 'visible'=>3, 'position'=>80),
  98. 'phone' =>array('type'=>'varchar(30)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>1, 'position'=>90, 'searchall'=>1),
  99. 'phone_perso' =>array('type'=>'varchar(30)', 'label'=>'PhonePerso', 'enabled'=>1, 'visible'=>-1, 'position'=>95, 'searchall'=>1),
  100. 'phone_mobile' =>array('type'=>'varchar(30)', 'label'=>'PhoneMobile', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'searchall'=>1),
  101. 'fax' =>array('type'=>'varchar(30)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105, 'searchall'=>1),
  102. 'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>1, 'position'=>110, 'searchall'=>1),
  103. 'socialnetworks' =>array('type'=>'text', 'label'=>'SocialNetworks', 'enabled'=>1, 'visible'=>3, 'position'=>115),
  104. 'photo' =>array('type'=>'varchar(255)', 'label'=>'Photo', 'enabled'=>1, 'visible'=>3, 'position'=>170),
  105. 'priv' =>array('type'=>'smallint(6)', 'label'=>'ContactVisibility', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>175),
  106. 'fk_stcommcontact' =>array('type'=>'integer', 'label'=>'ProspectStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
  107. 'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
  108. 'no_email' =>array('type'=>'smallint(6)', 'label'=>'No_Email', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>180),
  109. 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>3, 'position'=>195, 'searchall'=>1),
  110. 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>3, 'position'=>200, 'searchall'=>1),
  111. 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>3, 'position'=>205),
  112. 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>3, 'position'=>210),
  113. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
  114. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>305),
  115. 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>3, 'position'=>310),
  116. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>3, 'position'=>315),
  117. 'statut' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500),
  118. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000),
  119. );
  120. public $civility_id; // In fact we store civility_code
  121. public $civility_code;
  122. public $civility;
  123. /**
  124. * @var string The civilite code, not an integer
  125. * @deprecated
  126. * @see $civility_code
  127. */
  128. public $civilite;
  129. /**
  130. * @var string Address
  131. */
  132. public $address;
  133. /**
  134. * @var string zip code
  135. */
  136. public $zip;
  137. /**
  138. * @var string Town
  139. */
  140. public $town;
  141. /**
  142. * @var int // Id of department
  143. */
  144. public $state_id;
  145. /**
  146. * @var string // Code of department
  147. */
  148. public $state_code;
  149. /**
  150. * @var string // Label of department
  151. */
  152. public $state;
  153. public $poste; // Position
  154. /**
  155. * @var int Thirdparty ID
  156. */
  157. public $socid; // both socid and fk_soc are used
  158. public $fk_soc; // both socid and fk_soc are used
  159. /**
  160. * @var int 0=inactive, 1=active
  161. */
  162. public $statut;
  163. public $code;
  164. /**
  165. * Email
  166. * @var string
  167. */
  168. public $email;
  169. /**
  170. * URL
  171. * @var string
  172. */
  173. public $url;
  174. /**
  175. * Unsuscribe all : 1 = contact has globaly unsubscribe of all mass emailings
  176. * @var int
  177. */
  178. public $no_email;
  179. /**
  180. * @var array array of socialnetworks
  181. */
  182. public $socialnetworks;
  183. /**
  184. * Skype username
  185. * @var string
  186. * @deprecated
  187. */
  188. public $skype;
  189. /**
  190. * Twitter username
  191. * @var string
  192. * @deprecated
  193. */
  194. public $twitter;
  195. /**
  196. * Facebook username
  197. * @var string
  198. * @deprecated
  199. */
  200. public $facebook;
  201. /**
  202. * Linkedin username
  203. * @var string
  204. * @deprecated
  205. */
  206. public $linkedin;
  207. /**
  208. * Jabber username
  209. * @var string
  210. * @deprecated
  211. */
  212. public $jabberid;
  213. /**
  214. * @var string filename for photo
  215. */
  216. public $photo;
  217. /**
  218. * @var string phone pro
  219. */
  220. public $phone_pro;
  221. /**
  222. * @var string phone perso
  223. */
  224. public $phone_perso;
  225. /**
  226. * @var string phone mobile
  227. */
  228. public $phone_mobile;
  229. /**
  230. * @var string fax
  231. */
  232. public $fax;
  233. /**
  234. * Private or public
  235. * @var int
  236. */
  237. public $priv;
  238. public $birthday;
  239. public $default_lang;
  240. /**
  241. * @var int Number of invoices for which he is contact
  242. */
  243. public $ref_facturation;
  244. /**
  245. * @var int Number of contracts for which he is contact
  246. */
  247. public $ref_contrat;
  248. /**
  249. * @var int Number of orders for which he is contact
  250. */
  251. public $ref_commande;
  252. /**
  253. * @var int Number of proposals for which he is contact
  254. */
  255. public $ref_propal;
  256. /**
  257. * @var int user ID
  258. */
  259. public $user_id;
  260. /**
  261. * @var string user login
  262. */
  263. public $user_login;
  264. // END MODULEBUILDER PROPERTIES
  265. /**
  266. * Old copy
  267. * @var Contact
  268. */
  269. public $oldcopy; // To contains a clone of this when we need to save old properties of object
  270. /**
  271. * @var array roles
  272. */
  273. public $roles;
  274. public $cacheprospectstatus = array();
  275. public $fk_prospectlevel;
  276. public $stcomm_id;
  277. public $statut_commercial;
  278. /**
  279. * @var string picto
  280. */
  281. public $stcomm_picto;
  282. /**
  283. * Constructor
  284. *
  285. * @param DoliDB $db Database handler
  286. */
  287. public function __construct($db)
  288. {
  289. global $conf, $langs;
  290. $this->db = $db;
  291. $this->statut = 1; // By default, status is enabled
  292. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
  293. $this->fields['rowid']['visible'] = 0;
  294. }
  295. if (!isModEnabled('mailing')) {
  296. $this->fields['no_email']['enabled'] = 0;
  297. }
  298. // typical ['s.nom'] is used for third-parties
  299. if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
  300. $this->fields['fk_soc']['enabled'] = 0;
  301. $this->fields['fk_soc']['searchall'] = 0;
  302. }
  303. if (empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { // Default behaviour
  304. $this->field['fk_stcommcontact']['enabled'] = 0;
  305. $this->field['fk_prospectcontactlevel']['enabled'] = 0;
  306. }
  307. // Unset fields that are disabled
  308. foreach ($this->fields as $key => $val) {
  309. if (isset($val['enabled']) && empty($val['enabled'])) {
  310. unset($this->fields[$key]);
  311. }
  312. }
  313. // Translate some data of arrayofkeyval
  314. /*if (is_object($langs))
  315. {
  316. foreach($this->fields as $key => $val)
  317. {
  318. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
  319. {
  320. foreach($val['arrayofkeyval'] as $key2 => $val2)
  321. {
  322. $this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2);
  323. }
  324. }
  325. }
  326. }*/
  327. }
  328. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  329. /**
  330. * Load indicators into this->nb for board
  331. *
  332. * @return int <0 if KO, >0 if OK
  333. */
  334. public function load_state_board()
  335. {
  336. // phpcs:enable
  337. global $user, $hookmanager;
  338. $this->nb = array();
  339. $clause = "WHERE";
  340. $sql = "SELECT count(sp.rowid) as nb";
  341. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
  342. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  343. $sql .= ", ".MAIN_DB_PREFIX."societe as s";
  344. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  345. $sql .= " WHERE sp.fk_soc = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  346. $clause = "AND";
  347. }
  348. $sql .= " ".$clause." sp.entity IN (".getEntity($this->element).")";
  349. $sql .= " AND (sp.priv='0' OR (sp.priv='1' AND sp.fk_user_creat = ".((int) $user->id)."))";
  350. if ($user->socid > 0) {
  351. $sql .= " AND sp.fk_soc = ".((int) $user->socid);
  352. }
  353. // Add where from hooks
  354. if (is_object($hookmanager)) {
  355. $parameters = array();
  356. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
  357. $sql .= $hookmanager->resPrint;
  358. }
  359. $resql = $this->db->query($sql);
  360. if ($resql) {
  361. while ($obj = $this->db->fetch_object($resql)) {
  362. $this->nb["contacts"] = $obj->nb;
  363. }
  364. $this->db->free($resql);
  365. return 1;
  366. } else {
  367. dol_print_error($this->db);
  368. $this->error = $this->db->lasterror();
  369. return -1;
  370. }
  371. }
  372. /**
  373. * Add a contact into database
  374. *
  375. * @param User $user Object user that create
  376. * @return int <0 if KO, >0 if OK
  377. */
  378. public function create($user)
  379. {
  380. global $conf, $langs;
  381. $error = 0;
  382. $now = dol_now();
  383. $this->db->begin();
  384. // Clean parameters
  385. $this->lastname = $this->lastname ?trim($this->lastname) : trim($this->name);
  386. $this->firstname = trim($this->firstname);
  387. $this->setUpperOrLowerCase();
  388. if (empty($this->socid)) {
  389. $this->socid = 0;
  390. }
  391. if (empty($this->priv)) {
  392. $this->priv = 0;
  393. }
  394. if (empty($this->statut)) {
  395. $this->statut = 0; // This is to convert '' into '0' to avoid bad sql request
  396. }
  397. $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
  398. $sql = "INSERT INTO ".MAIN_DB_PREFIX."socpeople (";
  399. $sql .= " datec";
  400. $sql .= ", fk_soc";
  401. $sql .= ", lastname";
  402. $sql .= ", firstname";
  403. $sql .= ", fk_user_creat";
  404. $sql .= ", priv";
  405. $sql .= ", fk_stcommcontact";
  406. $sql .= ", statut";
  407. $sql .= ", canvas";
  408. $sql .= ", entity";
  409. $sql .= ", ref_ext";
  410. $sql .= ", import_key";
  411. $sql .= ") VALUES (";
  412. $sql .= "'".$this->db->idate($now)."',";
  413. if ($this->socid > 0) {
  414. $sql .= " ".((int) $this->socid).",";
  415. } else {
  416. $sql .= "null,";
  417. }
  418. $sql .= "'".$this->db->escape($this->lastname)."',";
  419. $sql .= "'".$this->db->escape($this->firstname)."',";
  420. $sql .= " ".($user->id > 0 ? ((int) $user->id) : "null").",";
  421. $sql .= " ".((int) $this->priv).",";
  422. $sql .= " 0,";
  423. $sql .= " ".((int) $this->statut).",";
  424. $sql .= " ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null").",";
  425. $sql .= " ".((int) $this->entity).",";
  426. $sql .= "'".$this->db->escape($this->ref_ext)."',";
  427. $sql .= " ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
  428. $sql .= ")";
  429. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  430. $resql = $this->db->query($sql);
  431. if ($resql) {
  432. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."socpeople");
  433. if (!$error) {
  434. $result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ...
  435. if ($result < 0) {
  436. $error++;
  437. $this->error = $this->db->lasterror();
  438. }
  439. }
  440. if (!$error) {
  441. $result = $this->update_perso($this->id, $user, 1); // TODO Remove function update_perso, should be same than update
  442. if ($result < 0) {
  443. $error++;
  444. $this->error = $this->db->lasterror();
  445. }
  446. }
  447. if (!$error) {
  448. // Call trigger
  449. $result = $this->call_trigger('CONTACT_CREATE', $user);
  450. if ($result < 0) {
  451. $error++;
  452. }
  453. // End call triggers
  454. }
  455. if (!$error) {
  456. $this->db->commit();
  457. return $this->id;
  458. } else {
  459. $this->db->rollback();
  460. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  461. return -2;
  462. }
  463. } else {
  464. $this->error = $this->db->lasterror();
  465. $this->db->rollback();
  466. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  467. return -1;
  468. }
  469. }
  470. /**
  471. * Update informations into database
  472. *
  473. * @param int $id Id of contact/address to update
  474. * @param User $user Objet user making change
  475. * @param int $notrigger 0=no, 1=yes
  476. * @param string $action Current action for hookmanager
  477. * @param int $nosyncuser No sync linked user (external users and contacts are linked)
  478. * @return int <0 if KO, >0 if OK
  479. */
  480. public function update($id, $user = null, $notrigger = 0, $action = 'update', $nosyncuser = 0)
  481. {
  482. global $conf, $langs, $hookmanager;
  483. $error = 0;
  484. $this->id = $id;
  485. $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
  486. // Clean parameters
  487. $this->ref_ext = trim($this->ref_ext);
  488. $this->lastname = trim($this->lastname) ?trim($this->lastname) : trim($this->lastname);
  489. $this->firstname = trim($this->firstname);
  490. $this->email = trim($this->email);
  491. $this->phone_pro = trim($this->phone_pro);
  492. $this->phone_perso = trim($this->phone_perso);
  493. $this->phone_mobile = trim($this->phone_mobile);
  494. $this->photo = trim($this->photo);
  495. $this->fax = trim($this->fax);
  496. $this->zip = (empty($this->zip) ? '' : trim($this->zip));
  497. $this->town = (empty($this->town) ? '' : trim($this->town));
  498. $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
  499. if (empty($this->statut)) {
  500. $this->statut = 0;
  501. }
  502. if (empty($this->civility_code) && !is_numeric($this->civility_id)) {
  503. $this->civility_code = $this->civility_id; // For backward compatibility
  504. }
  505. $this->setUpperOrLowerCase();
  506. $this->db->begin();
  507. $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET";
  508. if ($this->socid > 0) {
  509. $sql .= " fk_soc = ".((int) $this->socid).",";
  510. } elseif ($this->socid == -1) {
  511. $sql .= " fk_soc = NULL,";
  512. }
  513. $sql .= " civility='".$this->db->escape($this->civility_code)."'";
  514. $sql .= ", lastname='".$this->db->escape($this->lastname)."'";
  515. $sql .= ", firstname='".$this->db->escape($this->firstname)."'";
  516. $sql .= ", address='".$this->db->escape($this->address)."'";
  517. $sql .= ", zip='".$this->db->escape($this->zip)."'";
  518. $sql .= ", town='".$this->db->escape($this->town)."'";
  519. $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "NULL");
  520. $sql .= ", fk_pays=".($this->country_id > 0 ? $this->country_id : 'NULL');
  521. $sql .= ", fk_departement=".($this->state_id > 0 ? $this->state_id : 'NULL');
  522. $sql .= ", poste='".$this->db->escape($this->poste)."'";
  523. $sql .= ", fax='".$this->db->escape($this->fax)."'";
  524. $sql .= ", email='".$this->db->escape($this->email)."'";
  525. $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
  526. $sql .= ", photo='".$this->db->escape($this->photo)."'";
  527. $sql .= ", birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
  528. $sql .= ", note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "NULL");
  529. $sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "NULL");
  530. $sql .= ", phone = ".(isset($this->phone_pro) ? "'".$this->db->escape($this->phone_pro)."'" : "NULL");
  531. $sql .= ", phone_perso = ".(isset($this->phone_perso) ? "'".$this->db->escape($this->phone_perso)."'" : "NULL");
  532. $sql .= ", phone_mobile = ".(isset($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "NULL");
  533. $sql .= ", priv = '".$this->db->escape($this->priv)."'";
  534. $sql .= ", fk_prospectcontactlevel = '".$this->db->escape($this->fk_prospectlevel)."'";
  535. if (isset($this->stcomm_id)) {
  536. $sql .= ", fk_stcommcontact = ".($this->stcomm_id > 0 || $this->stcomm_id == -1 ? $this->stcomm_id : "0");
  537. }
  538. $sql .= ", statut = ".((int) $this->statut);
  539. $sql .= ", fk_user_modif=".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "NULL");
  540. $sql .= ", default_lang=".($this->default_lang ? "'".$this->db->escape($this->default_lang)."'" : "NULL");
  541. $sql .= ", entity = ".((int) $this->entity);
  542. $sql .= " WHERE rowid = ".((int) $id);
  543. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  544. $result = $this->db->query($sql);
  545. if ($result) {
  546. unset($this->country_code);
  547. unset($this->country);
  548. unset($this->state_code);
  549. unset($this->state);
  550. $action = 'update';
  551. // Actions on extra fields
  552. if (!$error) {
  553. $result = $this->insertExtraFields();
  554. if ($result < 0) {
  555. $error++;
  556. }
  557. }
  558. if (!$error) {
  559. $result = $this->updateRoles();
  560. if ($result < 0) {
  561. $error++;
  562. }
  563. }
  564. if (!$error && $this->user_id > 0) {
  565. // If contact is linked to a user
  566. $tmpobj = new User($this->db);
  567. $tmpobj->fetch($this->user_id);
  568. $usermustbemodified = 0;
  569. if ($tmpobj->office_phone != $this->phone_pro) {
  570. $tmpobj->office_phone = $this->phone_pro;
  571. $usermustbemodified++;
  572. }
  573. if ($tmpobj->office_fax != $this->fax) {
  574. $tmpobj->office_fax = $this->fax;
  575. $usermustbemodified++;
  576. }
  577. if ($tmpobj->address != $this->address) {
  578. $tmpobj->address = $this->address;
  579. $usermustbemodified++;
  580. }
  581. if ($tmpobj->town != $this->town) {
  582. $tmpobj->town = $this->town;
  583. $usermustbemodified++;
  584. }
  585. if ($tmpobj->zip != $this->zip) {
  586. $tmpobj->zip = $this->zip;
  587. $usermustbemodified++;
  588. }
  589. if ($tmpobj->zip != $this->zip) {
  590. $tmpobj->state_id = $this->state_id;
  591. $usermustbemodified++;
  592. }
  593. if ($tmpobj->country_id != $this->country_id) {
  594. $tmpobj->country_id = $this->country_id;
  595. $usermustbemodified++;
  596. }
  597. if ($tmpobj->email != $this->email) {
  598. $tmpobj->email = $this->email;
  599. $usermustbemodified++;
  600. }
  601. if (!empty(array_diff($tmpobj->socialnetworks, $this->socialnetworks))) {
  602. $tmpobj->socialnetworks = $this->socialnetworks;
  603. $usermustbemodified++;
  604. }
  605. // if ($tmpobj->skype != $this->skype) {
  606. // $tmpobj->skype = $this->skype;
  607. // $usermustbemodified++;
  608. // }
  609. // if ($tmpobj->twitter != $this->twitter) {
  610. // $tmpobj->twitter = $this->twitter;
  611. // $usermustbemodified++;
  612. // }
  613. // if ($tmpobj->facebook != $this->facebook) {
  614. // $tmpobj->facebook = $this->facebook;
  615. // $usermustbemodified++;
  616. // }
  617. // if ($tmpobj->linkedin != $this->linkedin) {
  618. // $tmpobj->linkedin = $this->linkedin;
  619. // $usermustbemodified++;
  620. // }
  621. if ($usermustbemodified) {
  622. $result = $tmpobj->update($user, 0, 1, 1, 1);
  623. if ($result < 0) {
  624. $error++;
  625. }
  626. }
  627. }
  628. if (!$error && !$notrigger) {
  629. // Call trigger
  630. $result = $this->call_trigger('CONTACT_MODIFY', $user);
  631. if ($result < 0) {
  632. $error++;
  633. }
  634. // End call triggers
  635. }
  636. if (!$error) {
  637. $this->db->commit();
  638. return 1;
  639. } else {
  640. dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
  641. $this->db->rollback();
  642. return -$error;
  643. }
  644. } else {
  645. $this->error = $this->db->lasterror().' sql='.$sql;
  646. $this->db->rollback();
  647. return -1;
  648. }
  649. }
  650. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  651. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  652. /**
  653. * Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
  654. *
  655. * @param array $info Info string loaded by _load_ldap_info
  656. * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
  657. * 1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb)
  658. * 2=Return key only (uid=qqq)
  659. * @return string DN
  660. */
  661. public function _load_ldap_dn($info, $mode = 0)
  662. {
  663. // phpcs:enable
  664. global $conf;
  665. $dn = '';
  666. if ($mode == 0) {
  667. $dn = $conf->global->LDAP_KEY_CONTACTS."=".$info[$conf->global->LDAP_KEY_CONTACTS].",".$conf->global->LDAP_CONTACT_DN;
  668. } elseif ($mode == 1) {
  669. $dn = $conf->global->LDAP_CONTACT_DN;
  670. } elseif ($mode == 2) {
  671. $dn = $conf->global->LDAP_KEY_CONTACTS."=".$info[$conf->global->LDAP_KEY_CONTACTS];
  672. }
  673. return $dn;
  674. }
  675. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  676. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  677. /**
  678. * Initialise tableau info (tableau des attributs LDAP)
  679. *
  680. * @return array Tableau info des attributs
  681. */
  682. public function _load_ldap_info()
  683. {
  684. // phpcs:enable
  685. global $conf, $langs;
  686. $info = array();
  687. // Object classes
  688. $info["objectclass"] = explode(',', $conf->global->LDAP_CONTACT_OBJECT_CLASS);
  689. $this->fullname = $this->getFullName($langs);
  690. // Fields
  691. if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) {
  692. $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname;
  693. }
  694. if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) {
  695. $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname;
  696. }
  697. if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) {
  698. $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname;
  699. }
  700. if ($this->poste) {
  701. $info["title"] = $this->poste;
  702. }
  703. if ($this->socid > 0) {
  704. $soc = new Societe($this->db);
  705. $soc->fetch($this->socid);
  706. $info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name;
  707. if ($soc->client == 1) {
  708. $info["businessCategory"] = "Customers";
  709. }
  710. if ($soc->client == 2) {
  711. $info["businessCategory"] = "Prospects";
  712. }
  713. if ($soc->fournisseur == 1) {
  714. $info["businessCategory"] = "Suppliers";
  715. }
  716. }
  717. if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) {
  718. $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address;
  719. }
  720. if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) {
  721. $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip;
  722. }
  723. if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) {
  724. $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town;
  725. }
  726. if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) {
  727. $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code;
  728. }
  729. if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) {
  730. $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro;
  731. }
  732. if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) {
  733. $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso;
  734. }
  735. if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) {
  736. $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile;
  737. }
  738. if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) {
  739. $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax;
  740. }
  741. if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) {
  742. $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype;
  743. }
  744. if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) {
  745. $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2);
  746. }
  747. if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) {
  748. $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email;
  749. }
  750. if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
  751. $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
  752. $info['uidnumber'] = $this->id;
  753. $info['phpgwTz'] = 0;
  754. $info['phpgwMailType'] = 'INTERNET';
  755. $info['phpgwMailHomeType'] = 'INTERNET';
  756. $info["phpgwContactTypeId"] = 'n';
  757. $info["phpgwContactCatId"] = 0;
  758. $info["phpgwContactAccess"] = "public";
  759. if (dol_strlen($this->egroupware_id) == 0) {
  760. $this->egroupware_id = 1;
  761. }
  762. $info["phpgwContactOwner"] = $this->egroupware_id;
  763. if ($this->email) {
  764. $info["rfc822Mailbox"] = $this->email;
  765. }
  766. if ($this->phone_mobile) {
  767. $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
  768. }
  769. }
  770. return $info;
  771. }
  772. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  773. /**
  774. * Update field alert birthday
  775. *
  776. * @param int $id Id of contact
  777. * @param User $user User asking to change alert or birthday
  778. * @param int $notrigger 0=no, 1=yes
  779. * @return int <0 if KO, >=0 if OK
  780. */
  781. public function update_perso($id, $user = null, $notrigger = 0)
  782. {
  783. // phpcs:enable
  784. $error = 0;
  785. $result = false;
  786. $this->db->begin();
  787. // Mis a jour contact
  788. $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET";
  789. $sql .= " birthday = ".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
  790. $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
  791. if ($user) {
  792. $sql .= ", fk_user_modif = ".((int) $user->id);
  793. }
  794. $sql .= " WHERE rowid = ".((int) $id);
  795. dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG);
  796. $resql = $this->db->query($sql);
  797. if (!$resql) {
  798. $error++;
  799. $this->error = $this->db->lasterror();
  800. }
  801. if ($user) {
  802. // Update birthday alert
  803. if (!empty($this->birthday_alert)) {
  804. //check existing
  805. $sql_check = "SELECT rowid FROM " . MAIN_DB_PREFIX . "user_alert WHERE type = 1 AND fk_contact = " . ((int) $id) . " AND fk_user = " . ((int) $user->id);
  806. $result_check = $this->db->query($sql_check);
  807. if (!$result_check || ($this->db->num_rows($result_check) < 1)) {
  808. //insert
  809. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_alert(type, fk_contact, fk_user) ";
  810. $sql .= "VALUES (1," . ((int) $id) . "," . ((int) $user->id) . ")";
  811. $result = $this->db->query($sql);
  812. if (!$result) {
  813. $error++;
  814. $this->error = $this->db->lasterror();
  815. }
  816. } else {
  817. $result = true;
  818. }
  819. } else {
  820. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_alert ";
  821. $sql .= "WHERE type=1 AND fk_contact=" . ((int) $id) . " AND fk_user=" . ((int) $user->id);
  822. $result = $this->db->query($sql);
  823. if (!$result) {
  824. $error++;
  825. $this->error = $this->db->lasterror();
  826. }
  827. }
  828. }
  829. if (!$error && !$notrigger) {
  830. // Call trigger
  831. $result = $this->call_trigger('CONTACT_MODIFY', $user);
  832. if ($result < 0) {
  833. $error++;
  834. }
  835. // End call triggers
  836. }
  837. if (!$error) {
  838. $this->db->commit();
  839. return 1;
  840. } else {
  841. dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
  842. $this->db->rollback();
  843. return -$error;
  844. }
  845. }
  846. /**
  847. * Load object contact.
  848. *
  849. * @param int $id Id of contact
  850. * @param User $user Load also alerts of this user (subscribing to alerts) that want alerts about this contact
  851. * @param string $ref_ext External reference, not given by Dolibarr
  852. * @param string $email Email
  853. * @param int $loadalsoroles Load also roles. Try to always 0 here and load roles with a separate call of fetchRoles().
  854. * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
  855. */
  856. public function fetch($id, $user = null, $ref_ext = '', $email = '', $loadalsoroles = 0)
  857. {
  858. global $langs;
  859. dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG);
  860. if (empty($id) && empty($ref_ext) && empty($email)) {
  861. $this->error = 'BadParameter';
  862. return -1;
  863. }
  864. $langs->loadLangs(array("dict", "companies"));
  865. $sql = "SELECT c.rowid, c.entity, c.fk_soc, c.ref_ext, c.civility as civility_code, c.lastname, c.firstname,";
  866. $sql .= " c.address, c.statut, c.zip, c.town,";
  867. $sql .= " c.fk_pays as country_id,";
  868. $sql .= " c.fk_departement as state_id,";
  869. $sql .= " c.birthday,";
  870. $sql .= " c.poste, c.phone, c.phone_perso, c.phone_mobile, c.fax, c.email,";
  871. $sql .= " c.socialnetworks,";
  872. $sql .= " c.photo,";
  873. $sql .= " c.priv, c.note_private, c.note_public, c.default_lang, c.canvas,";
  874. $sql .= " c.fk_prospectcontactlevel, c.fk_stcommcontact, st.libelle as stcomm, st.picto as stcomm_picto,";
  875. $sql .= " c.import_key,";
  876. $sql .= " c.datec as date_creation, c.tms as date_modification,";
  877. $sql .= " co.label as country, co.code as country_code,";
  878. $sql .= " d.nom as state, d.code_departement as state_code,";
  879. $sql .= " u.rowid as user_id, u.login as user_login,";
  880. $sql .= " s.nom as socname, s.address as socaddress, s.zip as soccp, s.town as soccity, s.default_lang as socdefault_lang";
  881. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c";
  882. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON c.fk_pays = co.rowid";
  883. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON c.fk_departement = d.rowid";
  884. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople";
  885. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
  886. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcommcontact as st ON c.fk_stcommcontact = st.id';
  887. if ($id) {
  888. $sql .= " WHERE c.rowid = ".((int) $id);
  889. } else {
  890. $sql .= " WHERE c.entity IN (".getEntity($this->element).")";
  891. if ($ref_ext) {
  892. $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
  893. }
  894. if ($email) {
  895. $sql .= " AND c.email = '".$this->db->escape($email)."'";
  896. }
  897. }
  898. $resql = $this->db->query($sql);
  899. if ($resql) {
  900. $num = $this->db->num_rows($resql);
  901. if ($num > 1) {
  902. $this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.';
  903. dol_syslog($this->error, LOG_ERR);
  904. return 2;
  905. } elseif ($num) { // $num = 1
  906. $obj = $this->db->fetch_object($resql);
  907. $this->id = $obj->rowid;
  908. $this->entity = $obj->entity;
  909. $this->ref = $obj->rowid;
  910. $this->ref_ext = $obj->ref_ext;
  911. $this->civility_code = $obj->civility_code;
  912. $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : '';
  913. $this->lastname = $obj->lastname;
  914. $this->firstname = $obj->firstname;
  915. $this->address = $obj->address;
  916. $this->zip = $obj->zip;
  917. $this->town = $obj->town;
  918. $this->date_creation = $this->db->jdate($obj->date_creation);
  919. $this->date_modification = $this->db->jdate($obj->date_modification);
  920. $this->state_id = $obj->state_id;
  921. $this->state_code = $obj->state_code;
  922. $this->state = $obj->state;
  923. $this->country_id = $obj->country_id;
  924. $this->country_code = $obj->country_id ? $obj->country_code : '';
  925. $this->country = $obj->country_id ? ($langs->trans('Country'.$obj->country_code) != 'Country'.$obj->country_code ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
  926. $this->fk_soc = $obj->fk_soc; // Both fk_soc and socid are used
  927. $this->socid = $obj->fk_soc; // Both fk_soc and socid are used
  928. $this->socname = $obj->socname;
  929. $this->poste = $obj->poste;
  930. $this->statut = $obj->statut;
  931. $this->fk_prospectlevel = $obj->fk_prospectcontactlevel;
  932. $transcode = $langs->trans('StatusProspect'.$obj->fk_stcommcontact);
  933. $libelle = ($transcode != 'StatusProspect'.$obj->fk_stcommcontact ? $transcode : $obj->stcomm);
  934. $this->stcomm_id = $obj->fk_stcommcontact; // id statut commercial
  935. $this->statut_commercial = $libelle; // libelle statut commercial
  936. $this->stcomm_picto = $obj->stcomm_picto; // Picto statut commercial
  937. $this->phone_pro = trim($obj->phone);
  938. $this->fax = trim($obj->fax);
  939. $this->phone_perso = trim($obj->phone_perso);
  940. $this->phone_mobile = trim($obj->phone_mobile);
  941. $this->email = $obj->email;
  942. $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
  943. $this->photo = $obj->photo;
  944. $this->priv = $obj->priv;
  945. $this->mail = $obj->email;
  946. $this->birthday = $this->db->jdate($obj->birthday);
  947. $this->note = $obj->note_private; // deprecated
  948. $this->note_private = $obj->note_private;
  949. $this->note_public = $obj->note_public;
  950. $this->default_lang = $obj->default_lang;
  951. $this->user_id = $obj->user_id;
  952. $this->user_login = $obj->user_login;
  953. $this->canvas = $obj->canvas;
  954. $this->import_key = $obj->import_key;
  955. // Define gender according to civility
  956. $this->setGenderFromCivility();
  957. // Search Dolibarr user linked to this contact
  958. $sql = "SELECT u.rowid ";
  959. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  960. $sql .= " WHERE u.fk_socpeople = ".((int) $this->id);
  961. $resql = $this->db->query($sql);
  962. if ($resql) {
  963. if ($this->db->num_rows($resql)) {
  964. $uobj = $this->db->fetch_object($resql);
  965. $this->user_id = $uobj->rowid;
  966. }
  967. $this->db->free($resql);
  968. } else {
  969. $this->error = $this->db->error();
  970. return -1;
  971. }
  972. // Retrieve all extrafield
  973. // fetch optionals attributes and labels
  974. $this->fetch_optionals();
  975. // Load also alerts of this user
  976. if ($user) {
  977. $sql = "SELECT fk_user";
  978. $sql .= " FROM ".MAIN_DB_PREFIX."user_alert";
  979. $sql .= " WHERE fk_user = ".((int) $user->id)." AND fk_contact = ".((int) $id);
  980. $resql = $this->db->query($sql);
  981. if ($resql) {
  982. if ($this->db->num_rows($resql)) {
  983. $obj = $this->db->fetch_object($resql);
  984. $this->birthday_alert = 1;
  985. }
  986. $this->db->free($resql);
  987. } else {
  988. $this->error = $this->db->error();
  989. return -1;
  990. }
  991. }
  992. // Load also roles of this address
  993. if ($loadalsoroles) {
  994. $resultRole = $this->fetchRoles();
  995. if ($resultRole < 0) {
  996. return $resultRole;
  997. }
  998. }
  999. return 1;
  1000. } else {
  1001. $this->error = $langs->trans("RecordNotFound");
  1002. return 0;
  1003. }
  1004. } else {
  1005. $this->error = $this->db->error();
  1006. return -1;
  1007. }
  1008. }
  1009. /**
  1010. * Set the property "gender" of this class, based on the property "civility_id"
  1011. * or use property "civility_code" as fallback, when "civility_id" is not available.
  1012. *
  1013. * @return void
  1014. */
  1015. public function setGenderFromCivility()
  1016. {
  1017. unset($this->gender);
  1018. if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR'))) {
  1019. $this->gender = 'man';
  1020. } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) {
  1021. $this->gender = 'woman';
  1022. }
  1023. }
  1024. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1025. /**
  1026. * Load number of elements the contact is used as a link for
  1027. * ref_facturation
  1028. * ref_contrat
  1029. * ref_commande (for order and/or shipments)
  1030. * ref_propale
  1031. *
  1032. * @return int <0 if KO, >=0 if OK
  1033. */
  1034. public function load_ref_elements()
  1035. {
  1036. // phpcs:enable
  1037. // Compte les elements pour lesquels il est contact
  1038. $sql = "SELECT tc.element, count(ec.rowid) as nb";
  1039. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc";
  1040. $sql .= " WHERE ec.fk_c_type_contact = tc.rowid";
  1041. $sql .= " AND fk_socpeople = ".((int) $this->id);
  1042. $sql .= " AND tc.source = 'external'";
  1043. $sql .= " GROUP BY tc.element";
  1044. dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG);
  1045. $resql = $this->db->query($sql);
  1046. if ($resql) {
  1047. while ($obj = $this->db->fetch_object($resql)) {
  1048. if ($obj->nb) {
  1049. if ($obj->element == 'facture') {
  1050. $this->ref_facturation = $obj->nb;
  1051. } elseif ($obj->element == 'contrat') {
  1052. $this->ref_contrat = $obj->nb;
  1053. } elseif ($obj->element == 'commande') {
  1054. $this->ref_commande = $obj->nb;
  1055. } elseif ($obj->element == 'propal') {
  1056. $this->ref_propal = $obj->nb;
  1057. }
  1058. }
  1059. }
  1060. $this->db->free($resql);
  1061. return 0;
  1062. } else {
  1063. $this->error = $this->db->lasterror();
  1064. return -1;
  1065. }
  1066. }
  1067. /**
  1068. * Delete a contact from database
  1069. * // TODO Add $user as first param
  1070. *
  1071. * @param int $notrigger Disable all trigger
  1072. * @return int <0 if KO, >0 if OK
  1073. */
  1074. public function delete($notrigger = 0)
  1075. {
  1076. global $conf, $langs, $user;
  1077. $error = 0;
  1078. $this->db->begin();
  1079. if (!$error && !$notrigger) {
  1080. // Call trigger
  1081. $result = $this->call_trigger('CONTACT_DELETE', $user);
  1082. if ($result < 0) {
  1083. $error++;
  1084. }
  1085. // End call triggers
  1086. }
  1087. if (!$error) {
  1088. // Get all rowid of element_contact linked to a type that is link to llx_socpeople
  1089. $sql = "SELECT ec.rowid";
  1090. $sql .= " FROM ".MAIN_DB_PREFIX."element_contact ec,";
  1091. $sql .= " ".MAIN_DB_PREFIX."c_type_contact tc";
  1092. $sql .= " WHERE ec.fk_socpeople=".((int) $this->id);
  1093. $sql .= " AND ec.fk_c_type_contact=tc.rowid";
  1094. $sql .= " AND tc.source='external'";
  1095. dol_syslog(__METHOD__, LOG_DEBUG);
  1096. $resql = $this->db->query($sql);
  1097. if ($resql) {
  1098. $num = $this->db->num_rows($resql);
  1099. $i = 0;
  1100. while ($i < $num && !$error) {
  1101. $obj = $this->db->fetch_object($resql);
  1102. $sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  1103. $sqldel .= " WHERE rowid = ".((int) $obj->rowid);
  1104. dol_syslog(__METHOD__, LOG_DEBUG);
  1105. $result = $this->db->query($sqldel);
  1106. if (!$result) {
  1107. $error++;
  1108. $this->error = $this->db->error().' sql='.$sqldel;
  1109. }
  1110. $i++;
  1111. }
  1112. } else {
  1113. $error++;
  1114. $this->error = $this->db->error().' sql='.$sql;
  1115. }
  1116. }
  1117. if (!$error) {
  1118. // Remove Roles
  1119. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".((int) $this->id);
  1120. dol_syslog(__METHOD__, LOG_DEBUG);
  1121. $resql = $this->db->query($sql);
  1122. if (!$resql) {
  1123. $error++;
  1124. $this->error .= $this->db->lasterror();
  1125. $errorflag = -1;
  1126. }
  1127. }
  1128. if (!$error) {
  1129. // Remove Roles
  1130. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".((int) $this->id);
  1131. dol_syslog(__METHOD__, LOG_DEBUG);
  1132. $resql = $this->db->query($sql);
  1133. if (!$resql) {
  1134. $error++;
  1135. $this->error .= $this->db->lasterror();
  1136. $errorflag = -1;
  1137. }
  1138. }
  1139. if (!$error) {
  1140. // Remove category
  1141. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".((int) $this->id);
  1142. dol_syslog(__METHOD__, LOG_DEBUG);
  1143. $resql = $this->db->query($sql);
  1144. if (!$resql) {
  1145. $error++;
  1146. $this->error .= $this->db->lasterror();
  1147. $errorflag = -1;
  1148. }
  1149. }
  1150. if (!$error) {
  1151. $sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople";
  1152. $sql .= " WHERE rowid = ".((int) $this->id);
  1153. dol_syslog(__METHOD__, LOG_DEBUG);
  1154. $result = $this->db->query($sql);
  1155. if (!$result) {
  1156. $error++;
  1157. $this->error = $this->db->error().' sql='.$sql;
  1158. }
  1159. }
  1160. // Removed extrafields
  1161. if (!$error) {
  1162. // For avoid conflicts if trigger used
  1163. $result = $this->deleteExtraFields();
  1164. if ($result < 0) {
  1165. $error++;
  1166. }
  1167. }
  1168. if (!$error) {
  1169. $this->db->commit();
  1170. return 1;
  1171. } else {
  1172. $this->db->rollback();
  1173. dol_syslog("Error ".$this->error, LOG_ERR);
  1174. return -1;
  1175. }
  1176. }
  1177. /**
  1178. * Charge les informations sur le contact, depuis la base
  1179. *
  1180. * @param int $id Id du contact a charger
  1181. * @return void
  1182. */
  1183. public function info($id)
  1184. {
  1185. $sql = "SELECT c.rowid, c.datec as datec, c.fk_user_creat,";
  1186. $sql .= " c.tms as tms, c.fk_user_modif";
  1187. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c";
  1188. $sql .= " WHERE c.rowid = ".((int) $id);
  1189. $resql = $this->db->query($sql);
  1190. if ($resql) {
  1191. if ($this->db->num_rows($resql)) {
  1192. $obj = $this->db->fetch_object($resql);
  1193. $this->id = $obj->rowid;
  1194. if ($obj->fk_user_creat) {
  1195. $cuser = new User($this->db);
  1196. $cuser->fetch($obj->fk_user_creat);
  1197. $this->user_creation = $cuser;
  1198. }
  1199. if ($obj->fk_user_modif) {
  1200. $muser = new User($this->db);
  1201. $muser->fetch($obj->fk_user_modif);
  1202. $this->user_modification = $muser;
  1203. }
  1204. $this->date_creation = $this->db->jdate($obj->datec);
  1205. $this->date_modification = $this->db->jdate($obj->tms);
  1206. }
  1207. $this->db->free($resql);
  1208. } else {
  1209. print $this->db->error();
  1210. }
  1211. }
  1212. /**
  1213. * Return number of mass Emailing received by this contacts with its email
  1214. *
  1215. * @return int Number of EMailings
  1216. */
  1217. public function getNbOfEMailings()
  1218. {
  1219. $sql = "SELECT count(mc.email) as nb";
  1220. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
  1221. $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
  1222. $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
  1223. $resql = $this->db->query($sql);
  1224. if ($resql) {
  1225. $obj = $this->db->fetch_object($resql);
  1226. $nb = $obj->nb;
  1227. $this->db->free($resql);
  1228. return $nb;
  1229. } else {
  1230. $this->error = $this->db->error();
  1231. return -1;
  1232. }
  1233. }
  1234. /**
  1235. * Return name of contact with link (and eventually picto)
  1236. * Use $this->id, $this->lastname, $this->firstname, this->civility_id
  1237. *
  1238. * @param int $withpicto Include picto with link (1=picto + name, 2=picto only, -1=photo+name, -2=photo only)
  1239. * @param string $option Where the link point to
  1240. * @param int $maxlen Max length of
  1241. * @param string $moreparam Add more param into URL
  1242. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1243. * @param int $notooltip 1=Disable tooltip
  1244. * @param string $morecss Add more css on link
  1245. * @return string String with URL
  1246. */
  1247. public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $moreparam = '', $save_lastsearch_value = -1, $notooltip = 0, $morecss = '')
  1248. {
  1249. global $conf, $langs, $hookmanager;
  1250. $result = ''; $label = '';
  1251. if (!empty($this->photo) && class_exists('Form')) {
  1252. $label .= '<div class="photointooltip floatright">';
  1253. $label .= Form::showphoto('contact', $this, 0, 40, 0, 'photoref', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
  1254. $label .= '</div>';
  1255. //$label .= '<div style="clear: both;"></div>';
  1256. }
  1257. $label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contact").'</u>';
  1258. $label .= ' '.$this->getLibStatut(4);
  1259. $label .= '<br><b>'.$langs->trans("Name").':</b> '.$this->getFullName($langs);
  1260. //if ($this->civility_id) $label.= '<br><b>' . $langs->trans("Civility") . ':</b> '.$this->civility_id; // TODO Translate cibilty_id code
  1261. if (!empty($this->poste)) {
  1262. $label .= '<br><b>'.$langs->trans("Poste").':</b> '.$this->poste;
  1263. }
  1264. $label .= '<br><b>'.$langs->trans("EMail").':</b> '.$this->email;
  1265. $phonelist = array();
  1266. $country_code = empty($this->country_code) ? '': $this->country_code;
  1267. if ($this->phone_pro) {
  1268. $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', '&nbsp;', 'phone');
  1269. }
  1270. if ($this->phone_mobile) {
  1271. $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', '&nbsp;', 'mobile');
  1272. }
  1273. if ($this->phone_perso) {
  1274. $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', '&nbsp;', 'phone');
  1275. }
  1276. $label .= '<br><b>'.$langs->trans("Phone").':</b> '.implode('&nbsp;', $phonelist);
  1277. $label .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs);
  1278. $url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id;
  1279. if ($option !== 'nolink') {
  1280. // Add param to save lastsearch_values or not
  1281. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1282. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1283. $add_save_lastsearch_values = 1;
  1284. }
  1285. if ($add_save_lastsearch_values) {
  1286. $url .= '&save_lastsearch_values=1';
  1287. }
  1288. }
  1289. $url .= $moreparam;
  1290. $linkclose = "";
  1291. if (empty($notooltip)) {
  1292. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1293. $label = $langs->trans("ShowContact");
  1294. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1295. }
  1296. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1297. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1298. }
  1299. $linkstart = '<a href="'.$url.'"';
  1300. $linkstart .= $linkclose.'>';
  1301. $linkend = '</a>';
  1302. if ($option == 'xxx') {
  1303. $linkstart = '<a href="'.DOL_URL_ROOT.'/contact/card.php?id='.$this->id.$moreparam.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  1304. $linkend = '</a>';
  1305. }
  1306. $result .= $linkstart;
  1307. if ($withpicto) {
  1308. if ($withpicto < 0) {
  1309. $result .= '<!-- picto photo user --><span class="nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.Form::showphoto('contact', $this, 0, 0, 0, 'userphoto'.($withpicto == -3 ? 'small' : ''), 'mini', 0, 1).'</span>';
  1310. } else {
  1311. $result .= img_object(($notooltip ? '' : $label), ( $this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1312. }
  1313. }
  1314. if ($withpicto != 2 && $withpicto != -2) {
  1315. $result .= '<span class="valigmiddle">'.($maxlen ? dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs)).'</span>';
  1316. }
  1317. $result .= $linkend;
  1318. global $action;
  1319. $hookmanager->initHooks(array('contactdao'));
  1320. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1321. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1322. if ($reshook > 0) {
  1323. $result = $hookmanager->resPrint;
  1324. } else {
  1325. $result .= $hookmanager->resPrint;
  1326. }
  1327. return $result;
  1328. }
  1329. /**
  1330. * Return civility label of contact
  1331. *
  1332. * @return string Translated name of civility
  1333. */
  1334. public function getCivilityLabel()
  1335. {
  1336. global $langs;
  1337. $code = ($this->civility_code ? $this->civility_code : (!empty($this->civility_id) ? $this->civility : (!empty($this->civilite) ? $this->civilite : '')));
  1338. if (empty($code)) {
  1339. return '';
  1340. }
  1341. $langs->load("dict");
  1342. return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
  1343. }
  1344. /**
  1345. * Return label of contact status
  1346. *
  1347. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1348. * @return string Label of contact status
  1349. */
  1350. public function getLibStatut($mode)
  1351. {
  1352. return $this->LibStatut($this->statut, $mode);
  1353. }
  1354. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1355. /**
  1356. * Renvoi le libelle d'un statut donne
  1357. *
  1358. * @param int $status Id statut
  1359. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1360. * @return string Libelle
  1361. */
  1362. public function LibStatut($status, $mode)
  1363. {
  1364. // phpcs:enable
  1365. global $langs;
  1366. $labelStatus = array(
  1367. 0 => 'ActivityCeased',
  1368. 1 => 'InActivity',
  1369. 4 => 'InActivity',
  1370. 5 => 'ActivityCeased',
  1371. );
  1372. $labelStatusShort = array(
  1373. 0 => 'ActivityCeased',
  1374. 1 => 'InActivity',
  1375. 4 => 'InActivity',
  1376. 5 => 'ActivityCeased',
  1377. );
  1378. $statusType = 'status4';
  1379. if ($status == 0 || $status == 5) {
  1380. $statusType = 'status5';
  1381. }
  1382. $label = $langs->transnoentitiesnoconv($labelStatus[$status]);
  1383. $labelshort = $langs->transnoentitiesnoconv($labelStatusShort[$status]);
  1384. return dolGetStatus($label, $labelshort, '', $statusType, $mode);
  1385. }
  1386. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1387. /**
  1388. * Return translated label of Public or Private
  1389. *
  1390. * @param int $status Type (0 = public, 1 = private)
  1391. * @return string Label translated
  1392. */
  1393. public function LibPubPriv($status)
  1394. {
  1395. // phpcs:enable
  1396. global $langs;
  1397. if ($status == '1') {
  1398. return $langs->trans('ContactPrivate');
  1399. } else {
  1400. return $langs->trans('ContactPublic');
  1401. }
  1402. }
  1403. /**
  1404. * Initialise an instance with random values.
  1405. * Used to build previews or test instances.
  1406. * id must be 0 if object instance is a specimen.
  1407. *
  1408. * @return int >0 if ok
  1409. */
  1410. public function initAsSpecimen()
  1411. {
  1412. // Get first id of existing company and save it into $socid
  1413. $socid = 0;
  1414. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe ORDER BY rowid LIMIT 1";
  1415. $resql = $this->db->query($sql);
  1416. if ($resql) {
  1417. $obj = $this->db->fetch_object($resql);
  1418. if ($obj) {
  1419. $socid = $obj->rowid;
  1420. }
  1421. }
  1422. // Initialise parameters
  1423. $this->id = 0;
  1424. $this->entity = 1;
  1425. $this->specimen = 1;
  1426. $this->lastname = 'DOLIBARR';
  1427. $this->firstname = 'SPECIMEN';
  1428. $this->address = '21 jump street';
  1429. $this->zip = '99999';
  1430. $this->town = 'MyTown';
  1431. $this->country_id = 1;
  1432. $this->country_code = 'FR';
  1433. $this->country = 'France';
  1434. $this->email = 'specimen@specimen.com';
  1435. $this->socialnetworks = array(
  1436. 'skype' => 'tom.hanson',
  1437. );
  1438. $this->phone_pro = '0909090901';
  1439. $this->phone_perso = '0909090902';
  1440. $this->phone_mobile = '0909090903';
  1441. $this->fax = '0909090909';
  1442. $this->note_public = 'This is a comment (public)';
  1443. $this->note_private = 'This is a comment (private)';
  1444. $this->socid = $socid;
  1445. $this->statut = 1;
  1446. return 1;
  1447. }
  1448. /**
  1449. * Change status of a user
  1450. *
  1451. * @param int $status Status to set
  1452. * @return int <0 if KO, 0 if nothing is done, >0 if OK
  1453. */
  1454. public function setstatus($status)
  1455. {
  1456. global $conf, $langs, $user;
  1457. $error = 0;
  1458. // Check parameters
  1459. if ($this->statut == $status) {
  1460. return 0;
  1461. } else {
  1462. $this->statut = $status;
  1463. }
  1464. $this->db->begin();
  1465. // Desactive utilisateur
  1466. $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople";
  1467. $sql .= " SET statut = ".((int) $this->statut);
  1468. $sql .= " WHERE rowid = ".((int) $this->id);
  1469. $result = $this->db->query($sql);
  1470. dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
  1471. if ($result) {
  1472. // Call trigger
  1473. $result = $this->call_trigger('CONTACT_ENABLEDISABLE', $user);
  1474. if ($result < 0) {
  1475. $error++;
  1476. }
  1477. // End call triggers
  1478. }
  1479. if ($error) {
  1480. $this->db->rollback();
  1481. return -$error;
  1482. } else {
  1483. $this->db->commit();
  1484. return 1;
  1485. }
  1486. }
  1487. /**
  1488. * Sets object to supplied categories.
  1489. *
  1490. * Deletes object from existing categories not supplied.
  1491. * Adds it to non existing supplied categories.
  1492. * Existing categories are left untouch.
  1493. *
  1494. * @param int[]|int $categories Category or categories IDs
  1495. * @return int <0 if KO, >0 if OK
  1496. */
  1497. public function setCategories($categories)
  1498. {
  1499. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1500. return parent::setCategoriesCommon($categories, Categorie::TYPE_CONTACT);
  1501. }
  1502. /**
  1503. * Function used to replace a thirdparty id with another one.
  1504. *
  1505. * @param DoliDB $db Database handler
  1506. * @param int $origin_id Old thirdparty id
  1507. * @param int $dest_id New thirdparty id
  1508. * @return bool
  1509. */
  1510. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1511. {
  1512. $tables = array(
  1513. 'socpeople', 'societe_contacts'
  1514. );
  1515. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1516. }
  1517. /**
  1518. * Fetch roles (default contact of some companies) for the current contact.
  1519. * This load the array ->roles.
  1520. *
  1521. * @return int <0 if KO, Nb of roles found if OK
  1522. * @see updateRoles()
  1523. */
  1524. public function fetchRoles()
  1525. {
  1526. global $langs;
  1527. $error = 0;
  1528. $num = 0;
  1529. $sql = "SELECT tc.rowid, tc.element, tc.source, tc.code, tc.libelle as label, sc.rowid as contactroleid, sc.fk_soc as socid";
  1530. $sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc, ".MAIN_DB_PREFIX."c_type_contact as tc";
  1531. $sql .= " WHERE tc.rowid = sc.fk_c_type_contact";
  1532. $sql .= " AND tc.source = 'external' AND tc.active=1";
  1533. $sql .= " AND sc.fk_socpeople = ".((int) $this->id);
  1534. $sql .= " AND sc.entity IN (".getEntity('societe').')';
  1535. $resql = $this->db->query($sql);
  1536. if ($resql) {
  1537. $this->roles = array();
  1538. $num = $this->db->num_rows($resql);
  1539. if ($num > 0) {
  1540. while ($obj = $this->db->fetch_object($resql)) {
  1541. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  1542. $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
  1543. $this->roles[$obj->contactroleid] = array('id'=>$obj->rowid, 'socid'=>$obj->socid, 'element'=>$obj->element, 'source'=>$obj->source, 'code'=>$obj->code, 'label'=>$libelle_element.' - '.($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->label));
  1544. }
  1545. }
  1546. } else {
  1547. $error++;
  1548. $this->error = $this->db->lasterror();
  1549. $this->errors[] = $this->db->lasterror();
  1550. }
  1551. if (empty($error)) {
  1552. return $num;
  1553. } else {
  1554. return $error * -1;
  1555. }
  1556. }
  1557. /**
  1558. * Get Contact roles for a thirdparty
  1559. *
  1560. * @param string $element Element type
  1561. * @return array|int Array of contact roles or -1
  1562. * @throws Exception
  1563. */
  1564. public function getContactRoles($element = '')
  1565. {
  1566. $tab = array();
  1567. if ($element == 'action') {
  1568. $element = 'agenda';
  1569. }
  1570. $sql = "SELECT sc.fk_socpeople as id, sc.fk_c_type_contact";
  1571. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  1572. $sql .= ", ".MAIN_DB_PREFIX."societe_contacts sc";
  1573. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."socpeople sp";
  1574. $sql .= " ON sc.fk_socpeople = sp.rowid AND sp.statut = 1";
  1575. $sql .= " WHERE sc.fk_soc =".((int) $this->socid);
  1576. $sql .= " AND sc.fk_c_type_contact=tc.rowid";
  1577. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  1578. $sql .= " AND tc.active = 1";
  1579. dol_syslog(__METHOD__, LOG_DEBUG);
  1580. $resql = $this->db->query($sql);
  1581. if ($resql) {
  1582. $num = $this->db->num_rows($resql);
  1583. $i = 0;
  1584. while ($i < $num) {
  1585. $obj = $this->db->fetch_object($resql);
  1586. $tab[] = array('fk_socpeople'=>$obj->id, 'type_contact'=>$obj->fk_c_type_contact);
  1587. $i++;
  1588. }
  1589. return $tab;
  1590. } else {
  1591. $this->error = $this->db->error();
  1592. dol_print_error($this->db);
  1593. return -1;
  1594. }
  1595. }
  1596. /**
  1597. * Updates all roles (default contact for companies) according to values inside the ->roles array.
  1598. * This is called by update of contact.
  1599. *
  1600. * @return float|int
  1601. * @see fetchRoles()
  1602. */
  1603. public function updateRoles()
  1604. {
  1605. global $conf;
  1606. $error = 0;
  1607. if (!isset($this->roles)) {
  1608. return; // Avoid to loose roles when property not set
  1609. }
  1610. $this->db->begin();
  1611. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople=".((int) $this->id)." AND entity IN (".getEntity("contact").")";
  1612. $result = $this->db->query($sql);
  1613. if (!$result) {
  1614. $this->errors[] = $this->db->lasterror().' sql='.$sql;
  1615. $error++;
  1616. } else {
  1617. if (count($this->roles) > 0) {
  1618. foreach ($this->roles as $keyRoles => $valRoles) {
  1619. $idrole = 0;
  1620. if (is_array($valRoles)) {
  1621. $idrole = $valRoles['id'];
  1622. } else {
  1623. $idrole = $valRoles;
  1624. }
  1625. $socid = 0;
  1626. if (is_array($valRoles)) {
  1627. $socid = $valRoles['socid'];
  1628. } else {
  1629. $socid = $this->socid;
  1630. }
  1631. if ($socid > 0) {
  1632. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_contacts";
  1633. $sql .= " (entity,";
  1634. $sql .= "date_creation,";
  1635. $sql .= "fk_soc,";
  1636. $sql .= "fk_c_type_contact,";
  1637. $sql .= "fk_socpeople) ";
  1638. $sql .= " VALUES (".$conf->entity.",";
  1639. $sql .= "'".$this->db->idate(dol_now())."',";
  1640. $sql .= $socid.", ";
  1641. $sql .= $idrole." , ";
  1642. $sql .= $this->id;
  1643. $sql .= ")";
  1644. $result = $this->db->query($sql);
  1645. if (!$result) {
  1646. $this->errors[] = $this->db->lasterror().' sql='.$sql;
  1647. $error++;
  1648. }
  1649. }
  1650. }
  1651. }
  1652. }
  1653. if (empty($error)) {
  1654. $this->db->commit();
  1655. return 1;
  1656. } else {
  1657. $this->error = implode(' ', $this->errors);
  1658. $this->db->rollback();
  1659. return $error * -1;
  1660. }
  1661. }
  1662. /**
  1663. * Load array of prospect status
  1664. *
  1665. * @param int $active 1=Active only, 0=Not active only, -1=All
  1666. * @return int <0 if KO, >0 if OK
  1667. */
  1668. public function loadCacheOfProspStatus($active = 1)
  1669. {
  1670. global $langs;
  1671. $sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcommcontact";
  1672. if ($active >= 0) {
  1673. $sql .= " WHERE active = ".((int) $active);
  1674. }
  1675. $resql = $this->db->query($sql);
  1676. $num = $this->db->num_rows($resql);
  1677. $i = 0;
  1678. while ($i < $num) {
  1679. $obj = $this->db->fetch_object($resql);
  1680. $this->cacheprospectstatus[$obj->id] = array('id' => $obj->id, 'code' => $obj->code, 'label' => ($langs->trans("ST_".strtoupper($obj->code)) == "ST_".strtoupper($obj->code)) ? $obj->label : $langs->trans("ST_".strtoupper($obj->code)), 'picto' => $obj->picto);
  1681. $i++;
  1682. }
  1683. return 1;
  1684. }
  1685. /**
  1686. * Return prostect level
  1687. *
  1688. * @return string Libelle
  1689. */
  1690. public function getLibProspLevel()
  1691. {
  1692. return $this->libProspLevel($this->fk_prospectlevel);
  1693. }
  1694. /**
  1695. * Return label of prospect level
  1696. *
  1697. * @param int $fk_prospectlevel Prospect level
  1698. * @return string label of level
  1699. */
  1700. public function libProspLevel($fk_prospectlevel)
  1701. {
  1702. global $langs;
  1703. $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
  1704. // If lib not found in language file, we get label from cache/databse
  1705. if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
  1706. $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
  1707. }
  1708. return $lib;
  1709. }
  1710. /**
  1711. * Set prospect level
  1712. *
  1713. * @param User $user Utilisateur qui definie la remise
  1714. * @return int <0 if KO, >0 if OK
  1715. * @deprecated Use update function instead
  1716. */
  1717. public function setProspectLevel(User $user)
  1718. {
  1719. return $this->update($this->id, $user);
  1720. }
  1721. /**
  1722. * Return status of prospect
  1723. *
  1724. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
  1725. * @param string $label Label to use for status for added status
  1726. * @return string Libelle
  1727. */
  1728. public function getLibProspCommStatut($mode = 0, $label = '')
  1729. {
  1730. return $this->libProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
  1731. }
  1732. /**
  1733. * Return label of a given status
  1734. *
  1735. * @param int|string $statut Id or code for prospection status
  1736. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  1737. * @param string $label Label to use for status for added status
  1738. * @param string $picto Name of image file to show ('filenew', ...)
  1739. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  1740. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  1741. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  1742. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  1743. * @return string Libelle du statut
  1744. */
  1745. public function libProspCommStatut($statut, $mode = 0, $label = '', $picto = '')
  1746. {
  1747. global $langs;
  1748. $langs->load('customers');
  1749. if ($mode == 2) {
  1750. if ($statut == '-1' || $statut == 'ST_NO') {
  1751. return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
  1752. } elseif ($statut == '0' || $statut == 'ST_NEVER') {
  1753. return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
  1754. } elseif ($statut == '1' || $statut == 'ST_TODO') {
  1755. return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
  1756. } elseif ($statut == '2' || $statut == 'ST_PEND') {
  1757. return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
  1758. } elseif ($statut == '3' || $statut == 'ST_DONE') {
  1759. return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
  1760. } else {
  1761. return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
  1762. }
  1763. }
  1764. if ($mode == 3) {
  1765. if ($statut == '-1' || $statut == 'ST_NO') {
  1766. return img_action($langs->trans("StatusProspect-1"), -1, $picto);
  1767. } elseif ($statut == '0' || $statut == 'ST_NEVER') {
  1768. return img_action($langs->trans("StatusProspect0"), 0, $picto);
  1769. } elseif ($statut == '1' || $statut == 'ST_TODO') {
  1770. return img_action($langs->trans("StatusProspect1"), 1, $picto);
  1771. } elseif ($statut == '2' || $statut == 'ST_PEND') {
  1772. return img_action($langs->trans("StatusProspect2"), 2, $picto);
  1773. } elseif ($statut == '3' || $statut == 'ST_DONE') {
  1774. return img_action($langs->trans("StatusProspect3"), 3, $picto);
  1775. } else {
  1776. return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto);
  1777. }
  1778. }
  1779. if ($mode == 4) {
  1780. if ($statut == '-1' || $statut == 'ST_NO') {
  1781. return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
  1782. } elseif ($statut == '0' || $statut == 'ST_NEVER') {
  1783. return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
  1784. } elseif ($statut == '1' || $statut == 'ST_TODO') {
  1785. return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
  1786. } elseif ($statut == '2' || $statut == 'ST_PEND') {
  1787. return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
  1788. } elseif ($statut == '3' || $statut == 'ST_DONE') {
  1789. return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
  1790. } else {
  1791. return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
  1792. }
  1793. }
  1794. return "Error, mode/status not found";
  1795. }
  1796. /**
  1797. * Set "blacklist" mailing status
  1798. *
  1799. * @param int $no_email 1=Do not send mailing, 0=Ok to recieve mailling
  1800. * @return int <0 if KO, >0 if OK
  1801. */
  1802. public function setNoEmail($no_email)
  1803. {
  1804. $error = 0;
  1805. // Update mass emailing flag into table mailing_unsubscribe
  1806. if ($this->email) {
  1807. $this->db->begin();
  1808. if ($no_email) {
  1809. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'";
  1810. $resql = $this->db->query($sql);
  1811. if ($resql) {
  1812. $obj = $this->db->fetch_object($resql);
  1813. $noemail = $obj->nb;
  1814. if (empty($noemail)) {
  1815. $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".getEntity('mailing', 0).", '".$this->db->idate(dol_now())."')";
  1816. $resql = $this->db->query($sql);
  1817. if (!$resql) {
  1818. $error++;
  1819. $this->error = $this->db->lasterror();
  1820. $this->errors[] = $this->error;
  1821. }
  1822. }
  1823. } else {
  1824. $error++;
  1825. $this->error = $this->db->lasterror();
  1826. $this->errors[] = $this->error;
  1827. }
  1828. } else {
  1829. $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
  1830. $resql = $this->db->query($sql);
  1831. if (!$resql) {
  1832. $error++;
  1833. $this->error = $this->db->lasterror();
  1834. $this->errors[] = $this->error;
  1835. }
  1836. }
  1837. if (empty($error)) {
  1838. $this->no_email = $no_email;
  1839. $this->db->commit();
  1840. return 1;
  1841. } else {
  1842. $this->db->rollback();
  1843. return $error * -1;
  1844. }
  1845. }
  1846. return 0;
  1847. }
  1848. /**
  1849. * get "blacklist" mailing status
  1850. * set no_email attribut to 1 or 0
  1851. *
  1852. * @return int <0 if KO, >0 if OK
  1853. */
  1854. public function getNoEmail()
  1855. {
  1856. if ($this->email) {
  1857. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
  1858. $resql = $this->db->query($sql);
  1859. if ($resql) {
  1860. $obj = $this->db->fetch_object($resql);
  1861. $this->no_email = $obj->nb;
  1862. return 1;
  1863. } else {
  1864. $this->error = $this->db->lasterror();
  1865. $this->errors[] = $this->error;
  1866. return -1;
  1867. }
  1868. }
  1869. return 0;
  1870. }
  1871. }