commonobject.class.php 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582
  1. <?php
  2. /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@capnetworks.com>
  4. * Copyright (C) 2010-2013 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  7. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  8. * Copyright (C) 2011-2014 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  10. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  11. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2015 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
  13. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  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 <http://www.gnu.org/licenses/>.
  27. */
  28. /**
  29. * \file htdocs/core/class/commonobject.class.php
  30. * \ingroup core
  31. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  32. */
  33. /**
  34. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  35. */
  36. abstract class CommonObject
  37. {
  38. /**
  39. * @var DoliDb Database handler (result of a new DoliDB)
  40. */
  41. public $db;
  42. /**
  43. * @var int The object identifier
  44. */
  45. public $id;
  46. /**
  47. * @var string Error string
  48. * @deprecated Use instead the array of error strings
  49. * @see errors
  50. */
  51. public $error;
  52. /**
  53. * @var string[] Array of error strings
  54. */
  55. public $errors=array();
  56. /**
  57. * @var string Key value used to track if data is coming from import wizard
  58. */
  59. public $import_key;
  60. /**
  61. * @var mixed Contains data to manage extrafields
  62. */
  63. public $array_options=array();
  64. /**
  65. * @var int[] Array of linked objects ids. Loaded by ->fetchObjectLinked
  66. */
  67. public $linkedObjectsIds;
  68. /**
  69. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  70. */
  71. public $linkedObjects;
  72. /**
  73. * @var string Column name of the ref field.
  74. */
  75. protected $table_ref_field = '';
  76. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  77. /**
  78. * @var string[] Can be used to pass information when only object is provided to method
  79. */
  80. public $context=array();
  81. /**
  82. * @var string Contains canvas name if record is an alternative canvas record
  83. */
  84. public $canvas;
  85. /**
  86. * @var Project The related project
  87. * @see fetch_projet()
  88. */
  89. public $project;
  90. /**
  91. * @var int The related project ID
  92. * @see setProject(), project
  93. */
  94. public $fk_project;
  95. /**
  96. * @deprecated
  97. * @see project
  98. */
  99. public $projet;
  100. /**
  101. * @var Contact a related contact
  102. * @see fetch_contact()
  103. */
  104. public $contact;
  105. /**
  106. * @var int The related contact ID
  107. * @see fetch_contact()
  108. */
  109. public $contact_id;
  110. /**
  111. * @var Societe A related thirdparty
  112. * @see fetch_thirdparty()
  113. */
  114. public $thirdparty;
  115. /**
  116. * @var User A related user
  117. * @see fetch_user()
  118. */
  119. public $user;
  120. /**
  121. * @var CommonObject An originating object?
  122. * @see fetch_origin()
  123. */
  124. public $origin;
  125. /**
  126. * @var int The originating object?
  127. * @see fetch_origin(), origin
  128. */
  129. public $origin_id;
  130. /**
  131. * @var string The object's reference
  132. */
  133. public $ref;
  134. /**
  135. * @var string The object's previous reference
  136. */
  137. public $ref_previous;
  138. /**
  139. * @var string The object's next reference
  140. */
  141. public $ref_next;
  142. /**
  143. * @var string An external reference for the object
  144. */
  145. public $ref_ext;
  146. /**
  147. * @var string
  148. */
  149. public $element;
  150. /**
  151. * @var string
  152. */
  153. public $table_element;
  154. /**
  155. * @var
  156. */
  157. public $table_element_line;
  158. /**
  159. * @var int The object's status
  160. * @see setStatut()
  161. */
  162. public $statut;
  163. /**
  164. * @var string
  165. * @see getFullAddress()
  166. */
  167. public $country;
  168. /**
  169. * @var int
  170. * @see getFullAddress(), country
  171. */
  172. public $country_id;
  173. /**
  174. * @var string
  175. * @see getFullAddress(), isInEEC(), country
  176. */
  177. public $country_code;
  178. /**
  179. * @var int
  180. * @see fetch_barcode()
  181. */
  182. public $barcode_type;
  183. /**
  184. * @var string
  185. * @see fetch_barcode(), barcode_type
  186. */
  187. public $barcode_type_code;
  188. /**
  189. * @var string
  190. * @see fetch_barcode(), barcode_type
  191. */
  192. public $barcode_type_label;
  193. /**
  194. * @var string
  195. * @see fetch_barcode(), barcode_type
  196. */
  197. public $barcode_type_coder;
  198. /**
  199. * @var int Payment method ID (cheque, cash, ...)
  200. * @see setPaymentMethods()
  201. */
  202. public $mode_reglement_id;
  203. /**
  204. * @var int Payment terms ID
  205. * @see setPaymentTerms()
  206. */
  207. public $cond_reglement_id;
  208. /**
  209. * @var int Payment terms ID
  210. * @deprecated Kept for compatibility
  211. * @see cond_reglement_id;
  212. */
  213. public $cond_reglement;
  214. /**
  215. * @var int Delivery address ID
  216. * @see setDeliveryAddress()
  217. */
  218. public $fk_delivery_address;
  219. /**
  220. * @var int Shipping method ID
  221. * @see setShippingMethod()
  222. */
  223. public $shipping_method_id;
  224. /**
  225. * @var string
  226. * @see SetDocModel()
  227. */
  228. public $modelpdf;
  229. /**
  230. * @var int Bank account ID
  231. * @see SetBankAccount()
  232. */
  233. public $fk_account;
  234. /**
  235. * @var string Public note
  236. * @see update_note()
  237. */
  238. public $note_public;
  239. /**
  240. * @var string Private note
  241. * @see update_note()
  242. */
  243. public $note_private;
  244. /**
  245. * @deprecated
  246. * @see note_public
  247. */
  248. public $note;
  249. /**
  250. * @var float Total amount before taxes
  251. * @see update_price()
  252. */
  253. public $total_ht;
  254. /**
  255. * @var float Total VAT amount
  256. * @see update_price()
  257. */
  258. public $total_tva;
  259. /**
  260. * @var float Total local tax 1 amount
  261. * @see update_price()
  262. */
  263. public $total_localtax1;
  264. /**
  265. * @var float Total local tax 2 amount
  266. * @see update_price()
  267. */
  268. public $total_localtax2;
  269. /**
  270. * @var float Total amount with taxes
  271. * @see update_price()
  272. */
  273. public $total_ttc;
  274. /**
  275. * @var CommonObjectLine[]
  276. */
  277. public $lines;
  278. /**
  279. * @var int
  280. * @see setIncoterms()
  281. */
  282. public $fk_incoterms;
  283. /**
  284. * @var string
  285. * @see SetIncoterms()
  286. */
  287. public $libelle_incoterms;
  288. /**
  289. * @var string
  290. * @see display_incoterms()
  291. */
  292. public $location_incoterms;
  293. public $name;
  294. public $lastname;
  295. public $firstname;
  296. public $civility_id;
  297. // No constructor as it is an abstract class
  298. /**
  299. * Check an object id/ref exists
  300. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  301. *
  302. * @param string $element String of element ('product', 'facture', ...)
  303. * @param int $id Id of object
  304. * @param string $ref Ref of object to check
  305. * @param string $ref_ext Ref ext of object to check
  306. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  307. */
  308. static function isExistingObject($element, $id, $ref='', $ref_ext='')
  309. {
  310. global $db,$conf;
  311. $sql = "SELECT rowid, ref, ref_ext";
  312. $sql.= " FROM ".MAIN_DB_PREFIX.$element;
  313. $sql.= " WHERE entity IN (".getEntity($element, true).")" ;
  314. if ($id > 0) $sql.= " AND rowid = ".$db->escape($id);
  315. else if ($ref) $sql.= " AND ref = '".$db->escape($ref)."'";
  316. else if ($ref_ext) $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'";
  317. else {
  318. $error='ErrorWrongParameters';
  319. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  320. return -1;
  321. }
  322. if ($ref || $ref_ext) $sql.= " AND entity = ".$conf->entity;
  323. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  324. $resql = $db->query($sql);
  325. if ($resql)
  326. {
  327. $num=$db->num_rows($resql);
  328. if ($num > 0) return 1;
  329. else return 0;
  330. }
  331. return -1;
  332. }
  333. /**
  334. * Method to output saved errors
  335. *
  336. * @return string String with errors
  337. */
  338. function errorsToString()
  339. {
  340. return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
  341. }
  342. /**
  343. * Return full name (civility+' '+name+' '+lastname)
  344. *
  345. * @param Translate $langs Language object for translation of civility
  346. * @param int $option 0=No option, 1=Add civility
  347. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
  348. * @param int $maxlen Maximum length
  349. * @return string String with full name
  350. */
  351. function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
  352. {
  353. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  354. $lastname=$this->lastname;
  355. $firstname=$this->firstname;
  356. if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:'')));
  357. $ret='';
  358. if ($option && $this->civility_id)
  359. {
  360. if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
  361. else $ret.=$this->civility_id.' ';
  362. }
  363. $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder);
  364. return dol_trunc($ret,$maxlen);
  365. }
  366. /**
  367. * Return full address of contact
  368. *
  369. * @param int $withcountry 1=Add country into address string
  370. * @param string $sep Separator to use to build string
  371. * @return string Full address string
  372. */
  373. function getFullAddress($withcountry=0,$sep="\n")
  374. {
  375. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
  376. {
  377. require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
  378. $tmparray=getCountry($this->country_id,'all');
  379. $this->country_code=$tmparray['code'];
  380. $this->country =$tmparray['label'];
  381. }
  382. return dol_format_address($this, $withcountry, $sep);
  383. }
  384. /**
  385. * Return full address of contact
  386. *
  387. * @param string $htmlkey HTML id to make banner content unique
  388. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  389. * @return string Full address string
  390. */
  391. function getBannerAddress($htmlkey, $object)
  392. {
  393. global $conf, $langs;
  394. $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  395. $contactid=0;
  396. $thirdpartyid=0;
  397. if ($this->element == 'societe')
  398. {
  399. $thirdpartyid=$this->id;
  400. }
  401. if ($this->element == 'contact')
  402. {
  403. $contactid=$this->id;
  404. $thirdpartyid=$object->fk_soc;
  405. }
  406. if ($this->element == 'user')
  407. {
  408. $contactid=$this->contact_id;
  409. $thirdpartyid=$object->fk_soc;
  410. }
  411. $out='<!-- BEGIN part to show address block -->';
  412. $outdone=0;
  413. $coords = $this->getFullAddress(1,', ');
  414. if ($coords)
  415. {
  416. if (! empty($conf->use_javascript_ajax))
  417. {
  418. $namecoords = $this->getFullName($langs,1).'<br>'.$coords;
  419. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  420. $out.='<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  421. $out.=img_picto($langs->trans("Address"), 'object_address.png');
  422. $out.='</a> ';
  423. }
  424. $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1); $outdone++;
  425. $outdone++;
  426. }
  427. if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
  428. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
  429. {
  430. $out.=($outdone?' - ':'').$this->state;
  431. $outdone++;
  432. }
  433. if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'<br>':'');
  434. if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  435. $out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
  436. }
  437. if (! empty($this->phone_pro)) {
  438. $out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
  439. }
  440. if (! empty($this->phone_mobile)) {
  441. $out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhoneMobile")); $outdone++;
  442. }
  443. if (! empty($this->phone_perso)) {
  444. $out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
  445. }
  446. if (! empty($this->fax)) {
  447. $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
  448. }
  449. if (! empty($this->office_phone)) {
  450. $out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
  451. }
  452. if (! empty($this->user_mobile)) {
  453. $out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhoneMobile")); $outdone++;
  454. }
  455. if (! empty($this->office_fax)) {
  456. $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
  457. }
  458. $out.='<div style="clear: both;"></div>';
  459. $outdone=0;
  460. if (! empty($this->email))
  461. {
  462. $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
  463. $outdone++;
  464. }
  465. if (! empty($this->url))
  466. {
  467. $out.=dol_print_url($this->url,'',0,1);
  468. $outdone++;
  469. }
  470. if (! empty($conf->skype->enabled))
  471. {
  472. $out.='<div style="clear: both;"></div>';
  473. if ($this->skype) $out.=dol_print_skype($this->skype,$this->id,$object->id,'AC_SKYPE');
  474. $outdone++;
  475. }
  476. $out.='<!-- END Part to show address block -->';
  477. return $out;
  478. }
  479. /**
  480. * Add a link between element $this->element and a contact
  481. *
  482. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  483. * @param int $type_contact Type of contact (code or id). Must be if or code found into table llx_c_type_contact. For example: SALESREPFOLL
  484. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  485. * @param int $notrigger Disable all triggers
  486. * @return int <0 if KO, >0 if OK
  487. */
  488. function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
  489. {
  490. global $user,$langs;
  491. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source");
  492. // Check parameters
  493. if ($fk_socpeople <= 0)
  494. {
  495. $langs->load("errors");
  496. $this->error=$langs->trans("ErrorWrongValueForParameterX","1");
  497. dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
  498. return -1;
  499. }
  500. if (! $type_contact)
  501. {
  502. $langs->load("errors");
  503. $this->error=$langs->trans("ErrorWrongValueForParameterX","2");
  504. dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
  505. return -2;
  506. }
  507. $id_type_contact=0;
  508. if (is_numeric($type_contact))
  509. {
  510. $id_type_contact=$type_contact;
  511. }
  512. else
  513. {
  514. // On recherche id type_contact
  515. $sql = "SELECT tc.rowid";
  516. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  517. $sql.= " WHERE tc.element='".$this->element."'";
  518. $sql.= " AND tc.source='".$source."'";
  519. $sql.= " AND tc.code='".$type_contact."' AND tc.active=1";
  520. //print $sql;
  521. $resql=$this->db->query($sql);
  522. if ($resql)
  523. {
  524. $obj = $this->db->fetch_object($resql);
  525. $id_type_contact=$obj->rowid;
  526. }
  527. }
  528. $datecreate = dol_now();
  529. $this->db->begin();
  530. // Insertion dans la base
  531. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  532. $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  533. $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
  534. $sql.= "'".$this->db->idate($datecreate)."'";
  535. $sql.= ", 4, '". $id_type_contact . "' ";
  536. $sql.= ")";
  537. dol_syslog(get_class($this)."::add_contact", LOG_DEBUG);
  538. $resql=$this->db->query($sql);
  539. if ($resql)
  540. {
  541. if (! $notrigger)
  542. {
  543. $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  544. if ($result < 0)
  545. {
  546. $this->db->rollback();
  547. return -1;
  548. }
  549. }
  550. $this->db->commit();
  551. return 1;
  552. }
  553. else
  554. {
  555. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  556. {
  557. $this->error=$this->db->errno();
  558. $this->db->rollback();
  559. return -2;
  560. }
  561. else
  562. {
  563. $this->error=$this->db->error();
  564. $this->db->rollback();
  565. return -1;
  566. }
  567. }
  568. }
  569. /**
  570. * Copy contact from one element to current
  571. *
  572. * @param CommonObject $objFrom Source element
  573. * @param string $source Nature of contact ('internal' or 'external')
  574. * @return int >0 if OK, <0 if KO
  575. */
  576. function copy_linked_contact($objFrom, $source='internal')
  577. {
  578. $contacts = $objFrom->liste_contact(-1, $source);
  579. foreach($contacts as $contact)
  580. {
  581. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
  582. {
  583. $this->error=$this->db->lasterror();
  584. return -1;
  585. }
  586. }
  587. return 1;
  588. }
  589. /**
  590. * Update a link to contact line
  591. *
  592. * @param int $rowid Id of line contact-element
  593. * @param int $statut New status of link
  594. * @param int $type_contact_id Id of contact type (not modified if 0)
  595. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  596. * @return int <0 if KO, >= 0 if OK
  597. */
  598. function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
  599. {
  600. // Insertion dans la base
  601. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  602. $sql.= " statut = ".$statut;
  603. if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
  604. if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
  605. $sql.= " where rowid = ".$rowid;
  606. $resql=$this->db->query($sql);
  607. if ($resql)
  608. {
  609. return 0;
  610. }
  611. else
  612. {
  613. $this->error=$this->db->lasterror();
  614. return -1;
  615. }
  616. }
  617. /**
  618. * Delete a link to contact line
  619. *
  620. * @param int $rowid Id of contact link line to delete
  621. * @param int $notrigger Disable all triggers
  622. * @return int >0 if OK, <0 if KO
  623. */
  624. function delete_contact($rowid, $notrigger=0)
  625. {
  626. global $user;
  627. $this->db->begin();
  628. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  629. $sql.= " WHERE rowid =".$rowid;
  630. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  631. if ($this->db->query($sql))
  632. {
  633. if (! $notrigger)
  634. {
  635. $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  636. if ($result < 0) { $this->db->rollback(); return -1; }
  637. }
  638. $this->db->commit();
  639. return 1;
  640. }
  641. else
  642. {
  643. $this->error=$this->db->lasterror();
  644. $this->db->rollback();
  645. return -1;
  646. }
  647. }
  648. /**
  649. * Delete all links between an object $this and all its contacts
  650. *
  651. * @param string $source '' or 'internal' or 'external'
  652. * @param string $code Type of contact (code or id)
  653. * @return int >0 if OK, <0 if KO
  654. */
  655. function delete_linked_contact($source='',$code='')
  656. {
  657. $temp = array();
  658. $typeContact = $this->liste_type_contact($source,'',0,0,$code);
  659. foreach($typeContact as $key => $value)
  660. {
  661. array_push($temp,$key);
  662. }
  663. $listId = implode(",", $temp);
  664. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  665. $sql.= " WHERE element_id = ".$this->id;
  666. if ($listId)
  667. $sql.= " AND fk_c_type_contact IN (".$listId.")";
  668. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  669. if ($this->db->query($sql))
  670. {
  671. return 1;
  672. }
  673. else
  674. {
  675. $this->error=$this->db->lasterror();
  676. return -1;
  677. }
  678. }
  679. /**
  680. * Get array of all contacts for an object
  681. *
  682. * @param int $statut Status of links to get (-1=all)
  683. * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
  684. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  685. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  686. * @return array Array of contacts
  687. */
  688. function liste_contact($statut=-1,$source='external',$list=0,$code='')
  689. {
  690. global $langs;
  691. $tab=array();
  692. $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
  693. if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact";
  694. if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
  695. $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  696. $sql.= ", tc.source, tc.element, tc.code, tc.libelle";
  697. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  698. $sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
  699. if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  700. if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  701. $sql.= " WHERE ec.element_id =".$this->id;
  702. $sql.= " AND ec.fk_c_type_contact=tc.rowid";
  703. $sql.= " AND tc.element='".$this->element."'";
  704. if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
  705. if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
  706. if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
  707. $sql.= " AND tc.active=1";
  708. if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
  709. $sql.=" ORDER BY t.lastname ASC";
  710. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  711. $resql=$this->db->query($sql);
  712. if ($resql)
  713. {
  714. $num=$this->db->num_rows($resql);
  715. $i=0;
  716. while ($i < $num)
  717. {
  718. $obj = $this->db->fetch_object($resql);
  719. if (! $list)
  720. {
  721. $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  722. $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
  723. $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
  724. 'nom'=>$obj->lastname, // For backward compatibility
  725. 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'statuscontact'=>$obj->statuscontact,
  726. 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
  727. }
  728. else
  729. {
  730. $tab[$i]=$obj->id;
  731. }
  732. $i++;
  733. }
  734. return $tab;
  735. }
  736. else
  737. {
  738. $this->error=$this->db->lasterror();
  739. dol_print_error($this->db);
  740. return -1;
  741. }
  742. }
  743. /**
  744. * Update status of a contact linked to object
  745. *
  746. * @param int $rowid Id of link between object and contact
  747. * @return int <0 if KO, >=0 if OK
  748. */
  749. function swapContactStatus($rowid)
  750. {
  751. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  752. $sql.= " tc.code, tc.libelle";
  753. //$sql.= ", s.fk_soc";
  754. $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  755. //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe
  756. $sql.= " WHERE ec.rowid =".$rowid;
  757. $sql.= " AND ec.fk_c_type_contact=tc.rowid";
  758. $sql.= " AND tc.element = '".$this->element."'";
  759. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  760. $resql=$this->db->query($sql);
  761. if ($resql)
  762. {
  763. $obj = $this->db->fetch_object($resql);
  764. $newstatut = ($obj->statut == 4) ? 5 : 4;
  765. $result = $this->update_contact($rowid, $newstatut);
  766. $this->db->free($resql);
  767. return $result;
  768. }
  769. else
  770. {
  771. $this->error=$this->db->error();
  772. dol_print_error($this->db);
  773. return -1;
  774. }
  775. }
  776. /**
  777. * Return array with list of possible values for type of contacts
  778. *
  779. * @param string $source 'internal', 'external' or 'all'
  780. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  781. * @param int $option 0=Return array id->label, 1=Return array code->label
  782. * @param int $activeonly 0=all status of contact, 1=only the active
  783. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  784. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  785. */
  786. function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
  787. {
  788. global $langs;
  789. if (empty($order)) $order='position';
  790. if ($order == 'position') $order.=',code';
  791. $tab = array();
  792. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle";
  793. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  794. $sql.= " WHERE tc.element='".$this->element."'";
  795. if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
  796. if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$source."'";
  797. if (! empty($code)) $sql.= " AND tc.code='".$code."'";
  798. $sql.= $this->db->order($order,'ASC');
  799. //print "sql=".$sql;
  800. $resql=$this->db->query($sql);
  801. if ($resql)
  802. {
  803. $num=$this->db->num_rows($resql);
  804. $i=0;
  805. while ($i < $num)
  806. {
  807. $obj = $this->db->fetch_object($resql);
  808. $transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
  809. $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
  810. if (empty($option)) $tab[$obj->rowid]=$libelle_type;
  811. else $tab[$obj->code]=$libelle_type;
  812. $i++;
  813. }
  814. return $tab;
  815. }
  816. else
  817. {
  818. $this->error=$this->db->lasterror();
  819. //dol_print_error($this->db);
  820. return null;
  821. }
  822. }
  823. /**
  824. * Return id of contacts for a source and a contact code.
  825. * Example: contact client de facturation ('external', 'BILLING')
  826. * Example: contact client de livraison ('external', 'SHIPPING')
  827. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  828. *
  829. * @param string $source 'external' or 'internal'
  830. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  831. * @param int $status limited to a certain status
  832. * @return array List of id for such contacts
  833. */
  834. function getIdContact($source,$code,$status=0)
  835. {
  836. global $conf;
  837. $result=array();
  838. $i=0;
  839. $sql = "SELECT ec.fk_socpeople";
  840. $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  841. if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
  842. if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
  843. $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  844. $sql.= " WHERE ec.element_id = ".$this->id;
  845. $sql.= " AND ec.fk_socpeople = c.rowid";
  846. if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")";
  847. if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe', 1).")";
  848. $sql.= " AND ec.fk_c_type_contact = tc.rowid";
  849. $sql.= " AND tc.element = '".$this->element."'";
  850. $sql.= " AND tc.source = '".$source."'";
  851. $sql.= " AND tc.code = '".$code."'";
  852. $sql.= " AND tc.active = 1";
  853. if ($status) $sql.= " AND ec.statut = ".$status;
  854. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  855. $resql=$this->db->query($sql);
  856. if ($resql)
  857. {
  858. while ($obj = $this->db->fetch_object($resql))
  859. {
  860. $result[$i]=$obj->fk_socpeople;
  861. $i++;
  862. }
  863. }
  864. else
  865. {
  866. $this->error=$this->db->error();
  867. return null;
  868. }
  869. return $result;
  870. }
  871. /**
  872. * Load object contact with id=$this->contactid into $this->contact
  873. *
  874. * @param int $contactid Id du contact. Use this->contactid if empty.
  875. * @return int <0 if KO, >0 if OK
  876. */
  877. function fetch_contact($contactid=null)
  878. {
  879. if (empty($contactid)) $contactid=$this->contactid;
  880. if (empty($contactid)) return 0;
  881. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  882. $contact = new Contact($this->db);
  883. $result=$contact->fetch($contactid);
  884. $this->contact = $contact;
  885. return $result;
  886. }
  887. /**
  888. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  889. *
  890. * @param int $force_thirdparty_id Force thirdparty id
  891. * @return int <0 if KO, >0 if OK
  892. */
  893. function fetch_thirdparty($force_thirdparty_id=0)
  894. {
  895. global $conf;
  896. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
  897. return 0;
  898. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  899. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  900. if ($force_thirdparty_id)
  901. $idtofetch = $force_thirdparty_id;
  902. if ($idtofetch) {
  903. $thirdparty = new Societe($this->db);
  904. $result = $thirdparty->fetch($idtofetch);
  905. $this->thirdparty = $thirdparty;
  906. // Use first price level if level not defined for third party
  907. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  908. $this->thirdparty->price_level = 1;
  909. }
  910. return $result;
  911. } else
  912. return -1;
  913. }
  914. /**
  915. * Looks for an object with ref matching the wildcard provided
  916. * It does only work when $this->table_ref_field is set
  917. *
  918. * @param string $ref Wildcard
  919. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  920. */
  921. public function fetchOneLike($ref)
  922. {
  923. if (!$this->table_ref_field) {
  924. return 0;
  925. }
  926. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  927. $query = $this->db->query($sql);
  928. if (!$this->db->num_rows($query)) {
  929. return 0;
  930. }
  931. $result = $this->db->fetch_object($query);
  932. return $this->fetch($result->rowid);
  933. }
  934. /**
  935. * Load data for barcode into properties ->barcode_type*
  936. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  937. * if it is not defined, ->element must be defined to know default barcode type.
  938. *
  939. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  940. */
  941. function fetch_barcode()
  942. {
  943. global $conf;
  944. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  945. $idtype=$this->barcode_type;
  946. if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
  947. {
  948. if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  949. else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  950. else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  951. }
  952. if ($idtype > 0)
  953. {
  954. if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded
  955. {
  956. $sql = "SELECT rowid, code, libelle as label, coder";
  957. $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  958. $sql.= " WHERE rowid = ".$idtype;
  959. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  960. $resql = $this->db->query($sql);
  961. if ($resql)
  962. {
  963. $obj = $this->db->fetch_object($resql);
  964. $this->barcode_type = $obj->rowid;
  965. $this->barcode_type_code = $obj->code;
  966. $this->barcode_type_label = $obj->label;
  967. $this->barcode_type_coder = $obj->coder;
  968. return 1;
  969. }
  970. else
  971. {
  972. dol_print_error($this->db);
  973. return -1;
  974. }
  975. }
  976. }
  977. return 0;
  978. }
  979. /**
  980. * Charge le projet d'id $this->fk_project dans this->projet
  981. *
  982. * @return int <0 if KO, >=0 if OK
  983. */
  984. function fetch_projet()
  985. {
  986. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  987. if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility
  988. if (empty($this->fk_project)) return 0;
  989. $project = new Project($this->db);
  990. $result = $project->fetch($this->fk_project);
  991. $this->projet = $project; // deprecated
  992. $this->project = $project;
  993. return $result;
  994. }
  995. /**
  996. * Charge le user d'id userid dans this->user
  997. *
  998. * @param int $userid Id du contact
  999. * @return int <0 if KO, >0 if OK
  1000. */
  1001. function fetch_user($userid)
  1002. {
  1003. $user = new User($this->db);
  1004. $result=$user->fetch($userid);
  1005. $this->user = $user;
  1006. return $result;
  1007. }
  1008. /**
  1009. * Read linked origin object
  1010. *
  1011. * @return void
  1012. */
  1013. function fetch_origin()
  1014. {
  1015. // TODO uniformise code
  1016. if ($this->origin == 'shipping') $this->origin = 'expedition';
  1017. if ($this->origin == 'delivery') $this->origin = 'livraison';
  1018. $origin = $this->origin;
  1019. $classname = ucfirst($origin);
  1020. $this->$origin = new $classname($this->db);
  1021. $this->$origin->fetch($this->origin_id);
  1022. }
  1023. /**
  1024. * Load object from specific field
  1025. *
  1026. * @param string $table Table element or element line
  1027. * @param string $field Field selected
  1028. * @param string $key Import key
  1029. * @return int <0 if KO, >0 if OK
  1030. */
  1031. function fetchObjectFrom($table,$field,$key)
  1032. {
  1033. global $conf;
  1034. $result=false;
  1035. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1036. $sql.= " WHERE ".$field." = '".$key."'";
  1037. $sql.= " AND entity = ".$conf->entity;
  1038. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1039. $resql = $this->db->query($sql);
  1040. if ($resql)
  1041. {
  1042. $row = $this->db->fetch_row($resql);
  1043. $result = $this->fetch($row[0]);
  1044. }
  1045. return $result;
  1046. }
  1047. /**
  1048. * Getter generic. Load value from a specific field
  1049. *
  1050. * @param string $table Table of element or element line
  1051. * @param int $id Element id
  1052. * @param string $field Field selected
  1053. * @return int <0 if KO, >0 if OK
  1054. */
  1055. function getValueFrom($table, $id, $field)
  1056. {
  1057. $result=false;
  1058. if (!empty($id) && !empty($field) && !empty($table)) {
  1059. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1060. $sql.= " WHERE rowid = ".$id;
  1061. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1062. $resql = $this->db->query($sql);
  1063. if ($resql)
  1064. {
  1065. $row = $this->db->fetch_row($resql);
  1066. $result = $row[0];
  1067. }
  1068. }
  1069. return $result;
  1070. }
  1071. /**
  1072. * Setter generic. Update a specific field into database
  1073. *
  1074. * @param string $field Field to update
  1075. * @param mixed $value New value
  1076. * @param string $table To force other table element or element line (should not be used)
  1077. * @param int $id To force other object id (should not be used)
  1078. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1079. * @param string $id_field To force rowid field name. 'rowid' is used it not defined
  1080. * @param User|string $user Update last update fields also if user object provided
  1081. * @return int <0 if KO, >0 if OK
  1082. */
  1083. function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $user='')
  1084. {
  1085. if (empty($table)) $table=$this->table_element;
  1086. if (empty($id)) $id=$this->id;
  1087. if (empty($format)) $format='text';
  1088. if (empty($id_field)) $id_field='rowid';
  1089. $this->db->begin();
  1090. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1091. if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'";
  1092. else if ($format == 'date') $sql.= $field." = '".$this->db->idate($value)."'";
  1093. if (is_object($user)) $sql.=", fk_user_modif = ".$user->id;
  1094. $sql.= " WHERE ".$id_field." = ".$id;
  1095. dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
  1096. $resql = $this->db->query($sql);
  1097. if ($resql)
  1098. {
  1099. $this->db->commit();
  1100. return 1;
  1101. }
  1102. else
  1103. {
  1104. $this->error=$this->db->lasterror();
  1105. $this->db->rollback();
  1106. return -1;
  1107. }
  1108. }
  1109. /**
  1110. * Load properties id_previous and id_next
  1111. *
  1112. * @param string $filter Optional filter
  1113. * @param int $fieldid Name of field to use for the select MAX and MIN
  1114. * @param int $nodbprefix Do not include DB prefix to forge table name
  1115. * @return int <0 if KO, >0 if OK
  1116. */
  1117. function load_previous_next_ref($filter,$fieldid,$nodbprefix=0)
  1118. {
  1119. global $user;
  1120. if (! $this->table_element)
  1121. {
  1122. dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1123. return -1;
  1124. }
  1125. // this->ismultientitymanaged contains
  1126. // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  1127. $alias = 's';
  1128. if ($this->element == 'societe') $alias = 'te';
  1129. $sql = "SELECT MAX(te.".$fieldid.")";
  1130. $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1131. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && empty($user->rights->societe->client->voir))) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity
  1132. if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
  1133. $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'";
  1134. if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id;
  1135. if (! empty($filter)) $sql.=" AND ".$filter;
  1136. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
  1137. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')';
  1138. //print $sql."<br>";
  1139. $result = $this->db->query($sql);
  1140. if (! $result)
  1141. {
  1142. $this->error=$this->db->lasterror();
  1143. return -1;
  1144. }
  1145. $row = $this->db->fetch_row($result);
  1146. $this->ref_previous = $row[0];
  1147. $sql = "SELECT MIN(te.".$fieldid.")";
  1148. $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1149. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity
  1150. if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
  1151. $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'";
  1152. if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id;
  1153. if (! empty($filter)) $sql.=" AND ".$filter;
  1154. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
  1155. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')';
  1156. // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
  1157. //print $sql."<br>";
  1158. $result = $this->db->query($sql);
  1159. if (! $result)
  1160. {
  1161. $this->error=$this->db->lasterror();
  1162. return -2;
  1163. }
  1164. $row = $this->db->fetch_row($result);
  1165. $this->ref_next = $row[0];
  1166. return 1;
  1167. }
  1168. /**
  1169. * Return list of id of contacts of project
  1170. *
  1171. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1172. * @return array Array of id of contacts (if source=external or internal)
  1173. * Array of id of third parties with at least one contact on project (if source=thirdparty)
  1174. */
  1175. function getListContactId($source='external')
  1176. {
  1177. $contactAlreadySelected = array();
  1178. $tab = $this->liste_contact(-1,$source);
  1179. $num=count($tab);
  1180. $i = 0;
  1181. while ($i < $num)
  1182. {
  1183. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1184. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  1185. $i++;
  1186. }
  1187. return $contactAlreadySelected;
  1188. }
  1189. /**
  1190. * Link element with a project
  1191. *
  1192. * @param int $projectid Project id to link element to
  1193. * @return int <0 if KO, >0 if OK
  1194. */
  1195. function setProject($projectid)
  1196. {
  1197. if (! $this->table_element)
  1198. {
  1199. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR);
  1200. return -1;
  1201. }
  1202. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1203. if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
  1204. else $sql.= ' SET fk_projet = NULL';
  1205. $sql.= ' WHERE rowid = '.$this->id;
  1206. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1207. if ($this->db->query($sql))
  1208. {
  1209. $this->fk_project = $projectid;
  1210. return 1;
  1211. }
  1212. else
  1213. {
  1214. dol_print_error($this->db);
  1215. return -1;
  1216. }
  1217. }
  1218. /**
  1219. * Change the payments methods
  1220. *
  1221. * @param int $id Id of new payment method
  1222. * @return int >0 if OK, <0 if KO
  1223. */
  1224. function setPaymentMethods($id)
  1225. {
  1226. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1227. if ($this->statut >= 0 || $this->element == 'societe')
  1228. {
  1229. // TODO uniformize field name
  1230. $fieldname = 'fk_mode_reglement';
  1231. if ($this->element == 'societe') $fieldname = 'mode_reglement';
  1232. if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
  1233. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1234. $sql .= ' SET '.$fieldname.' = '.$id;
  1235. $sql .= ' WHERE rowid='.$this->id;
  1236. if ($this->db->query($sql))
  1237. {
  1238. $this->mode_reglement_id = $id;
  1239. // for supplier
  1240. if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
  1241. return 1;
  1242. }
  1243. else
  1244. {
  1245. dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
  1246. $this->error=$this->db->error();
  1247. return -1;
  1248. }
  1249. }
  1250. else
  1251. {
  1252. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  1253. $this->error='Status of the object is incompatible '.$this->statut;
  1254. return -2;
  1255. }
  1256. }
  1257. /**
  1258. * Change the multicurrency code
  1259. *
  1260. * @param string $code multicurrency code
  1261. * @return int >0 if OK, <0 if KO
  1262. */
  1263. function setMulticurrencyCode($code)
  1264. {
  1265. dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')');
  1266. if ($this->statut >= 0 || $this->element == 'societe')
  1267. {
  1268. $fieldname = 'multicurrency_code';
  1269. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1270. $sql .= ' SET '.$fieldname.' = "'.$this->db->escape($code).'"';
  1271. $sql .= ' WHERE rowid='.$this->id;
  1272. if ($this->db->query($sql))
  1273. {
  1274. $this->multicurrency_code = $code;
  1275. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  1276. if ($rate) $this->setMulticurrencyRate($rate);
  1277. return 1;
  1278. }
  1279. else
  1280. {
  1281. dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
  1282. $this->error=$this->db->error();
  1283. return -1;
  1284. }
  1285. }
  1286. else
  1287. {
  1288. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  1289. $this->error='Status of the object is incompatible '.$this->statut;
  1290. return -2;
  1291. }
  1292. }
  1293. /**
  1294. * Change the multicurrency rate
  1295. *
  1296. * @param double $rate multicurrency rate
  1297. * @return int >0 if OK, <0 if KO
  1298. */
  1299. function setMulticurrencyRate($rate)
  1300. {
  1301. dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')');
  1302. if ($this->statut >= 0 || $this->element == 'societe')
  1303. {
  1304. $fieldname = 'multicurrency_tx';
  1305. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1306. $sql .= ' SET '.$fieldname.' = '.$rate;
  1307. $sql .= ' WHERE rowid='.$this->id;
  1308. if ($this->db->query($sql))
  1309. {
  1310. $this->multicurrency_tx = $rate;
  1311. // Update line price
  1312. if (!empty($this->lines))
  1313. {
  1314. foreach ($this->lines as &$line)
  1315. {
  1316. switch ($this->element) {
  1317. case 'propal':
  1318. $this->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->desc, 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit);
  1319. break;
  1320. case 'commande':
  1321. $this->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit);
  1322. break;
  1323. case 'facture':
  1324. $this->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
  1325. break;
  1326. case 'supplier_proposal':
  1327. $this->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->desc, 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options, $line->ref_fourn);
  1328. break;
  1329. case 'order_supplier':
  1330. $this->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit);
  1331. break;
  1332. default:
  1333. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. return 1;
  1339. }
  1340. else
  1341. {
  1342. dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
  1343. $this->error=$this->db->error();
  1344. return -1;
  1345. }
  1346. }
  1347. else
  1348. {
  1349. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  1350. $this->error='Status of the object is incompatible '.$this->statut;
  1351. return -2;
  1352. }
  1353. }
  1354. /**
  1355. * Change the payments terms
  1356. *
  1357. * @param int $id Id of new payment terms
  1358. * @return int >0 if OK, <0 if KO
  1359. */
  1360. function setPaymentTerms($id)
  1361. {
  1362. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  1363. if ($this->statut >= 0 || $this->element == 'societe')
  1364. {
  1365. // TODO uniformize field name
  1366. $fieldname = 'fk_cond_reglement';
  1367. if ($this->element == 'societe') $fieldname = 'cond_reglement';
  1368. if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
  1369. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1370. $sql .= ' SET '.$fieldname.' = '.$id;
  1371. $sql .= ' WHERE rowid='.$this->id;
  1372. if ($this->db->query($sql))
  1373. {
  1374. $this->cond_reglement_id = $id;
  1375. // for supplier
  1376. if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
  1377. $this->cond_reglement = $id; // for compatibility
  1378. return 1;
  1379. }
  1380. else
  1381. {
  1382. dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
  1383. $this->error=$this->db->error();
  1384. return -1;
  1385. }
  1386. }
  1387. else
  1388. {
  1389. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  1390. $this->error='Status of the object is incompatible '.$this->statut;
  1391. return -2;
  1392. }
  1393. }
  1394. /**
  1395. * Define delivery address
  1396. *
  1397. * @param int $id Address id
  1398. * @return int <0 si ko, >0 si ok
  1399. */
  1400. function setDeliveryAddress($id)
  1401. {
  1402. $fieldname = 'fk_delivery_address';
  1403. if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
  1404. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
  1405. $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  1406. if ($this->db->query($sql))
  1407. {
  1408. $this->fk_delivery_address = $id;
  1409. return 1;
  1410. }
  1411. else
  1412. {
  1413. $this->error=$this->db->error();
  1414. dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
  1415. return -1;
  1416. }
  1417. }
  1418. /**
  1419. * Change the shipping method
  1420. *
  1421. * @param int $shipping_method_id Id of shipping method
  1422. * @return int 1 if OK, 0 if KO
  1423. */
  1424. function setShippingMethod($shipping_method_id)
  1425. {
  1426. if (! $this->table_element) {
  1427. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR);
  1428. return -1;
  1429. }
  1430. if ($shipping_method_id<0) $shipping_method_id='NULL';
  1431. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  1432. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1433. $sql.= " SET fk_shipping_method = ".$shipping_method_id;
  1434. $sql.= " WHERE rowid=".$this->id;
  1435. if ($this->db->query($sql)) {
  1436. $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id;
  1437. return 1;
  1438. } else {
  1439. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  1440. $this->error=$this->db->error();
  1441. return 0;
  1442. }
  1443. }
  1444. /**
  1445. * Change the warehouse
  1446. *
  1447. * @param int $warehouse_id Id of warehouse
  1448. * @return int 1 if OK, 0 if KO
  1449. */
  1450. function setWarehouse($warehouse_id)
  1451. {
  1452. if (! $this->table_element) {
  1453. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR);
  1454. return -1;
  1455. }
  1456. if ($warehouse_id<0) $warehouse_id='NULL';
  1457. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  1458. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1459. $sql.= " SET fk_warehouse = ".$warehouse_id;
  1460. $sql.= " WHERE rowid=".$this->id;
  1461. if ($this->db->query($sql)) {
  1462. $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id;
  1463. return 1;
  1464. } else {
  1465. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  1466. $this->error=$this->db->error();
  1467. return 0;
  1468. }
  1469. }
  1470. /**
  1471. * Set last model used by doc generator
  1472. *
  1473. * @param User $user User object that make change
  1474. * @param string $modelpdf Modele name
  1475. * @return int <0 if KO, >0 if OK
  1476. */
  1477. function setDocModel($user, $modelpdf)
  1478. {
  1479. if (! $this->table_element)
  1480. {
  1481. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR);
  1482. return -1;
  1483. }
  1484. $newmodelpdf=dol_trunc($modelpdf,255);
  1485. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1486. $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  1487. $sql.= " WHERE rowid = ".$this->id;
  1488. // if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
  1489. // if ($this->element == 'propal') $sql.= " AND fk_statut = 0";
  1490. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  1491. $resql=$this->db->query($sql);
  1492. if ($resql)
  1493. {
  1494. $this->modelpdf=$modelpdf;
  1495. return 1;
  1496. }
  1497. else
  1498. {
  1499. dol_print_error($this->db);
  1500. return 0;
  1501. }
  1502. }
  1503. /**
  1504. * Change the bank account
  1505. *
  1506. * @param int $fk_account Id of bank account
  1507. * @return int 1 if OK, 0 if KO
  1508. */
  1509. function setBankAccount($fk_account)
  1510. {
  1511. if (! $this->table_element) {
  1512. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR);
  1513. return -1;
  1514. }
  1515. if ($fk_account<0) $fk_account='NULL';
  1516. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  1517. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1518. $sql.= " SET fk_account = ".$fk_account;
  1519. $sql.= " WHERE rowid=".$this->id;
  1520. if ($this->db->query($sql)) {
  1521. $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
  1522. return 1;
  1523. } else {
  1524. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  1525. $this->error=$this->db->error();
  1526. return 0;
  1527. }
  1528. }
  1529. // TODO: Move line related operations to CommonObjectLine?
  1530. /**
  1531. * Save a new position (field rang) for details lines.
  1532. * You can choose to set position for lines with already a position or lines without any position defined.
  1533. *
  1534. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  1535. * @param string $rowidorder ASC or DESC
  1536. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1537. * @return int <0 if KO, >0 if OK
  1538. */
  1539. function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
  1540. {
  1541. if (! $this->table_element_line)
  1542. {
  1543. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR);
  1544. return -1;
  1545. }
  1546. if (! $this->fk_element)
  1547. {
  1548. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR);
  1549. return -1;
  1550. }
  1551. // Count number of lines to reorder (according to choice $renum)
  1552. $nl=0;
  1553. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1554. $sql.= ' WHERE '.$this->fk_element.'='.$this->id;
  1555. if (! $renum) $sql.= ' AND rang = 0';
  1556. if ($renum) $sql.= ' AND rang <> 0';
  1557. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  1558. $resql = $this->db->query($sql);
  1559. if ($resql)
  1560. {
  1561. $row = $this->db->fetch_row($resql);
  1562. $nl = $row[0];
  1563. }
  1564. else dol_print_error($this->db);
  1565. if ($nl > 0)
  1566. {
  1567. // The goal of this part is to reorder all lines, with all children lines sharing the same
  1568. // counter that parents.
  1569. $rows=array();
  1570. // We first search all lines that are parent lines (for multilevel details lines)
  1571. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1572. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1573. if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL';
  1574. $sql.= ' ORDER BY rang ASC, rowid '.$rowidorder;
  1575. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  1576. $resql = $this->db->query($sql);
  1577. if ($resql)
  1578. {
  1579. $i=0;
  1580. $num = $this->db->num_rows($resql);
  1581. while ($i < $num)
  1582. {
  1583. $row = $this->db->fetch_row($resql);
  1584. $rows[] = $row[0]; // Add parent line into array rows
  1585. $childrens = $this->getChildrenOfLine($row[0]);
  1586. if (! empty($childrens))
  1587. {
  1588. foreach($childrens as $child)
  1589. {
  1590. array_push($rows, $child);
  1591. }
  1592. }
  1593. $i++;
  1594. }
  1595. // Now we set a new number for each lines (parent and children with children included into parent tree)
  1596. if (! empty($rows))
  1597. {
  1598. foreach($rows as $key => $row)
  1599. {
  1600. $this->updateRangOfLine($row, ($key+1));
  1601. }
  1602. }
  1603. }
  1604. else
  1605. {
  1606. dol_print_error($this->db);
  1607. }
  1608. }
  1609. return 1;
  1610. }
  1611. /**
  1612. * Get children of line
  1613. *
  1614. * @param int $id Id of parent line
  1615. * @return array Array with list of children lines id
  1616. */
  1617. function getChildrenOfLine($id)
  1618. {
  1619. $rows=array();
  1620. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1621. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1622. $sql.= ' AND fk_parent_line = '.$id;
  1623. $sql.= ' ORDER BY rang ASC';
  1624. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  1625. $resql = $this->db->query($sql);
  1626. if ($resql)
  1627. {
  1628. $i=0;
  1629. $num = $this->db->num_rows($resql);
  1630. while ($i < $num)
  1631. {
  1632. $row = $this->db->fetch_row($resql);
  1633. $rows[$i] = $row[0];
  1634. $i++;
  1635. }
  1636. }
  1637. return $rows;
  1638. }
  1639. /**
  1640. * Update a line to have a lower rank
  1641. *
  1642. * @param int $rowid Id of line
  1643. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1644. * @return void
  1645. */
  1646. function line_up($rowid, $fk_parent_line=true)
  1647. {
  1648. $this->line_order(false, 'ASC', $fk_parent_line);
  1649. // Get rang of line
  1650. $rang = $this->getRangOfLine($rowid);
  1651. // Update position of line
  1652. $this->updateLineUp($rowid, $rang);
  1653. }
  1654. /**
  1655. * Update a line to have a higher rank
  1656. *
  1657. * @param int $rowid Id of line
  1658. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1659. * @return void
  1660. */
  1661. function line_down($rowid, $fk_parent_line=true)
  1662. {
  1663. $this->line_order(false, 'ASC', $fk_parent_line);
  1664. // Get rang of line
  1665. $rang = $this->getRangOfLine($rowid);
  1666. // Get max value for rang
  1667. $max = $this->line_max();
  1668. // Update position of line
  1669. $this->updateLineDown($rowid, $rang, $max);
  1670. }
  1671. /**
  1672. * Update position of line (rang)
  1673. *
  1674. * @param int $rowid Id of line
  1675. * @param int $rang Position
  1676. * @return void
  1677. */
  1678. function updateRangOfLine($rowid,$rang)
  1679. {
  1680. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang;
  1681. $sql.= ' WHERE rowid = '.$rowid;
  1682. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  1683. if (! $this->db->query($sql))
  1684. {
  1685. dol_print_error($this->db);
  1686. }
  1687. }
  1688. /**
  1689. * Update position of line with ajax (rang)
  1690. *
  1691. * @param array $rows Array of rows
  1692. * @return void
  1693. */
  1694. function line_ajaxorder($rows)
  1695. {
  1696. $num = count($rows);
  1697. for ($i = 0 ; $i < $num ; $i++)
  1698. {
  1699. $this->updateRangOfLine($rows[$i], ($i+1));
  1700. }
  1701. }
  1702. /**
  1703. * Update position of line up (rang)
  1704. *
  1705. * @param int $rowid Id of line
  1706. * @param int $rang Position
  1707. * @return void
  1708. */
  1709. function updateLineUp($rowid,$rang)
  1710. {
  1711. if ($rang > 1 )
  1712. {
  1713. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ;
  1714. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1715. $sql.= ' AND rang = '.($rang - 1);
  1716. if ($this->db->query($sql) )
  1717. {
  1718. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1);
  1719. $sql.= ' WHERE rowid = '.$rowid;
  1720. if (! $this->db->query($sql) )
  1721. {
  1722. dol_print_error($this->db);
  1723. }
  1724. }
  1725. else
  1726. {
  1727. dol_print_error($this->db);
  1728. }
  1729. }
  1730. }
  1731. /**
  1732. * Update position of line down (rang)
  1733. *
  1734. * @param int $rowid Id of line
  1735. * @param int $rang Position
  1736. * @param int $max Max
  1737. * @return void
  1738. */
  1739. function updateLineDown($rowid,$rang,$max)
  1740. {
  1741. if ($rang < $max)
  1742. {
  1743. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang;
  1744. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1745. $sql.= ' AND rang = '.($rang+1);
  1746. if ($this->db->query($sql) )
  1747. {
  1748. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1);
  1749. $sql.= ' WHERE rowid = '.$rowid;
  1750. if (! $this->db->query($sql) )
  1751. {
  1752. dol_print_error($this->db);
  1753. }
  1754. }
  1755. else
  1756. {
  1757. dol_print_error($this->db);
  1758. }
  1759. }
  1760. }
  1761. /**
  1762. * Get position of line (rang)
  1763. *
  1764. * @param int $rowid Id of line
  1765. * @return int Value of rang in table of lines
  1766. */
  1767. function getRangOfLine($rowid)
  1768. {
  1769. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1770. $sql.= ' WHERE rowid ='.$rowid;
  1771. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  1772. $resql = $this->db->query($sql);
  1773. if ($resql)
  1774. {
  1775. $row = $this->db->fetch_row($resql);
  1776. return $row[0];
  1777. }
  1778. }
  1779. /**
  1780. * Get rowid of the line relative to its position
  1781. *
  1782. * @param int $rang Rang value
  1783. * @return int Rowid of the line
  1784. */
  1785. function getIdOfLine($rang)
  1786. {
  1787. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1788. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1789. $sql.= ' AND rang = '.$rang;
  1790. $resql = $this->db->query($sql);
  1791. if ($resql)
  1792. {
  1793. $row = $this->db->fetch_row($resql);
  1794. return $row[0];
  1795. }
  1796. }
  1797. /**
  1798. * Get max value used for position of line (rang)
  1799. *
  1800. * @param int $fk_parent_line Parent line id
  1801. * @return int Max value of rang in table of lines
  1802. */
  1803. function line_max($fk_parent_line=0)
  1804. {
  1805. // Search the last rang with fk_parent_line
  1806. if ($fk_parent_line)
  1807. {
  1808. $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1809. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1810. $sql.= ' AND fk_parent_line = '.$fk_parent_line;
  1811. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  1812. $resql = $this->db->query($sql);
  1813. if ($resql)
  1814. {
  1815. $row = $this->db->fetch_row($resql);
  1816. if (! empty($row[0]))
  1817. {
  1818. return $row[0];
  1819. }
  1820. else
  1821. {
  1822. return $this->getRangOfLine($fk_parent_line);
  1823. }
  1824. }
  1825. }
  1826. // If not, search the last rang of element
  1827. else
  1828. {
  1829. $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1830. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1831. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  1832. $resql = $this->db->query($sql);
  1833. if ($resql)
  1834. {
  1835. $row = $this->db->fetch_row($resql);
  1836. return $row[0];
  1837. }
  1838. }
  1839. }
  1840. /**
  1841. * Update external ref of element
  1842. *
  1843. * @param string $ref_ext Update field ref_ext
  1844. * @return int <0 if KO, >0 if OK
  1845. */
  1846. function update_ref_ext($ref_ext)
  1847. {
  1848. if (! $this->table_element)
  1849. {
  1850. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  1851. return -1;
  1852. }
  1853. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1854. $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  1855. $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id;
  1856. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  1857. if ($this->db->query($sql))
  1858. {
  1859. $this->ref_ext = $ref_ext;
  1860. return 1;
  1861. }
  1862. else
  1863. {
  1864. $this->error=$this->db->error();
  1865. return -1;
  1866. }
  1867. }
  1868. /**
  1869. * Update note of element
  1870. *
  1871. * @param string $note New value for note
  1872. * @param string $suffix '', '_public' or '_private'
  1873. * @return int <0 if KO, >0 if OK
  1874. */
  1875. function update_note($note,$suffix='')
  1876. {
  1877. if (! $this->table_element)
  1878. {
  1879. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  1880. return -1;
  1881. }
  1882. if (! in_array($suffix,array('','_public','_private')))
  1883. {
  1884. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  1885. return -2;
  1886. }
  1887. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1888. $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
  1889. $sql.= " WHERE rowid =". $this->id;
  1890. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  1891. if ($this->db->query($sql))
  1892. {
  1893. if ($suffix == '_public') $this->note_public = $note;
  1894. else if ($suffix == '_private') $this->note_private = $note;
  1895. else $this->note = $note;
  1896. return 1;
  1897. }
  1898. else
  1899. {
  1900. $this->error=$this->db->lasterror();
  1901. return -1;
  1902. }
  1903. }
  1904. /**
  1905. * Update public note (kept for backward compatibility)
  1906. *
  1907. * @param string $note New value for note
  1908. * @return int <0 if KO, >0 if OK
  1909. * @deprecated
  1910. * @see update_note()
  1911. */
  1912. function update_note_public($note)
  1913. {
  1914. return $this->update_note($note,'_public');
  1915. }
  1916. /**
  1917. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  1918. * Must be called at end of methods addline or updateline.
  1919. *
  1920. * @param int $exclspec >0 = Exclude special product (product_type=9)
  1921. * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total
  1922. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  1923. * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object.
  1924. * @return int <0 if KO, >0 if OK
  1925. */
  1926. function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null)
  1927. {
  1928. global $conf;
  1929. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1930. if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility
  1931. $forcedroundingmode=$roundingadjust;
  1932. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  1933. elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
  1934. $error=0;
  1935. // Define constants to find lines to sum
  1936. $fieldtva='total_tva';
  1937. $fieldlocaltax1='total_localtax1';
  1938. $fieldlocaltax2='total_localtax2';
  1939. $fieldup='subprice';
  1940. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  1941. {
  1942. $fieldtva='tva';
  1943. $fieldup='pu_ht';
  1944. }
  1945. if ($this->element == 'expensereport')
  1946. {
  1947. $fieldup='value_unit';
  1948. }
  1949. $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,';
  1950. $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  1951. if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
  1952. $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  1953. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1954. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1955. if ($exclspec)
  1956. {
  1957. $product_field='product_type';
  1958. if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field
  1959. if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
  1960. }
  1961. $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
  1962. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  1963. $resql = $this->db->query($sql);
  1964. if ($resql)
  1965. {
  1966. $this->total_ht = 0;
  1967. $this->total_tva = 0;
  1968. $this->total_localtax1 = 0;
  1969. $this->total_localtax2 = 0;
  1970. $this->total_ttc = 0;
  1971. $total_ht_by_vats = array();
  1972. $total_tva_by_vats = array();
  1973. $total_ttc_by_vats = array();
  1974. $this->multicurrency_total_ht = 0;
  1975. $this->multicurrency_total_tva = 0;
  1976. $this->multicurrency_total_ttc = 0;
  1977. $num = $this->db->num_rows($resql);
  1978. $i = 0;
  1979. while ($i < $num)
  1980. {
  1981. $obj = $this->db->fetch_object($resql);
  1982. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  1983. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  1984. if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
  1985. {
  1986. $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
  1987. $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
  1988. $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
  1989. if ($diff)
  1990. {
  1991. $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  1992. dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
  1993. $resqlfix=$this->db->query($sqlfix);
  1994. if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
  1995. $obj->total_tva = $tmpcal[1];
  1996. $obj->total_ttc = $tmpcal[2];
  1997. //
  1998. }
  1999. }
  2000. $this->total_ht += $obj->total_ht; // The only field visible at end of line detail
  2001. $this->total_tva += $obj->total_tva;
  2002. $this->total_localtax1 += $obj->total_localtax1;
  2003. $this->total_localtax2 += $obj->total_localtax2;
  2004. $this->total_ttc += $obj->total_ttc;
  2005. if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0;
  2006. if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
  2007. if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
  2008. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  2009. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  2010. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  2011. if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat
  2012. {
  2013. $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  2014. $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
  2015. //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."<br>\n";
  2016. if ($diff)
  2017. {
  2018. if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
  2019. $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
  2020. dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
  2021. $resqlfix=$this->db->query($sqlfix);
  2022. if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
  2023. $this->total_tva -= $diff;
  2024. $this->total_ttc -= $diff;
  2025. $total_tva_by_vats[$obj->vatrate] -= $diff;
  2026. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  2027. }
  2028. }
  2029. $i++;
  2030. }
  2031. // Add revenue stamp to total
  2032. $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0;
  2033. // Situations totals
  2034. if ($this->situation_cycle_ref && $this->situation_counter > 1) {
  2035. $prev_sits = $this->get_prev_sits();
  2036. foreach ($prev_sits as $sit) {
  2037. $this->total_ht -= $sit->total_ht;
  2038. $this->total_tva -= $sit->total_tva;
  2039. $this->total_localtax1 -= $sit->total_localtax1;
  2040. $this->total_localtax2 -= $sit->total_localtax2;
  2041. $this->total_ttc -= $sit->total_ttc;
  2042. }
  2043. }
  2044. // Multicurrency
  2045. $this->multicurrency_total_ht += $this->total_ht * $multicurrency_tx;
  2046. $this->multicurrency_total_tva += $this->total_tva * $multicurrency_tx;
  2047. $this->multicurrency_total_ttc += $this->total_ttc * $multicurrency_tx;
  2048. $this->db->free($resql);
  2049. // Now update global field total_ht, total_ttc and tva
  2050. $fieldht='total_ht';
  2051. $fieldtva='tva';
  2052. $fieldlocaltax1='localtax1';
  2053. $fieldlocaltax2='localtax2';
  2054. $fieldttc='total_ttc';
  2055. // Specific code for backward compatibility with old field names
  2056. if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total';
  2057. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
  2058. if ($this->element == 'propal') $fieldttc='total';
  2059. if ($this->element == 'expensereport') $fieldtva='total_tva';
  2060. if ($this->element == 'supplier_proposal') $fieldttc='total';
  2061. if (empty($nodatabaseupdate))
  2062. {
  2063. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  2064. $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
  2065. $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
  2066. $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
  2067. $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
  2068. $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
  2069. $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
  2070. $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
  2071. $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
  2072. $sql .= ' WHERE rowid = '.$this->id;
  2073. //print "xx".$sql;
  2074. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2075. $resql=$this->db->query($sql);
  2076. if (! $resql)
  2077. {
  2078. $error++;
  2079. $this->error=$this->db->lasterror();
  2080. $this->errors[]=$this->db->lasterror();
  2081. }
  2082. }
  2083. if (! $error)
  2084. {
  2085. return 1;
  2086. }
  2087. else
  2088. {
  2089. return -1;
  2090. }
  2091. }
  2092. else
  2093. {
  2094. dol_print_error($this->db,'Bad request in update_price');
  2095. return -1;
  2096. }
  2097. }
  2098. /**
  2099. * Add objects linked in llx_element_element.
  2100. *
  2101. * @param string $origin Linked element type
  2102. * @param int $origin_id Linked element id
  2103. * @return int <=0 if KO, >0 if OK
  2104. * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked
  2105. */
  2106. function add_object_linked($origin=null, $origin_id=null)
  2107. {
  2108. $origin = (! empty($origin) ? $origin : $this->origin);
  2109. $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
  2110. $this->db->begin();
  2111. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  2112. $sql.= "fk_source";
  2113. $sql.= ", sourcetype";
  2114. $sql.= ", fk_target";
  2115. $sql.= ", targettype";
  2116. $sql.= ") VALUES (";
  2117. $sql.= $origin_id;
  2118. $sql.= ", '".$origin."'";
  2119. $sql.= ", ".$this->id;
  2120. $sql.= ", '".$this->element."'";
  2121. $sql.= ")";
  2122. dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
  2123. if ($this->db->query($sql))
  2124. {
  2125. $this->db->commit();
  2126. return 1;
  2127. }
  2128. else
  2129. {
  2130. $this->error=$this->db->lasterror();
  2131. $this->db->rollback();
  2132. return 0;
  2133. }
  2134. }
  2135. /**
  2136. * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds
  2137. * Possible usage for parameters:
  2138. * - all parameters empty -> we look all link to current object (current object can be source or target)
  2139. * - one couple id+type is provided -> this will set $justsource or $justtarget
  2140. * - one couple id+type is provided and other type is provided -> this will set $justsource or $justtarget + criteria on other type
  2141. *
  2142. *
  2143. * @param int $sourceid Object source id (if not defined, id of object)
  2144. * @param string $sourcetype Object source type (if not defined, element name of object)
  2145. * @param int $targetid Object target id (if not defined, id of object)
  2146. * @param string $targettype Object target type (if not defined, elemennt name of object)
  2147. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  2148. * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type.
  2149. * @return void
  2150. * @see add_object_linked, updateObjectLinked, deleteObjectLinked
  2151. */
  2152. function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1)
  2153. {
  2154. global $conf;
  2155. $this->linkedObjectsIds=array();
  2156. $this->linkedObjects=array();
  2157. $justsource=false;
  2158. $justtarget=false;
  2159. $withtargettype=false;
  2160. $withsourcetype=false;
  2161. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
  2162. {
  2163. $justsource=true; // the source (id and type) is a search criteria
  2164. if (! empty($targettype)) $withtargettype=true;
  2165. }
  2166. if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
  2167. {
  2168. $justtarget=true; // the target (id and type) is a search criteria
  2169. if (! empty($sourcetype)) $withsourcetype=true;
  2170. }
  2171. $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
  2172. $targetid = (! empty($targetid) ? $targetid : $this->id);
  2173. $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
  2174. $targettype = (! empty($targettype) ? $targettype : $this->element);
  2175. /*if (empty($sourceid) && empty($targetid))
  2176. {
  2177. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  2178. return -1;
  2179. }*/
  2180. // Links between objects are stored in table element_element
  2181. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  2182. $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
  2183. $sql.= " WHERE ";
  2184. if ($justsource || $justtarget)
  2185. {
  2186. if ($justsource)
  2187. {
  2188. $sql.= "fk_source = '".$sourceid."' AND sourcetype = '".$sourcetype."'";
  2189. if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
  2190. }
  2191. else if ($justtarget)
  2192. {
  2193. $sql.= "fk_target = '".$targetid."' AND targettype = '".$targettype."'";
  2194. if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
  2195. }
  2196. }
  2197. else
  2198. {
  2199. $sql.= "(fk_source = '".$sourceid."' AND sourcetype = '".$sourcetype."')";
  2200. $sql.= " ".$clause." (fk_target = '".$targetid."' AND targettype = '".$targettype."')";
  2201. }
  2202. $sql .= ' ORDER BY sourcetype';
  2203. //print $sql;
  2204. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  2205. $resql = $this->db->query($sql);
  2206. if ($resql)
  2207. {
  2208. $num = $this->db->num_rows($resql);
  2209. $i = 0;
  2210. while ($i < $num)
  2211. {
  2212. $obj = $this->db->fetch_object($resql);
  2213. if ($justsource || $justtarget)
  2214. {
  2215. if ($justsource)
  2216. {
  2217. $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
  2218. }
  2219. else if ($justtarget)
  2220. {
  2221. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
  2222. }
  2223. }
  2224. else
  2225. {
  2226. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
  2227. {
  2228. $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
  2229. }
  2230. if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
  2231. {
  2232. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
  2233. }
  2234. }
  2235. $i++;
  2236. }
  2237. if (! empty($this->linkedObjectsIds))
  2238. {
  2239. foreach($this->linkedObjectsIds as $objecttype => $objectids)
  2240. {
  2241. // Parse element/subelement (ex: project_task)
  2242. $module = $element = $subelement = $objecttype;
  2243. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  2244. && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  2245. {
  2246. $module = $element = $regs[1];
  2247. $subelement = $regs[2];
  2248. }
  2249. $classpath = $element.'/class';
  2250. // To work with non standard classpath or module name
  2251. if ($objecttype == 'facture') {
  2252. $classpath = 'compta/facture/class';
  2253. }
  2254. else if ($objecttype == 'facturerec') {
  2255. $classpath = 'compta/facture/class'; $module = 'facture';
  2256. }
  2257. else if ($objecttype == 'propal') {
  2258. $classpath = 'comm/propal/class';
  2259. }
  2260. else if ($objecttype == 'supplier_proposal') {
  2261. $classpath = 'supplier_proposal/class';
  2262. }
  2263. else if ($objecttype == 'shipping') {
  2264. $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
  2265. }
  2266. else if ($objecttype == 'delivery') {
  2267. $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
  2268. }
  2269. else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  2270. $classpath = 'fourn/class'; $module = 'fournisseur';
  2271. }
  2272. else if ($objecttype == 'fichinter') {
  2273. $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
  2274. }
  2275. else if ($objecttype == 'subscription') {
  2276. $classpath = 'adherents/class'; $module = 'adherent';
  2277. }
  2278. // Set classfile
  2279. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  2280. if ($objecttype == 'invoice_supplier') {
  2281. $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
  2282. }
  2283. else if ($objecttype == 'order_supplier') {
  2284. $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
  2285. }
  2286. else if ($objecttype == 'supplier_proposal') {
  2287. $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
  2288. }
  2289. else if ($objecttype == 'facturerec') {
  2290. $classfile = 'facture-rec'; $classname = 'FactureRec';
  2291. }
  2292. else if ($objecttype == 'subscription') {
  2293. $classfile = 'cotisation'; $classname = 'Cotisation';
  2294. }
  2295. // Here $module, $classfile and $classname are set
  2296. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
  2297. {
  2298. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  2299. foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element
  2300. {
  2301. $object = new $classname($this->db);
  2302. $ret = $object->fetch($objectid);
  2303. if ($ret >= 0)
  2304. {
  2305. $this->linkedObjects[$objecttype][$i] = $object;
  2306. }
  2307. }
  2308. }
  2309. }
  2310. }
  2311. }
  2312. else
  2313. {
  2314. dol_print_error($this->db);
  2315. }
  2316. }
  2317. /**
  2318. * Update object linked of a current object
  2319. *
  2320. * @param int $sourceid Object source id
  2321. * @param string $sourcetype Object source type
  2322. * @param int $targetid Object target id
  2323. * @param string $targettype Object target type
  2324. * @return int >0 if OK, <0 if KO
  2325. * @see add_object_linked, fetObjectLinked, deleteObjectLinked
  2326. */
  2327. function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='')
  2328. {
  2329. $updatesource=false;
  2330. $updatetarget=false;
  2331. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true;
  2332. else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true;
  2333. $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
  2334. if ($updatesource)
  2335. {
  2336. $sql.= "fk_source = ".$sourceid;
  2337. $sql.= ", sourcetype = '".$sourcetype."'";
  2338. $sql.= " WHERE fk_target = ".$this->id;
  2339. $sql.= " AND targettype = '".$this->element."'";
  2340. }
  2341. else if ($updatetarget)
  2342. {
  2343. $sql.= "fk_target = ".$targetid;
  2344. $sql.= ", targettype = '".$targettype."'";
  2345. $sql.= " WHERE fk_source = ".$this->id;
  2346. $sql.= " AND sourcetype = '".$this->element."'";
  2347. }
  2348. dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
  2349. if ($this->db->query($sql))
  2350. {
  2351. return 1;
  2352. }
  2353. else
  2354. {
  2355. $this->error=$this->db->lasterror();
  2356. return -1;
  2357. }
  2358. }
  2359. /**
  2360. * Delete all links between an object $this
  2361. *
  2362. * @param int $sourceid Object source id
  2363. * @param string $sourcetype Object source type
  2364. * @param int $targetid Object target id
  2365. * @param string $targettype Object target type
  2366. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  2367. * @return int >0 if OK, <0 if KO
  2368. * @see add_object_linked, updateObjectLinked, fetchObjectLinked
  2369. */
  2370. function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
  2371. {
  2372. $deletesource=false;
  2373. $deletetarget=false;
  2374. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource=true;
  2375. else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $deletetarget=true;
  2376. $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
  2377. $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
  2378. $targetid = (! empty($targetid) ? $targetid : $this->id);
  2379. $targettype = (! empty($targettype) ? $targettype : $this->element);
  2380. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  2381. $sql.= " WHERE";
  2382. if ($rowid > 0)
  2383. {
  2384. $sql.=" rowid = ".$rowid;
  2385. }
  2386. else
  2387. {
  2388. if ($deletesource)
  2389. {
  2390. $sql.= " fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
  2391. $sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->element."'";
  2392. }
  2393. else if ($deletetarget)
  2394. {
  2395. $sql.= " fk_target = ".$targetid." AND targettype = '".$targettype."'";
  2396. $sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->element."'";
  2397. }
  2398. else
  2399. {
  2400. $sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->element."')";
  2401. $sql.= " OR";
  2402. $sql.= " (fk_target = ".$this->id." AND targettype = '".$this->element."')";
  2403. }
  2404. }
  2405. dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
  2406. if ($this->db->query($sql))
  2407. {
  2408. return 1;
  2409. }
  2410. else
  2411. {
  2412. $this->error=$this->db->lasterror();
  2413. $this->errors[]=$this->error;
  2414. return -1;
  2415. }
  2416. }
  2417. /**
  2418. * Set status of an object
  2419. *
  2420. * @param int $status Status to set
  2421. * @param int $elementId Id of element to force (use this->id by default)
  2422. * @param string $elementType Type of element to force (use this->table_element by default)
  2423. * @return int <0 if KO, >0 if OK
  2424. */
  2425. function setStatut($status,$elementId=null,$elementType='')
  2426. {
  2427. global $user,$langs,$conf;
  2428. $elementId = (!empty($elementId)?$elementId:$this->id);
  2429. $elementTable = (!empty($elementType)?$elementType:$this->table_element);
  2430. $this->db->begin();
  2431. $fieldstatus="fk_statut";
  2432. if ($elementTable == 'user') $fieldstatus="statut";
  2433. if ($elementTable == 'expensereport') $fieldstatus="fk_statut";
  2434. if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status";
  2435. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  2436. $sql.= " SET ".$fieldstatus." = ".$status;
  2437. // If status = 1 = validated, update also fk_user_valid
  2438. if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id;
  2439. $sql.= " WHERE rowid=".$elementId;
  2440. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  2441. if ($this->db->query($sql))
  2442. {
  2443. $error = 0;
  2444. $trigkey='';
  2445. if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_CLOSE';
  2446. if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED';
  2447. if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED';
  2448. if ($trigkey)
  2449. {
  2450. // Appel des triggers
  2451. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  2452. $interface=new Interfaces($this->db);
  2453. $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf);
  2454. if ($result < 0) {
  2455. $error++; $this->errors=$interface->errors;
  2456. }
  2457. // Fin appel triggers
  2458. }
  2459. if (! $error)
  2460. {
  2461. $this->db->commit();
  2462. $this->statut = $status;
  2463. return 1;
  2464. }
  2465. else
  2466. {
  2467. $this->db->rollback();
  2468. dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
  2469. return -1;
  2470. }
  2471. }
  2472. else
  2473. {
  2474. $this->error=$this->db->lasterror();
  2475. $this->db->rollback();
  2476. return -1;
  2477. }
  2478. }
  2479. /**
  2480. * Load type of canvas of an object if it exists
  2481. *
  2482. * @param int $id Record id
  2483. * @param string $ref Record ref
  2484. * @return int <0 if KO, 0 if nothing done, >0 if OK
  2485. */
  2486. function getCanvas($id=0,$ref='')
  2487. {
  2488. global $conf;
  2489. if (empty($id) && empty($ref)) return 0;
  2490. if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
  2491. // Clean parameters
  2492. $ref = trim($ref);
  2493. $sql = "SELECT rowid, canvas";
  2494. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  2495. $sql.= " WHERE entity IN (".getEntity($this->element, 1).")";
  2496. if (! empty($id)) $sql.= " AND rowid = ".$id;
  2497. if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
  2498. $resql = $this->db->query($sql);
  2499. if ($resql)
  2500. {
  2501. $obj = $this->db->fetch_object($resql);
  2502. if ($obj)
  2503. {
  2504. $this->canvas = $obj->canvas;
  2505. return 1;
  2506. }
  2507. else return 0;
  2508. }
  2509. else
  2510. {
  2511. dol_print_error($this->db);
  2512. return -1;
  2513. }
  2514. }
  2515. /**
  2516. * Get special code of a line
  2517. *
  2518. * @param int $lineid Id of line
  2519. * @return int Special code
  2520. */
  2521. function getSpecialCode($lineid)
  2522. {
  2523. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2524. $sql.= ' WHERE rowid = '.$lineid;
  2525. $resql = $this->db->query($sql);
  2526. if ($resql)
  2527. {
  2528. $row = $this->db->fetch_row($resql);
  2529. return $row[0];
  2530. }
  2531. }
  2532. /**
  2533. * Function to check if an object is used by others.
  2534. * Check is done into this->childtables. There is no check into llx_element_element.
  2535. *
  2536. * @param int $id Id of object
  2537. * @return int <0 if KO, 0 if not used, >0 if already used
  2538. */
  2539. function isObjectUsed($id)
  2540. {
  2541. // Check parameters
  2542. if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
  2543. {
  2544. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  2545. return -1;
  2546. }
  2547. // Test if child exists
  2548. $haschild=0;
  2549. foreach($this->childtables as $table)
  2550. {
  2551. // Check if third party can be deleted
  2552. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  2553. $sql.= " WHERE ".$this->fk_element." = ".$id;
  2554. $resql=$this->db->query($sql);
  2555. if ($resql)
  2556. {
  2557. $obj=$this->db->fetch_object($resql);
  2558. $haschild+=$obj->nb;
  2559. //print 'Found into table '.$table;
  2560. if ($haschild) break; // We found at least on, we stop here
  2561. }
  2562. else
  2563. {
  2564. $this->error=$this->db->lasterror();
  2565. return -1;
  2566. }
  2567. }
  2568. if ($haschild > 0)
  2569. {
  2570. $this->error="ErrorRecordHasChildren";
  2571. return $haschild;
  2572. }
  2573. else return 0;
  2574. }
  2575. /**
  2576. * Function to say how many lines object contains
  2577. *
  2578. * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service
  2579. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  2580. */
  2581. function hasProductsOrServices($predefined=-1)
  2582. {
  2583. $nb=0;
  2584. foreach($this->lines as $key => $val)
  2585. {
  2586. $qualified=0;
  2587. if ($predefined == -1) $qualified=1;
  2588. if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
  2589. if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
  2590. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
  2591. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
  2592. if ($qualified) $nb++;
  2593. }
  2594. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  2595. return $nb;
  2596. }
  2597. /**
  2598. * Function that returns the total amount HT of discounts applied for all lines.
  2599. *
  2600. * @return float
  2601. */
  2602. function getTotalDiscount()
  2603. {
  2604. $total_discount=0.00;
  2605. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  2606. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  2607. $sql.= " WHERE ".$this->fk_element." = ".$this->id;
  2608. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  2609. $resql = $this->db->query($sql);
  2610. if ($resql)
  2611. {
  2612. $num=$this->db->num_rows($resql);
  2613. $i=0;
  2614. while ($i < $num)
  2615. {
  2616. $obj = $this->db->fetch_object($resql);
  2617. $pu_ht = $obj->pu_ht;
  2618. $qty= $obj->qty;
  2619. $total_ht = $obj->total_ht;
  2620. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  2621. $total_discount += $total_discount_line;
  2622. $i++;
  2623. }
  2624. }
  2625. //print $total_discount; exit;
  2626. return price2num($total_discount);
  2627. }
  2628. /**
  2629. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  2630. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  2631. *
  2632. * @return array array('weight'=>...,'volume'=>...)
  2633. */
  2634. function getTotalWeightVolume()
  2635. {
  2636. $weightUnit=0;
  2637. $volumeUnit=0;
  2638. $totalWeight = '';
  2639. $totalVolume = '';
  2640. $totalOrdered = ''; // defined for shipment only
  2641. $totalToShip = ''; // defined for shipment only
  2642. foreach ($this->lines as $line)
  2643. {
  2644. $totalOrdered+=$line->qty_asked; // defined for shipment only
  2645. $totalToShip+=$line->qty_shipped; // defined for shipment only
  2646. // Define qty, weight, volume, weight_units, volume_units
  2647. if ($this->element == 'shipping') $qty=$line->qty_shipped; // for shipments
  2648. else $qty=$line->qty;
  2649. $weight=$line->weight;
  2650. $volume=$line->volume;
  2651. $weight_units=$line->weight_units;
  2652. $volume_units=$line->volume_units;
  2653. $weightUnit=0;
  2654. $volumeUnit=0;
  2655. if (! empty($weight_units)) $weightUnit = $weight_units;
  2656. if (! empty($volume_units)) $volumeUnit = $volume_units;
  2657. //var_dump($line->volume_units);
  2658. if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit) > 50 means an exotic unit (like inch)
  2659. {
  2660. $trueWeightUnit=pow(10, $weightUnit);
  2661. $totalWeight += $weight * $qty * $trueWeightUnit;
  2662. }
  2663. else
  2664. {
  2665. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  2666. }
  2667. if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit) > 50 means an exotic unit (like inch)
  2668. {
  2669. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  2670. $trueVolumeUnit=pow(10, $volumeUnit);
  2671. //print $line->volume;
  2672. $totalVolume += $volume * $qty * $trueVolumeUnit;
  2673. }
  2674. else
  2675. {
  2676. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  2677. }
  2678. }
  2679. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  2680. }
  2681. /**
  2682. * Set extra parameters
  2683. *
  2684. * @return int <0 if KO, >0 if OK
  2685. */
  2686. function setExtraParameters()
  2687. {
  2688. $this->db->begin();
  2689. $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
  2690. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2691. $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  2692. $sql.= " WHERE rowid = ".$this->id;
  2693. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  2694. $resql = $this->db->query($sql);
  2695. if (! $resql)
  2696. {
  2697. $this->error=$this->db->lasterror();
  2698. $this->db->rollback();
  2699. return -1;
  2700. }
  2701. else
  2702. {
  2703. $this->db->commit();
  2704. return 1;
  2705. }
  2706. }
  2707. /**
  2708. * Return incoterms informations
  2709. *
  2710. * @return string incoterms info
  2711. */
  2712. function display_incoterms()
  2713. {
  2714. $out = '';
  2715. $this->libelle_incoterms = '';
  2716. if (!empty($this->fk_incoterms))
  2717. {
  2718. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  2719. $result = $this->db->query($sql);
  2720. if ($result)
  2721. {
  2722. $res = $this->db->fetch_object($result);
  2723. $out .= $res->code;
  2724. }
  2725. }
  2726. $out .= ' - '.$this->location_incoterms;
  2727. return $out;
  2728. }
  2729. /**
  2730. * Return incoterms informations for pdf display
  2731. *
  2732. * @return string incoterms info
  2733. */
  2734. function getIncotermsForPDF()
  2735. {
  2736. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  2737. $resql = $this->db->query($sql);
  2738. if ($resql)
  2739. {
  2740. $res = $this->db->fetch_object($resql);
  2741. return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
  2742. }
  2743. else
  2744. {
  2745. $this->errors[] = $this->db->lasterror();
  2746. return false;
  2747. }
  2748. }
  2749. /**
  2750. * Define incoterms values of current object
  2751. *
  2752. * @param int $id_incoterm Id of incoterm to set or '' to remove
  2753. * @param string $location location of incoterm
  2754. * @return int <0 if KO, >0 if OK
  2755. */
  2756. function setIncoterms($id_incoterm, $location)
  2757. {
  2758. if ($this->id && $this->table_element)
  2759. {
  2760. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2761. $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
  2762. $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
  2763. $sql.= " WHERE rowid = " . $this->id;
  2764. dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
  2765. $resql=$this->db->query($sql);
  2766. if ($resql)
  2767. {
  2768. $this->fk_incoterms = $id_incoterm;
  2769. $this->location_incoterms = $location;
  2770. $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  2771. $res = $this->db->query($sql);
  2772. if ($res)
  2773. {
  2774. $obj = $this->db->fetch_object($res);
  2775. $this->libelle_incoterms = $obj->libelle;
  2776. }
  2777. return 1;
  2778. }
  2779. else
  2780. {
  2781. $this->errors[] = $this->db->lasterror();
  2782. return -1;
  2783. }
  2784. }
  2785. else return -1;
  2786. }
  2787. /**
  2788. * Return if a country is inside the EEC (European Economic Community)
  2789. * TODO Add a field into dictionary
  2790. *
  2791. * @return boolean true = country inside EEC, false = country outside EEC
  2792. */
  2793. function isInEEC()
  2794. {
  2795. // List of all country codes that are in europe for european vat rules
  2796. // List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9
  2797. $country_code_in_EEC=array(
  2798. 'AT', // Austria
  2799. 'BE', // Belgium
  2800. 'BG', // Bulgaria
  2801. 'CY', // Cyprus
  2802. 'CZ', // Czech republic
  2803. 'DE', // Germany
  2804. 'DK', // Danemark
  2805. 'EE', // Estonia
  2806. 'ES', // Spain
  2807. 'FI', // Finland
  2808. 'FR', // France
  2809. 'GB', // United Kingdom
  2810. 'GR', // Greece
  2811. 'HR', // Croatia
  2812. 'NL', // Holland
  2813. 'HU', // Hungary
  2814. 'IE', // Ireland
  2815. 'IM', // Isle of Man - Included in UK
  2816. 'IT', // Italy
  2817. 'LT', // Lithuania
  2818. 'LU', // Luxembourg
  2819. 'LV', // Latvia
  2820. 'MC', // Monaco - Included in France
  2821. 'MT', // Malta
  2822. //'NO', // Norway
  2823. 'PL', // Poland
  2824. 'PT', // Portugal
  2825. 'RO', // Romania
  2826. 'SE', // Sweden
  2827. 'SK', // Slovakia
  2828. 'SI', // Slovenia
  2829. 'UK', // United Kingdom
  2830. //'CH', // Switzerland - No. Swizerland in not in EEC
  2831. );
  2832. //print "dd".$this->country_code;
  2833. return in_array($this->country_code,$country_code_in_EEC);
  2834. }
  2835. // --------------------
  2836. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  2837. // --------------------
  2838. /**
  2839. * Show linked object block.
  2840. *
  2841. * @return int <0 if KO, >0 if OK
  2842. * @deprecated 3.8 Use instead $form->showLinkedObjectBlock($object)
  2843. * @see Form::showLinkedObjectBlock
  2844. */
  2845. function showLinkedObjectBlock()
  2846. {
  2847. global $form;
  2848. return $form->showLinkedObjectBlock($this);
  2849. }
  2850. /* This is to show add lines */
  2851. /**
  2852. * Show add free and predefined products/services form
  2853. *
  2854. * @param int $dateSelector 1=Show also date range input fields
  2855. * @param Societe $seller Object thirdparty who sell
  2856. * @param Societe $buyer Object thirdparty who buy
  2857. * @return void
  2858. */
  2859. function formAddObjectLine($dateSelector,$seller,$buyer)
  2860. {
  2861. global $conf,$user,$langs,$object,$hookmanager;
  2862. global $form,$bcnd,$var;
  2863. //Line extrafield
  2864. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  2865. $extrafieldsline = new ExtraFields($this->db);
  2866. $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
  2867. // Output template part (modules that overwrite templates must declare this into descriptor)
  2868. // Use global variables + $dateSelector + $seller and $buyer
  2869. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  2870. foreach($dirtpls as $reldir)
  2871. {
  2872. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  2873. if (empty($conf->file->strict_mode)) {
  2874. $res=@include $tpl;
  2875. } else {
  2876. $res=include $tpl; // for debug
  2877. }
  2878. if ($res) break;
  2879. }
  2880. }
  2881. /* This is to show array of line of details */
  2882. /**
  2883. * Return HTML table for object lines
  2884. * TODO Move this into an output class file (htmlline.class.php)
  2885. * If lines are into a template, title must also be into a template
  2886. * But for the moment we don't know if it'st possible as we keep a method available on overloaded objects.
  2887. *
  2888. * @param string $action Action code
  2889. * @param string $seller Object of seller third party
  2890. * @param string $buyer Object of buyer third party
  2891. * @param int $selected Object line selected
  2892. * @param int $dateSelector 1=Show also date range input fields
  2893. * @return void
  2894. */
  2895. function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
  2896. {
  2897. global $conf, $hookmanager, $langs, $user;
  2898. // TODO We should not use global var for this !
  2899. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove;
  2900. // Define usemargins
  2901. $usemargins=0;
  2902. if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
  2903. print '<tr class="liste_titre nodrag nodrop">';
  2904. if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
  2905. // Description
  2906. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  2907. if ($this->element == 'supplier_proposal')
  2908. {
  2909. print '<td class="linerefsupplier" align="right"><span id="title_fourn_ref">'.$langs->trans("SupplierProposalRefFourn").'</span></td>';
  2910. }
  2911. // VAT
  2912. print '<td class="linecolvat" align="right" width="50">'.$langs->trans('VAT').'</td>';
  2913. // Price HT
  2914. print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
  2915. // Multicurrency
  2916. if (!empty($conf->multicurrency->enabled)) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency').'</td>';
  2917. if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
  2918. // Qty
  2919. print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
  2920. if($conf->global->PRODUCT_USE_UNITS)
  2921. {
  2922. print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
  2923. }
  2924. // Reduction short
  2925. print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
  2926. if ($this->situation_cycle_ref) {
  2927. print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
  2928. }
  2929. if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id))
  2930. {
  2931. if ($conf->global->MARGIN_TYPE == "1")
  2932. print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
  2933. else
  2934. print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
  2935. if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
  2936. print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
  2937. if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
  2938. print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
  2939. }
  2940. // Total HT
  2941. print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
  2942. // Multicurrency
  2943. if (!empty($conf->multicurrency->enabled)) print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency').'</td>';
  2944. print '<td class="linecoledit"></td>'; // No width to allow autodim
  2945. print '<td class="linecoldelete" width="10"></td>';
  2946. print '<td class="linecolmove" width="10"></td>';
  2947. print "</tr>\n";
  2948. $num = count($this->lines);
  2949. $var = true;
  2950. $i = 0;
  2951. //Line extrafield
  2952. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  2953. $extrafieldsline = new ExtraFields($this->db);
  2954. $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
  2955. foreach ($this->lines as $line)
  2956. {
  2957. //Line extrafield
  2958. $line->fetch_optionals($line->id,$extralabelslines);
  2959. $var=!$var;
  2960. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  2961. if (is_object($hookmanager)) // Old code is commented on preceding line.
  2962. {
  2963. if (empty($line->fk_parent_line))
  2964. {
  2965. $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
  2966. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2967. }
  2968. else
  2969. {
  2970. $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
  2971. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2972. }
  2973. }
  2974. if (empty($reshook))
  2975. {
  2976. $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
  2977. }
  2978. $i++;
  2979. }
  2980. }
  2981. /**
  2982. * Return HTML content of a detail line
  2983. * TODO Move this into an output class file (htmlline.class.php)
  2984. *
  2985. * @param string $action GET/POST action
  2986. * @param CommonObjectLine $line Selected object line to output
  2987. * @param string $var Is it a an odd line (true)
  2988. * @param int $num Number of line (0)
  2989. * @param int $i I
  2990. * @param int $dateSelector 1=Show also date range input fields
  2991. * @param string $seller Object of seller third party
  2992. * @param string $buyer Object of buyer third party
  2993. * @param int $selected Object line selected
  2994. * @param int $extrafieldsline Object of extrafield line attribute
  2995. * @return void
  2996. */
  2997. function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
  2998. {
  2999. global $conf,$langs,$user,$object,$hookmanager;
  3000. global $form,$bc,$bcdd;
  3001. global $object_rights, $disableedit, $disablemove; // TODO We should not use global var for this !
  3002. $object_rights = $this->getRights();
  3003. $element=$this->element;
  3004. $text=''; $description=''; $type=0;
  3005. // Show product and description
  3006. $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
  3007. // Try to enhance type detection using date_start and date_end for free lines where type was not saved.
  3008. if (! empty($line->date_start)) $type=1; // deprecated
  3009. if (! empty($line->date_end)) $type=1; // deprecated
  3010. // Ligne en mode visu
  3011. if ($action != 'editline' || $selected != $line->id)
  3012. {
  3013. // Product
  3014. if ($line->fk_product > 0)
  3015. {
  3016. $product_static = new Product($this->db);
  3017. $product_static->fetch($line->fk_product);
  3018. $product_static->ref = $line->ref; //can change ref in hook
  3019. $product_static->label = $line->label; //can change label in hook
  3020. $text=$product_static->getNomUrl(1);
  3021. // Define output language and label
  3022. if (! empty($conf->global->MAIN_MULTILANGS))
  3023. {
  3024. if (! is_object($this->thirdparty))
  3025. {
  3026. dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  3027. return;
  3028. }
  3029. $prod = new Product($this->db);
  3030. $prod->fetch($line->fk_product);
  3031. $outputlangs = $langs;
  3032. $newlang='';
  3033. if (empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
  3034. if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang; // For language to language of customer
  3035. if (! empty($newlang))
  3036. {
  3037. $outputlangs = new Translate("",$conf);
  3038. $outputlangs->setDefaultLang($newlang);
  3039. }
  3040. $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  3041. }
  3042. else
  3043. {
  3044. $label = $line->product_label;
  3045. }
  3046. $text.= ' - '.(! empty($line->label)?$line->label:$label);
  3047. $description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
  3048. }
  3049. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
  3050. // Output template part (modules that overwrite templates must declare this into descriptor)
  3051. // Use global variables + $dateSelector + $seller and $buyer
  3052. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3053. foreach($dirtpls as $reldir)
  3054. {
  3055. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  3056. if (empty($conf->file->strict_mode)) {
  3057. $res=@include $tpl;
  3058. } else {
  3059. $res=include $tpl; // for debug
  3060. }
  3061. if ($res) break;
  3062. }
  3063. }
  3064. // Ligne en mode update
  3065. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
  3066. {
  3067. $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  3068. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("Label").'"';
  3069. else $placeholder=' title="'.$langs->trans("Label").'"';
  3070. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
  3071. // Output template part (modules that overwrite templates must declare this into descriptor)
  3072. // Use global variables + $dateSelector + $seller and $buyer
  3073. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3074. foreach($dirtpls as $reldir)
  3075. {
  3076. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  3077. if (empty($conf->file->strict_mode)) {
  3078. $res=@include $tpl;
  3079. } else {
  3080. $res=include $tpl; // for debug
  3081. }
  3082. if ($res) break;
  3083. }
  3084. }
  3085. }
  3086. /* This is to show array of line of details of source object */
  3087. /**
  3088. * Return HTML table table of source object lines
  3089. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3090. * If lines are into a template, title must also be into a template
  3091. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3092. *
  3093. * @return void
  3094. */
  3095. function printOriginLinesList()
  3096. {
  3097. global $langs, $hookmanager, $conf;
  3098. print '<tr class="liste_titre">';
  3099. print '<td>'.$langs->trans('Ref').'</td>';
  3100. print '<td>'.$langs->trans('Description').'</td>';
  3101. print '<td align="right">'.$langs->trans('VAT').'</td>';
  3102. print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
  3103. if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  3104. print '<td align="right">'.$langs->trans('Qty').'</td>';
  3105. if($conf->global->PRODUCT_USE_UNITS)
  3106. {
  3107. print '<td align="left">'.$langs->trans('Unit').'</td>';
  3108. }
  3109. print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
  3110. $var = true;
  3111. $i = 0;
  3112. foreach ($this->lines as $line)
  3113. {
  3114. $var=!$var;
  3115. if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3116. {
  3117. if (empty($line->fk_parent_line))
  3118. {
  3119. $parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
  3120. $action='';
  3121. $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  3122. }
  3123. }
  3124. else
  3125. {
  3126. $this->printOriginLine($line,$var);
  3127. }
  3128. $i++;
  3129. }
  3130. }
  3131. /**
  3132. * Return HTML with a line of table array of source object lines
  3133. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3134. * If lines are into a template, title must also be into a template
  3135. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3136. *
  3137. * @param CommonObjectLine $line Line
  3138. * @param string $var Var
  3139. * @return void
  3140. */
  3141. function printOriginLine($line,$var)
  3142. {
  3143. global $langs, $conf;
  3144. //var_dump($line);
  3145. if (!empty($line->date_start))
  3146. {
  3147. $date_start=$line->date_start;
  3148. }
  3149. else
  3150. {
  3151. $date_start=$line->date_debut_prevue;
  3152. if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
  3153. }
  3154. if (!empty($line->date_end))
  3155. {
  3156. $date_end=$line->date_end;
  3157. }
  3158. else
  3159. {
  3160. $date_end=$line->date_fin_prevue;
  3161. if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
  3162. }
  3163. $this->tpl['label'] = '';
  3164. if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
  3165. if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object
  3166. {
  3167. $discount=new DiscountAbsolute($this->db);
  3168. $discount->fk_soc = $this->socid;
  3169. $this->tpl['label'].= $discount->getNomUrl(0,'discount');
  3170. }
  3171. else if (! empty($line->fk_product))
  3172. {
  3173. $productstatic = new Product($this->db);
  3174. $productstatic->id = $line->fk_product;
  3175. $productstatic->ref = $line->ref;
  3176. $productstatic->type = $line->fk_product_type;
  3177. $this->tpl['label'].= $productstatic->getNomUrl(1);
  3178. $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
  3179. // Dates
  3180. if ($line->product_type == 1 && ($date_start || $date_end))
  3181. {
  3182. $this->tpl['label'].= get_date_range($date_start,$date_end);
  3183. }
  3184. }
  3185. else
  3186. {
  3187. $this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
  3188. if (!empty($line->desc)) {
  3189. $this->tpl['label'].=$line->desc;
  3190. }else {
  3191. $this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
  3192. }
  3193. // Dates
  3194. if ($line->product_type == 1 && ($date_start || $date_end))
  3195. {
  3196. $this->tpl['label'].= get_date_range($date_start,$date_end);
  3197. }
  3198. }
  3199. if (! empty($line->desc))
  3200. {
  3201. if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object
  3202. {
  3203. $discount=new DiscountAbsolute($this->db);
  3204. $discount->fetch($line->fk_remise_except);
  3205. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
  3206. }
  3207. elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object
  3208. {
  3209. $discount=new DiscountAbsolute($this->db);
  3210. $discount->fetch($line->fk_remise_except);
  3211. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
  3212. }
  3213. else
  3214. {
  3215. $this->tpl['description'] = dol_trunc($line->desc,60);
  3216. }
  3217. }
  3218. else
  3219. {
  3220. $this->tpl['description'] = '&nbsp;';
  3221. }
  3222. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  3223. $this->tpl['price'] = price($line->subprice);
  3224. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  3225. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  3226. if($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $line->getLabelOfUnit('long');
  3227. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  3228. // Output template part (modules that overwrite templates must declare this into descriptor)
  3229. // Use global variables + $dateSelector + $seller and $buyer
  3230. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3231. foreach($dirtpls as $reldir)
  3232. {
  3233. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  3234. if (empty($conf->file->strict_mode)) {
  3235. $res=@include $tpl;
  3236. } else {
  3237. $res=include $tpl; // for debug
  3238. }
  3239. if ($res) break;
  3240. }
  3241. }
  3242. /**
  3243. * Show the array with all margin infos
  3244. *
  3245. * @param bool $force_price Force price
  3246. * @return void
  3247. * @deprecated 3.8 Load FormMargin class and make a direct call to displayMarginInfos
  3248. */
  3249. function displayMarginInfos($force_price=false)
  3250. {
  3251. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
  3252. $formmargin=new FormMargin($this->db);
  3253. $formmargin->displayMarginInfos($this, $force_price);
  3254. }
  3255. /**
  3256. * Add resources to the current object : add entry into llx_element_resources
  3257. * Need $this->element & $this->id
  3258. *
  3259. * @param int $resource_id Resource id
  3260. * @param string $resource_type 'resource'
  3261. * @param int $busy Busy or not
  3262. * @param int $mandatory Mandatory or not
  3263. * @return int <=0 if KO, >0 if OK
  3264. */
  3265. function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
  3266. {
  3267. $this->db->begin();
  3268. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  3269. $sql.= "resource_id";
  3270. $sql.= ", resource_type";
  3271. $sql.= ", element_id";
  3272. $sql.= ", element_type";
  3273. $sql.= ", busy";
  3274. $sql.= ", mandatory";
  3275. $sql.= ") VALUES (";
  3276. $sql.= $resource_id;
  3277. $sql.= ", '".$resource_type."'";
  3278. $sql.= ", '".$this->id."'";
  3279. $sql.= ", '".$this->element."'";
  3280. $sql.= ", '".$busy."'";
  3281. $sql.= ", '".$mandatory."'";
  3282. $sql.= ")";
  3283. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  3284. if ($this->db->query($sql))
  3285. {
  3286. $this->db->commit();
  3287. return 1;
  3288. }
  3289. else
  3290. {
  3291. $this->error=$this->db->lasterror();
  3292. $this->db->rollback();
  3293. return 0;
  3294. }
  3295. }
  3296. /**
  3297. * Delete a link to resource line
  3298. *
  3299. * @param int $rowid Id of resource line to delete
  3300. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  3301. * @param int $notrigger Disable all triggers
  3302. * @return int >0 if OK, <0 if KO
  3303. */
  3304. function delete_resource($rowid, $element, $notrigger=0)
  3305. {
  3306. global $user;
  3307. $this->db->begin();
  3308. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  3309. $sql.= " WHERE rowid=".$rowid;
  3310. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  3311. $resql=$this->db->query($sql);
  3312. if (! $resql)
  3313. {
  3314. $this->error=$this->db->lasterror();
  3315. $this->db->rollback();
  3316. return -1;
  3317. }
  3318. else
  3319. {
  3320. if (! $notrigger)
  3321. {
  3322. $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  3323. if ($result < 0) { $this->db->rollback(); return -1; }
  3324. }
  3325. $this->db->commit();
  3326. return 1;
  3327. }
  3328. }
  3329. /**
  3330. * Overwrite magic function to solve problem of cloning object that are kept as references
  3331. *
  3332. * @return void
  3333. */
  3334. function __clone()
  3335. {
  3336. // Force a copy of this->lines, otherwise it will point to same object.
  3337. if (isset($this->lines) && is_array($this->lines))
  3338. {
  3339. $nboflines=count($this->lines);
  3340. for($i=0; $i < $nboflines; $i++)
  3341. {
  3342. $this->lines[$i] = clone $this->lines[$i];
  3343. }
  3344. }
  3345. }
  3346. /**
  3347. * Common function for all objects extending CommonObject for generating documents
  3348. *
  3349. * @param string $modelspath Relative folder where generators are placed
  3350. * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
  3351. * @param Translate $outputlangs Language to use
  3352. * @param int $hidedetails 1 to hide details. 0 by default
  3353. * @param int $hidedesc 1 to hide product description. 0 by default
  3354. * @param int $hideref 1 to hide product reference. 0 by default
  3355. * @return int >0 if OK, <0 if KO
  3356. */
  3357. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref)
  3358. {
  3359. global $conf, $langs;
  3360. $srctemplatepath='';
  3361. // Increase limit for PDF build
  3362. $err=error_reporting();
  3363. error_reporting(0);
  3364. @set_time_limit(120);
  3365. error_reporting($err);
  3366. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  3367. $tmp=explode(':',$modele,2);
  3368. if (! empty($tmp[1]))
  3369. {
  3370. $modele=$tmp[0];
  3371. $srctemplatepath=$tmp[1];
  3372. }
  3373. // Search template files
  3374. $file=''; $classname=''; $filefound=0;
  3375. $dirmodels=array('/');
  3376. if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
  3377. foreach($dirmodels as $reldir)
  3378. {
  3379. foreach(array('doc','pdf') as $prefix)
  3380. {
  3381. $file = $prefix."_".$modele.".modules.php";
  3382. // On verifie l'emplacement du modele
  3383. $file=dol_buildpath($reldir.$modelspath.$file,0);
  3384. if (file_exists($file))
  3385. {
  3386. $filefound=1;
  3387. $classname=$prefix.'_'.$modele;
  3388. break;
  3389. }
  3390. }
  3391. if ($filefound) break;
  3392. }
  3393. // If generator was found
  3394. if ($filefound)
  3395. {
  3396. require_once $file;
  3397. $obj = new $classname($this->db);
  3398. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  3399. if ($obj->type == 'odt' && empty($srctemplatepath))
  3400. {
  3401. $varfortemplatedir=$obj->scandir;
  3402. if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir))
  3403. {
  3404. $dirtoscan=$conf->global->$varfortemplatedir;
  3405. $listoffiles=array();
  3406. // Now we add first model found in directories scanned
  3407. $listofdir=explode(',',$dirtoscan);
  3408. foreach($listofdir as $key=>$tmpdir)
  3409. {
  3410. $tmpdir=trim($tmpdir);
  3411. $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
  3412. if (! $tmpdir) { unset($listofdir[$key]); continue; }
  3413. if (is_dir($tmpdir))
  3414. {
  3415. $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
  3416. if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
  3417. }
  3418. }
  3419. if (count($listoffiles))
  3420. {
  3421. foreach($listoffiles as $record)
  3422. {
  3423. $srctemplatepath=$record['fullname'];
  3424. break;
  3425. }
  3426. }
  3427. }
  3428. if (empty($srctemplatepath))
  3429. {
  3430. $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  3431. return -1;
  3432. }
  3433. }
  3434. if ($obj->type == 'odt' && ! empty($srctemplatepath))
  3435. {
  3436. if (! dol_is_file($srctemplatepath))
  3437. {
  3438. $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  3439. return -1;
  3440. }
  3441. }
  3442. // We save charset_output to restore it because write_file can change it if needed for
  3443. // output format that does not support UTF8.
  3444. $sav_charset_output=$outputlangs->charset_output;
  3445. if ($obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0)
  3446. {
  3447. $outputlangs->charset_output=$sav_charset_output;
  3448. // We delete old preview
  3449. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3450. dol_delete_preview($this);
  3451. // Success in building document. We build meta file.
  3452. dol_meta_create($this);
  3453. return 1;
  3454. }
  3455. else
  3456. {
  3457. $outputlangs->charset_output=$sav_charset_output;
  3458. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  3459. return -1;
  3460. }
  3461. }
  3462. else
  3463. {
  3464. $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
  3465. dol_print_error('',$this->error);
  3466. return -1;
  3467. }
  3468. }
  3469. /**
  3470. * Build thumb
  3471. *
  3472. * @param string $file Path file in UTF8 to original file to create thumbs from.
  3473. * @return void
  3474. */
  3475. function addThumbs($file)
  3476. {
  3477. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  3478. require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  3479. $file_osencoded=dol_osencode($file);
  3480. if (file_exists($file_osencoded))
  3481. {
  3482. // Create small thumbs for company (Ratio is near 16/9)
  3483. // Used on logon for example
  3484. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  3485. // Create mini thumbs for company (Ratio is near 16/9)
  3486. // Used on menu or for setup page for example
  3487. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  3488. }
  3489. }
  3490. /* Functions common to commonobject and commonobjectline */
  3491. /* For default values */
  3492. /**
  3493. * Return the default value to use for a field when showing the create form of object.
  3494. * Return values in this order:
  3495. * 1) If parameter is available into POST, we return it first.
  3496. * 2) If not but an alternate value was provided as parameter of function, we return it.
  3497. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  3498. * 4) Return value found into database (TODO No yet implemented)
  3499. *
  3500. * @param string $fieldname Name of field
  3501. * @param string $alternatevalue Alternate value to use
  3502. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  3503. **/
  3504. function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
  3505. {
  3506. global $conf, $_POST;
  3507. // If param here has been posted, we use this value first.
  3508. if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
  3509. if (isset($alternatevalue)) return $alternatevalue;
  3510. $newelement=$this->element;
  3511. if ($newelement == 'facture') $newelement='invoice';
  3512. if ($newelement == 'commande') $newelement='order';
  3513. if (empty($newelement))
  3514. {
  3515. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  3516. return '';
  3517. }
  3518. $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
  3519. //var_dump($keyforfieldname);
  3520. if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
  3521. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  3522. }
  3523. /* For triggers */
  3524. /**
  3525. * Call trigger based on this instance.
  3526. * Some context information may also be provided into array property this->context.
  3527. * NB: Error from trigger are stacked in interface->errors
  3528. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  3529. *
  3530. * @param string $trigger_name trigger's name to execute
  3531. * @param User $user Object user
  3532. * @return int Result of run_triggers
  3533. */
  3534. function call_trigger($trigger_name, $user)
  3535. {
  3536. global $langs,$conf;
  3537. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  3538. $interface=new Interfaces($this->db);
  3539. $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
  3540. if ($result < 0)
  3541. {
  3542. if (!empty($this->errors))
  3543. {
  3544. $this->errors=array_unique(array_merge($this->errors,$interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
  3545. }
  3546. else
  3547. {
  3548. $this->errors=$interface->errors;
  3549. }
  3550. }
  3551. return $result;
  3552. }
  3553. /* Functions for extrafields */
  3554. /**
  3555. * Function to get extra fields of a member into $this->array_options
  3556. * This method is in most cases called by method fetch of objects but you can call it separately.
  3557. *
  3558. * @param int $rowid Id of line
  3559. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label()
  3560. * @return int <0 if error, 0 if no optionals to find nor found, 1 if a line is found and optional loaded
  3561. */
  3562. function fetch_optionals($rowid=null,$optionsArray=null)
  3563. {
  3564. if (empty($rowid)) $rowid=$this->id;
  3565. //To avoid SQL errors. Probably not the better solution though
  3566. if (!$this->table_element) {
  3567. return 0;
  3568. }
  3569. if (! is_array($optionsArray))
  3570. {
  3571. // optionsArray not already loaded, so we load it
  3572. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3573. $extrafields = new ExtraFields($this->db);
  3574. $optionsArray = $extrafields->fetch_name_optionals_label($this->table_element);
  3575. }
  3576. // Request to get complementary values
  3577. if (count($optionsArray) > 0)
  3578. {
  3579. $sql = "SELECT rowid";
  3580. foreach ($optionsArray as $name => $label)
  3581. {
  3582. $sql.= ", ".$name;
  3583. }
  3584. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields";
  3585. $sql.= " WHERE fk_object = ".$rowid;
  3586. dol_syslog(get_class($this)."::fetch_optionals", LOG_DEBUG);
  3587. $resql=$this->db->query($sql);
  3588. if ($resql)
  3589. {
  3590. $numrows=$this->db->num_rows($resql);
  3591. if ($numrows)
  3592. {
  3593. $tab = $this->db->fetch_array($resql);
  3594. foreach ($tab as $key => $value)
  3595. {
  3596. // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine)
  3597. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
  3598. {
  3599. // we can add this attribute to object
  3600. $this->array_options["options_".$key]=$value;
  3601. }
  3602. }
  3603. }
  3604. $this->db->free($resql);
  3605. if ($numrows) return $numrows;
  3606. else return 0;
  3607. }
  3608. else
  3609. {
  3610. dol_print_error($this->db);
  3611. return -1;
  3612. }
  3613. }
  3614. return 0;
  3615. }
  3616. /**
  3617. * Delete all extra fields values for the current object.
  3618. *
  3619. * @return int <0 if KO, >0 if OK
  3620. */
  3621. function deleteExtraFields()
  3622. {
  3623. $this->db->begin();
  3624. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  3625. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  3626. $resql=$this->db->query($sql_del);
  3627. if (! $resql)
  3628. {
  3629. $this->error=$this->db->lasterror();
  3630. $this->db->rollback();
  3631. return -1;
  3632. }
  3633. else
  3634. {
  3635. $this->db->commit();
  3636. return 1;
  3637. }
  3638. }
  3639. /**
  3640. * Add/Update all extra fields values for the current object.
  3641. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  3642. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  3643. *
  3644. * @return int -1=error, O=did nothing, 1=OK
  3645. */
  3646. function insertExtraFields()
  3647. {
  3648. global $conf,$langs;
  3649. $error=0;
  3650. if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
  3651. if (! empty($this->array_options))
  3652. {
  3653. // Check parameters
  3654. $langs->load('admin');
  3655. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3656. $extrafields = new ExtraFields($this->db);
  3657. $extrafields->fetch_name_optionals_label($this->table_element);
  3658. foreach($this->array_options as $key => $value)
  3659. {
  3660. $attributeKey = substr($key,8); // Remove 'options_' prefix
  3661. $attributeType = $extrafields->attribute_type[$attributeKey];
  3662. $attributeLabel = $extrafields->attribute_label[$attributeKey];
  3663. $attributeParam = $extrafields->attribute_param[$attributeKey];
  3664. switch ($attributeType)
  3665. {
  3666. case 'int':
  3667. if (!is_numeric($value) && $value!='')
  3668. {
  3669. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
  3670. return -1;
  3671. }
  3672. elseif ($value=='')
  3673. {
  3674. $this->array_options[$key] = null;
  3675. }
  3676. break;
  3677. case 'price':
  3678. $this->array_options[$key] = price2num($this->array_options[$key]);
  3679. break;
  3680. case 'date':
  3681. $this->array_options[$key]=$this->db->idate($this->array_options[$key]);
  3682. break;
  3683. case 'datetime':
  3684. $this->array_options[$key]=$this->db->idate($this->array_options[$key]);
  3685. break;
  3686. case 'link':
  3687. $param_list=array_keys($attributeParam ['options']);
  3688. // 0 : ObjectName
  3689. // 1 : classPath
  3690. $InfoFieldList = explode(":", $param_list[0]);
  3691. dol_include_once($InfoFieldList[1]);
  3692. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  3693. {
  3694. $object = new $InfoFieldList[0]($this->db);
  3695. if ($value)
  3696. {
  3697. $res=$object->fetch(0,$value);
  3698. if ($res > 0) $this->array_options[$key]=$object->id;
  3699. else
  3700. {
  3701. $this->error="Ref '".$value."' for object '".$object->element."' not found";
  3702. $this->db->rollback();
  3703. return -1;
  3704. }
  3705. }
  3706. }
  3707. else
  3708. {
  3709. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  3710. }
  3711. break;
  3712. }
  3713. }
  3714. $this->db->begin();
  3715. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  3716. dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
  3717. $this->db->query($sql_del);
  3718. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."_extrafields (fk_object";
  3719. foreach($this->array_options as $key => $value)
  3720. {
  3721. $attributeKey = substr($key,8); // Remove 'options_' prefix
  3722. // Add field of attribut
  3723. if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate
  3724. $sql.=",".$attributeKey;
  3725. }
  3726. $sql .= ") VALUES (".$this->id;
  3727. foreach($this->array_options as $key => $value)
  3728. {
  3729. $attributeKey = substr($key,8); // Remove 'options_' prefix
  3730. // Add field o fattribut
  3731. if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate)
  3732. {
  3733. if ($this->array_options[$key] != '')
  3734. {
  3735. $sql.=",'".$this->db->escape($this->array_options[$key])."'";
  3736. }
  3737. else
  3738. {
  3739. $sql.=",null";
  3740. }
  3741. }
  3742. }
  3743. $sql.=")";
  3744. dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
  3745. $resql = $this->db->query($sql);
  3746. if (! $resql)
  3747. {
  3748. $this->error=$this->db->lasterror();
  3749. $this->db->rollback();
  3750. return -1;
  3751. }
  3752. else
  3753. {
  3754. $this->db->commit();
  3755. return 1;
  3756. }
  3757. }
  3758. else return 0;
  3759. }
  3760. /**
  3761. * Update an exta field value for the current object.
  3762. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  3763. * This function delte record with all extrafields and insert them again from the array $this->array_options.
  3764. *
  3765. * @param string $key Key of the extrafield
  3766. * @return int -1=error, O=did nothing, 1=OK
  3767. */
  3768. function updateExtraField($key)
  3769. {
  3770. global $conf,$langs;
  3771. $error=0;
  3772. if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
  3773. if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
  3774. {
  3775. // Check parameters
  3776. $langs->load('admin');
  3777. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3778. $extrafields = new ExtraFields($this->db);
  3779. $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
  3780. $value=$this->array_options["options_".$key];
  3781. $attributeType = $extrafields->attribute_type[$key];
  3782. $attributeLabel = $extrafields->attribute_label[$key];
  3783. $attributeParam = $extrafields->attribute_param[$key];
  3784. switch ($attributeType)
  3785. {
  3786. case 'int':
  3787. if (!is_numeric($value) && $value!='')
  3788. {
  3789. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
  3790. return -1;
  3791. }
  3792. elseif ($value=='')
  3793. {
  3794. $this->array_options["options_".$key] = null;
  3795. }
  3796. break;
  3797. case 'price':
  3798. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  3799. break;
  3800. case 'date':
  3801. $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
  3802. break;
  3803. case 'datetime':
  3804. $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
  3805. break;
  3806. case 'link':
  3807. $param_list=array_keys($attributeParam ['options']);
  3808. // 0 : ObjectName
  3809. // 1 : classPath
  3810. $InfoFieldList = explode(":", $param_list[0]);
  3811. dol_include_once($InfoFieldList[1]);
  3812. $object = new $InfoFieldList[0]($this->db);
  3813. if ($value)
  3814. {
  3815. $object->fetch(0,$value);
  3816. $this->array_options["options_".$key]=$object->id;
  3817. }
  3818. break;
  3819. }
  3820. $this->db->begin();
  3821. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
  3822. $sql .= " WHERE fk_object = ".$this->id;
  3823. $resql = $this->db->query($sql);
  3824. if (! $resql)
  3825. {
  3826. $this->error=$this->db->lasterror();
  3827. $this->db->rollback();
  3828. return -1;
  3829. }
  3830. else
  3831. {
  3832. $this->db->commit();
  3833. return 1;
  3834. }
  3835. }
  3836. else return 0;
  3837. }
  3838. /**
  3839. * Function to show lines of extrafields with output datas
  3840. *
  3841. * @param Extrafields $extrafields Extrafield Object
  3842. * @param string $mode Show output (view) or input (edit) for extrafield
  3843. * @param array $params Optional parameters
  3844. * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  3845. *
  3846. * @return string
  3847. */
  3848. function showOptionals($extrafields, $mode='view', $params=null, $keyprefix='')
  3849. {
  3850. global $_POST, $conf, $langs;
  3851. $out = '';
  3852. if (count($extrafields->attribute_label) > 0)
  3853. {
  3854. $out .= "\n";
  3855. $out .= '<!-- showOptionalsInput --> ';
  3856. $out .= "\n";
  3857. $e = 0;
  3858. foreach($extrafields->attribute_label as $key=>$label)
  3859. {
  3860. if (is_array($params) && count($params)>0) {
  3861. if (array_key_exists('colspan',$params)) {
  3862. $colspan=$params['colspan'];
  3863. }
  3864. }else {
  3865. $colspan='3';
  3866. }
  3867. switch($mode) {
  3868. case "view":
  3869. $value=$this->array_options["options_".$key];
  3870. break;
  3871. case "edit":
  3872. if (isset($_POST["options_" . $key])) {
  3873. if (is_array($_POST["options_" . $key])) {
  3874. // $_POST["options"] is an array but following code expects a comma separated string
  3875. $value = implode(",", $_POST["options_" . $key]);
  3876. } else {
  3877. $value = $_POST["options_" . $key];
  3878. }
  3879. } else {
  3880. $value = $this->array_options["options_" . $key];
  3881. }
  3882. break;
  3883. }
  3884. if ($extrafields->attribute_type[$key] == 'separate')
  3885. {
  3886. $out .= $extrafields->showSeparator($key);
  3887. }
  3888. else
  3889. {
  3890. $csstyle='';
  3891. $class=(!empty($extrafields->attribute_hidden[$key]) ? 'class="hideobject" ' : '');
  3892. if (is_array($params) && count($params)>0) {
  3893. if (array_key_exists('style',$params)) {
  3894. $csstyle=$params['style'];
  3895. }
  3896. }
  3897. if ( !empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
  3898. {
  3899. $out .= '<tr '.$class.$csstyle.'>';
  3900. $colspan='0';
  3901. }
  3902. else
  3903. {
  3904. $out .= '<tr '.$class.$csstyle.'>';
  3905. }
  3906. // Convert date into timestamp format
  3907. if (in_array($extrafields->attribute_type[$key],array('date','datetime')))
  3908. {
  3909. $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$this->db->jdate($this->array_options['options_'.$key]);
  3910. }
  3911. if($extrafields->attribute_required[$key])
  3912. $label = '<span'.($mode != 'view' ? ' class="fieldrequired"':'').'>'.$label.'</span>';
  3913. $out .= '<td>'.$langs->trans($label).'</td>';
  3914. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  3915. $out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
  3916. switch($mode) {
  3917. case "view":
  3918. $out .= $extrafields->showOutputField($key,$value);
  3919. break;
  3920. case "edit":
  3921. $out .= $extrafields->showInputField($key,$value,'',$keyprefix,'',0,$this->id);
  3922. break;
  3923. }
  3924. $out .= '</td>';
  3925. if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
  3926. else $out .= '</tr>';
  3927. $e++;
  3928. }
  3929. }
  3930. $out .= "\n";
  3931. $out .= '
  3932. <script type="text/javascript">
  3933. jQuery(document).ready(function() {
  3934. function showOptions(child_list, parent_list)
  3935. {
  3936. var val = $("select[name=\"options_"+parent_list+"\"]").val();
  3937. var parentVal = parent_list + ":" + val;
  3938. if(val > 0) {
  3939. $("select[name=\""+child_list+"\"] option[parent]").hide();
  3940. $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
  3941. } else {
  3942. $("select[name=\""+child_list+"\"] option").show();
  3943. }
  3944. }
  3945. function setListDependencies() {
  3946. jQuery("select option[parent]").parent().each(function() {
  3947. var child_list = $(this).attr("name");
  3948. var parent = $(this).find("option[parent]:first").attr("parent");
  3949. var infos = parent.split(":");
  3950. var parent_list = infos[0];
  3951. $("select[name=\"options_"+parent_list+"\"]").change(function() {
  3952. showOptions(child_list, parent_list);
  3953. });
  3954. });
  3955. }
  3956. setListDependencies();
  3957. });
  3958. </script>'."\n";
  3959. $out .= '<!-- /showOptionalsInput --> '."\n";
  3960. }
  3961. return $out;
  3962. }
  3963. /**
  3964. * Returns the rights used for this class
  3965. * @return stdClass
  3966. */
  3967. public function getRights()
  3968. {
  3969. global $user;
  3970. $element = $this->element;
  3971. if ($element == 'facturerec') $element='facture';
  3972. return $user->rights->{$element};
  3973. }
  3974. /**
  3975. * Function used to replace a thirdparty id with another one.
  3976. * This function is meant to be called from replaceThirdparty with the appropiate tables
  3977. * Column name fk_soc MUST be used to identify thirdparties
  3978. *
  3979. * @param DoliDB $db Database handler
  3980. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  3981. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  3982. * @param string[] $tables Tables that need to be changed
  3983. * @param int $ignoreerrors Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old thirdparty may already exists on new one)
  3984. * @return bool
  3985. */
  3986. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
  3987. {
  3988. foreach ($tables as $table)
  3989. {
  3990. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
  3991. if (! $db->query($sql))
  3992. {
  3993. if ($ignoreerrors) return true;
  3994. //$this->errors = $db->lasterror();
  3995. return false;
  3996. }
  3997. }
  3998. return true;
  3999. }
  4000. /**
  4001. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  4002. * set buy price = sell price if ForceBuyingPriceIfNull configured,
  4003. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  4004. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  4005. * else set min buy price as buy price
  4006. *
  4007. * @param float $unitPrice product unit price
  4008. * @param float $discountPercent line discount percent
  4009. * @param int $fk_product product id
  4010. *
  4011. * @return float <0 if ko, buyprice if ok
  4012. */
  4013. public function defineBuyPrice($unitPrice = 0, $discountPercent = 0, $fk_product = 0)
  4014. {
  4015. global $conf;
  4016. $buyPrice = 0;
  4017. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
  4018. {
  4019. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  4020. }
  4021. else
  4022. {
  4023. // Get cost price for margin calculation
  4024. if (! empty($fk_product))
  4025. {
  4026. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
  4027. {
  4028. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4029. $product = new Product($this->db);
  4030. $result = $product->fetch($fk_product);
  4031. if ($result <= 0)
  4032. {
  4033. $this->errors[] = 'ErrorProductIdDoesNotExists';
  4034. return -1;
  4035. }
  4036. if ($product->cost_price > 0)
  4037. {
  4038. $buyPrice = $product->cost_price;
  4039. }
  4040. else if ($product->pmp > 0)
  4041. {
  4042. $buyPrice = $product->pmp;
  4043. }
  4044. }
  4045. else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
  4046. {
  4047. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4048. $product = new Product($this->db);
  4049. $result = $product->fetch($fk_product);
  4050. if ($result <= 0)
  4051. {
  4052. $this->errors[] = 'ErrorProductIdDoesNotExists';
  4053. return -1;
  4054. }
  4055. if ($product->pmp > 0)
  4056. {
  4057. $buyPrice = $product->pmp;
  4058. }
  4059. }
  4060. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
  4061. {
  4062. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  4063. $productFournisseur = new ProductFournisseur($this->db);
  4064. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
  4065. {
  4066. $buyPrice = $productFournisseur->fourn_unitprice;
  4067. }
  4068. else if ($result < 0)
  4069. {
  4070. $this->errors[] = $productFournisseur->error;
  4071. return -2;
  4072. }
  4073. }
  4074. }
  4075. }
  4076. return $buyPrice;
  4077. }
  4078. }