commonobject.class.php 164 KB

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