contact.class.php 68 KB

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