commonobject.class.php 173 KB

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