contact.class.php 69 KB

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