commonobject.class.php 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071
  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').")";
  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. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  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))
  1176. {
  1177. if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility
  1178. $sql.=$filter;
  1179. }
  1180. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
  1181. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')';
  1182. //print $filter.' '.$sql."<br>";
  1183. $result = $this->db->query($sql);
  1184. if (! $result)
  1185. {
  1186. $this->error=$this->db->lasterror();
  1187. return -1;
  1188. }
  1189. $row = $this->db->fetch_row($result);
  1190. $this->ref_previous = $row[0];
  1191. $sql = "SELECT MIN(te.".$fieldid.")";
  1192. $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1193. 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
  1194. 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";
  1195. $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1196. if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id;
  1197. if (! empty($filter))
  1198. {
  1199. if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility
  1200. $sql.=$filter;
  1201. }
  1202. 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
  1203. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')';
  1204. // 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
  1205. //print $sql."<br>";
  1206. $result = $this->db->query($sql);
  1207. if (! $result)
  1208. {
  1209. $this->error=$this->db->lasterror();
  1210. return -2;
  1211. }
  1212. $row = $this->db->fetch_row($result);
  1213. $this->ref_next = $row[0];
  1214. return 1;
  1215. }
  1216. /**
  1217. * Return list of id of contacts of project
  1218. *
  1219. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1220. * @return array Array of id of contacts (if source=external or internal)
  1221. * Array of id of third parties with at least one contact on project (if source=thirdparty)
  1222. */
  1223. function getListContactId($source='external')
  1224. {
  1225. $contactAlreadySelected = array();
  1226. $tab = $this->liste_contact(-1,$source);
  1227. $num=count($tab);
  1228. $i = 0;
  1229. while ($i < $num)
  1230. {
  1231. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1232. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  1233. $i++;
  1234. }
  1235. return $contactAlreadySelected;
  1236. }
  1237. /**
  1238. * Link element with a project
  1239. *
  1240. * @param int $projectid Project id to link element to
  1241. * @return int <0 if KO, >0 if OK
  1242. */
  1243. function setProject($projectid)
  1244. {
  1245. if (! $this->table_element)
  1246. {
  1247. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR);
  1248. return -1;
  1249. }
  1250. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1251. if ($this->table_element == 'actioncomm')
  1252. {
  1253. if ($projectid) $sql.= ' SET fk_project = '.$projectid;
  1254. else $sql.= ' SET fk_project = NULL';
  1255. $sql.= ' WHERE id = '.$this->id;
  1256. }
  1257. else
  1258. {
  1259. if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
  1260. else $sql.= ' SET fk_projet = NULL';
  1261. $sql.= ' WHERE rowid = '.$this->id;
  1262. }
  1263. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1264. if ($this->db->query($sql))
  1265. {
  1266. $this->fk_project = $projectid;
  1267. return 1;
  1268. }
  1269. else
  1270. {
  1271. dol_print_error($this->db);
  1272. return -1;
  1273. }
  1274. }
  1275. /**
  1276. * Change the payments methods
  1277. *
  1278. * @param int $id Id of new payment method
  1279. * @return int >0 if OK, <0 if KO
  1280. */
  1281. function setPaymentMethods($id)
  1282. {
  1283. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1284. if ($this->statut >= 0 || $this->element == 'societe')
  1285. {
  1286. // TODO uniformize field name
  1287. $fieldname = 'fk_mode_reglement';
  1288. if ($this->element == 'societe') $fieldname = 'mode_reglement';
  1289. if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
  1290. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1291. $sql .= ' SET '.$fieldname.' = '.$id;
  1292. $sql .= ' WHERE rowid='.$this->id;
  1293. if ($this->db->query($sql))
  1294. {
  1295. $this->mode_reglement_id = $id;
  1296. // for supplier
  1297. if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
  1298. return 1;
  1299. }
  1300. else
  1301. {
  1302. dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
  1303. $this->error=$this->db->error();
  1304. return -1;
  1305. }
  1306. }
  1307. else
  1308. {
  1309. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  1310. $this->error='Status of the object is incompatible '.$this->statut;
  1311. return -2;
  1312. }
  1313. }
  1314. /**
  1315. * Change the multicurrency code
  1316. *
  1317. * @param string $code multicurrency code
  1318. * @return int >0 if OK, <0 if KO
  1319. */
  1320. function setMulticurrencyCode($code)
  1321. {
  1322. dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')');
  1323. if ($this->statut >= 0 || $this->element == 'societe')
  1324. {
  1325. $fieldname = 'multicurrency_code';
  1326. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1327. $sql .= ' SET '.$fieldname.' = "'.$this->db->escape($code).'"';
  1328. $sql .= ' WHERE rowid='.$this->id;
  1329. if ($this->db->query($sql))
  1330. {
  1331. $this->multicurrency_code = $code;
  1332. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  1333. if ($rate) $this->setMulticurrencyRate($rate);
  1334. return 1;
  1335. }
  1336. else
  1337. {
  1338. dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
  1339. $this->error=$this->db->error();
  1340. return -1;
  1341. }
  1342. }
  1343. else
  1344. {
  1345. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  1346. $this->error='Status of the object is incompatible '.$this->statut;
  1347. return -2;
  1348. }
  1349. }
  1350. /**
  1351. * Change the multicurrency rate
  1352. *
  1353. * @param double $rate multicurrency rate
  1354. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency
  1355. * @return int >0 if OK, <0 if KO
  1356. */
  1357. function setMulticurrencyRate($rate, $mode=1)
  1358. {
  1359. dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')');
  1360. if ($this->statut >= 0 || $this->element == 'societe')
  1361. {
  1362. $fieldname = 'multicurrency_tx';
  1363. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1364. $sql .= ' SET '.$fieldname.' = '.$rate;
  1365. $sql .= ' WHERE rowid='.$this->id;
  1366. if ($this->db->query($sql))
  1367. {
  1368. $this->multicurrency_tx = $rate;
  1369. // Update line price
  1370. if (!empty($this->lines))
  1371. {
  1372. foreach ($this->lines as &$line)
  1373. {
  1374. if($mode == 1) {
  1375. $line->subprice = 0;
  1376. }
  1377. switch ($this->element) {
  1378. case 'propal':
  1379. $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);
  1380. break;
  1381. case 'commande':
  1382. $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);
  1383. break;
  1384. case 'facture':
  1385. $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);
  1386. break;
  1387. case 'supplier_proposal':
  1388. $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);
  1389. break;
  1390. case 'order_supplier':
  1391. $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);
  1392. break;
  1393. case 'invoice_supplier':
  1394. $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);
  1395. break;
  1396. default:
  1397. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  1398. break;
  1399. }
  1400. }
  1401. }
  1402. return 1;
  1403. }
  1404. else
  1405. {
  1406. dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
  1407. $this->error=$this->db->error();
  1408. return -1;
  1409. }
  1410. }
  1411. else
  1412. {
  1413. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  1414. $this->error='Status of the object is incompatible '.$this->statut;
  1415. return -2;
  1416. }
  1417. }
  1418. /**
  1419. * Change the payments terms
  1420. *
  1421. * @param int $id Id of new payment terms
  1422. * @return int >0 if OK, <0 if KO
  1423. */
  1424. function setPaymentTerms($id)
  1425. {
  1426. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  1427. if ($this->statut >= 0 || $this->element == 'societe')
  1428. {
  1429. // TODO uniformize field name
  1430. $fieldname = 'fk_cond_reglement';
  1431. if ($this->element == 'societe') $fieldname = 'cond_reglement';
  1432. if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
  1433. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1434. $sql .= ' SET '.$fieldname.' = '.$id;
  1435. $sql .= ' WHERE rowid='.$this->id;
  1436. if ($this->db->query($sql))
  1437. {
  1438. $this->cond_reglement_id = $id;
  1439. // for supplier
  1440. if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
  1441. $this->cond_reglement = $id; // for compatibility
  1442. return 1;
  1443. }
  1444. else
  1445. {
  1446. dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
  1447. $this->error=$this->db->error();
  1448. return -1;
  1449. }
  1450. }
  1451. else
  1452. {
  1453. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  1454. $this->error='Status of the object is incompatible '.$this->statut;
  1455. return -2;
  1456. }
  1457. }
  1458. /**
  1459. * Define delivery address
  1460. * @deprecated
  1461. *
  1462. * @param int $id Address id
  1463. * @return int <0 si ko, >0 si ok
  1464. */
  1465. function setDeliveryAddress($id)
  1466. {
  1467. $fieldname = 'fk_delivery_address';
  1468. if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
  1469. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
  1470. $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  1471. if ($this->db->query($sql))
  1472. {
  1473. $this->fk_delivery_address = $id;
  1474. return 1;
  1475. }
  1476. else
  1477. {
  1478. $this->error=$this->db->error();
  1479. dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
  1480. return -1;
  1481. }
  1482. }
  1483. /**
  1484. * Change the shipping method
  1485. *
  1486. * @param int $shipping_method_id Id of shipping method
  1487. * @return int 1 if OK, 0 if KO
  1488. */
  1489. function setShippingMethod($shipping_method_id)
  1490. {
  1491. if (! $this->table_element) {
  1492. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR);
  1493. return -1;
  1494. }
  1495. if ($shipping_method_id<0) $shipping_method_id='NULL';
  1496. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  1497. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1498. $sql.= " SET fk_shipping_method = ".$shipping_method_id;
  1499. $sql.= " WHERE rowid=".$this->id;
  1500. if ($this->db->query($sql)) {
  1501. $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id;
  1502. return 1;
  1503. } else {
  1504. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  1505. $this->error=$this->db->error();
  1506. return 0;
  1507. }
  1508. }
  1509. /**
  1510. * Change the warehouse
  1511. *
  1512. * @param int $warehouse_id Id of warehouse
  1513. * @return int 1 if OK, 0 if KO
  1514. */
  1515. function setWarehouse($warehouse_id)
  1516. {
  1517. if (! $this->table_element) {
  1518. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR);
  1519. return -1;
  1520. }
  1521. if ($warehouse_id<0) $warehouse_id='NULL';
  1522. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  1523. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1524. $sql.= " SET fk_warehouse = ".$warehouse_id;
  1525. $sql.= " WHERE rowid=".$this->id;
  1526. if ($this->db->query($sql)) {
  1527. $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id;
  1528. return 1;
  1529. } else {
  1530. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  1531. $this->error=$this->db->error();
  1532. return 0;
  1533. }
  1534. }
  1535. /**
  1536. * Set last model used by doc generator
  1537. *
  1538. * @param User $user User object that make change
  1539. * @param string $modelpdf Modele name
  1540. * @return int <0 if KO, >0 if OK
  1541. */
  1542. function setDocModel($user, $modelpdf)
  1543. {
  1544. if (! $this->table_element)
  1545. {
  1546. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR);
  1547. return -1;
  1548. }
  1549. $newmodelpdf=dol_trunc($modelpdf,255);
  1550. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1551. $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  1552. $sql.= " WHERE rowid = ".$this->id;
  1553. // if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
  1554. // if ($this->element == 'propal') $sql.= " AND fk_statut = 0";
  1555. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  1556. $resql=$this->db->query($sql);
  1557. if ($resql)
  1558. {
  1559. $this->modelpdf=$modelpdf;
  1560. return 1;
  1561. }
  1562. else
  1563. {
  1564. dol_print_error($this->db);
  1565. return 0;
  1566. }
  1567. }
  1568. /**
  1569. * Change the bank account
  1570. *
  1571. * @param int $fk_account Id of bank account
  1572. * @return int 1 if OK, 0 if KO
  1573. */
  1574. function setBankAccount($fk_account)
  1575. {
  1576. if (! $this->table_element) {
  1577. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR);
  1578. return -1;
  1579. }
  1580. if ($fk_account<0) $fk_account='NULL';
  1581. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  1582. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1583. $sql.= " SET fk_account = ".$fk_account;
  1584. $sql.= " WHERE rowid=".$this->id;
  1585. if ($this->db->query($sql)) {
  1586. $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
  1587. return 1;
  1588. } else {
  1589. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  1590. $this->error=$this->db->error();
  1591. return 0;
  1592. }
  1593. }
  1594. // TODO: Move line related operations to CommonObjectLine?
  1595. /**
  1596. * Save a new position (field rang) for details lines.
  1597. * You can choose to set position for lines with already a position or lines without any position defined.
  1598. *
  1599. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  1600. * @param string $rowidorder ASC or DESC
  1601. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1602. * @return int <0 if KO, >0 if OK
  1603. */
  1604. function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
  1605. {
  1606. if (! $this->table_element_line)
  1607. {
  1608. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR);
  1609. return -1;
  1610. }
  1611. if (! $this->fk_element)
  1612. {
  1613. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR);
  1614. return -1;
  1615. }
  1616. // Count number of lines to reorder (according to choice $renum)
  1617. $nl=0;
  1618. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1619. $sql.= ' WHERE '.$this->fk_element.'='.$this->id;
  1620. if (! $renum) $sql.= ' AND rang = 0';
  1621. if ($renum) $sql.= ' AND rang <> 0';
  1622. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  1623. $resql = $this->db->query($sql);
  1624. if ($resql)
  1625. {
  1626. $row = $this->db->fetch_row($resql);
  1627. $nl = $row[0];
  1628. }
  1629. else dol_print_error($this->db);
  1630. if ($nl > 0)
  1631. {
  1632. // The goal of this part is to reorder all lines, with all children lines sharing the same
  1633. // counter that parents.
  1634. $rows=array();
  1635. // We first search all lines that are parent lines (for multilevel details lines)
  1636. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1637. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1638. if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL';
  1639. $sql.= ' ORDER BY rang ASC, rowid '.$rowidorder;
  1640. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  1641. $resql = $this->db->query($sql);
  1642. if ($resql)
  1643. {
  1644. $i=0;
  1645. $num = $this->db->num_rows($resql);
  1646. while ($i < $num)
  1647. {
  1648. $row = $this->db->fetch_row($resql);
  1649. $rows[] = $row[0]; // Add parent line into array rows
  1650. $childrens = $this->getChildrenOfLine($row[0]);
  1651. if (! empty($childrens))
  1652. {
  1653. foreach($childrens as $child)
  1654. {
  1655. array_push($rows, $child);
  1656. }
  1657. }
  1658. $i++;
  1659. }
  1660. // Now we set a new number for each lines (parent and children with children included into parent tree)
  1661. if (! empty($rows))
  1662. {
  1663. foreach($rows as $key => $row)
  1664. {
  1665. $this->updateRangOfLine($row, ($key+1));
  1666. }
  1667. }
  1668. }
  1669. else
  1670. {
  1671. dol_print_error($this->db);
  1672. }
  1673. }
  1674. return 1;
  1675. }
  1676. /**
  1677. * Get children of line
  1678. *
  1679. * @param int $id Id of parent line
  1680. * @return array Array with list of children lines id
  1681. */
  1682. function getChildrenOfLine($id)
  1683. {
  1684. $rows=array();
  1685. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1686. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1687. $sql.= ' AND fk_parent_line = '.$id;
  1688. $sql.= ' ORDER BY rang ASC';
  1689. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  1690. $resql = $this->db->query($sql);
  1691. if ($resql)
  1692. {
  1693. $i=0;
  1694. $num = $this->db->num_rows($resql);
  1695. while ($i < $num)
  1696. {
  1697. $row = $this->db->fetch_row($resql);
  1698. $rows[$i] = $row[0];
  1699. $i++;
  1700. }
  1701. }
  1702. return $rows;
  1703. }
  1704. /**
  1705. * Update a line to have a lower rank
  1706. *
  1707. * @param int $rowid Id of line
  1708. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1709. * @return void
  1710. */
  1711. function line_up($rowid, $fk_parent_line=true)
  1712. {
  1713. $this->line_order(false, 'ASC', $fk_parent_line);
  1714. // Get rang of line
  1715. $rang = $this->getRangOfLine($rowid);
  1716. // Update position of line
  1717. $this->updateLineUp($rowid, $rang);
  1718. }
  1719. /**
  1720. * Update a line to have a higher rank
  1721. *
  1722. * @param int $rowid Id of line
  1723. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1724. * @return void
  1725. */
  1726. function line_down($rowid, $fk_parent_line=true)
  1727. {
  1728. $this->line_order(false, 'ASC', $fk_parent_line);
  1729. // Get rang of line
  1730. $rang = $this->getRangOfLine($rowid);
  1731. // Get max value for rang
  1732. $max = $this->line_max();
  1733. // Update position of line
  1734. $this->updateLineDown($rowid, $rang, $max);
  1735. }
  1736. /**
  1737. * Update position of line (rang)
  1738. *
  1739. * @param int $rowid Id of line
  1740. * @param int $rang Position
  1741. * @return void
  1742. */
  1743. function updateRangOfLine($rowid,$rang)
  1744. {
  1745. $fieldposition = 'rang';
  1746. if ($this->table_element_line == 'ecm_files') $fieldposition = 'position';
  1747. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  1748. $sql.= ' WHERE rowid = '.$rowid;
  1749. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  1750. if (! $this->db->query($sql))
  1751. {
  1752. dol_print_error($this->db);
  1753. }
  1754. }
  1755. /**
  1756. * Update position of line with ajax (rang)
  1757. *
  1758. * @param array $rows Array of rows
  1759. * @return void
  1760. */
  1761. function line_ajaxorder($rows)
  1762. {
  1763. $num = count($rows);
  1764. for ($i = 0 ; $i < $num ; $i++)
  1765. {
  1766. $this->updateRangOfLine($rows[$i], ($i+1));
  1767. }
  1768. }
  1769. /**
  1770. * Update position of line up (rang)
  1771. *
  1772. * @param int $rowid Id of line
  1773. * @param int $rang Position
  1774. * @return void
  1775. */
  1776. function updateLineUp($rowid,$rang)
  1777. {
  1778. if ($rang > 1 )
  1779. {
  1780. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ;
  1781. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1782. $sql.= ' AND rang = '.($rang - 1);
  1783. if ($this->db->query($sql) )
  1784. {
  1785. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1);
  1786. $sql.= ' WHERE rowid = '.$rowid;
  1787. if (! $this->db->query($sql) )
  1788. {
  1789. dol_print_error($this->db);
  1790. }
  1791. }
  1792. else
  1793. {
  1794. dol_print_error($this->db);
  1795. }
  1796. }
  1797. }
  1798. /**
  1799. * Update position of line down (rang)
  1800. *
  1801. * @param int $rowid Id of line
  1802. * @param int $rang Position
  1803. * @param int $max Max
  1804. * @return void
  1805. */
  1806. function updateLineDown($rowid,$rang,$max)
  1807. {
  1808. if ($rang < $max)
  1809. {
  1810. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang;
  1811. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1812. $sql.= ' AND rang = '.($rang+1);
  1813. if ($this->db->query($sql) )
  1814. {
  1815. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1);
  1816. $sql.= ' WHERE rowid = '.$rowid;
  1817. if (! $this->db->query($sql) )
  1818. {
  1819. dol_print_error($this->db);
  1820. }
  1821. }
  1822. else
  1823. {
  1824. dol_print_error($this->db);
  1825. }
  1826. }
  1827. }
  1828. /**
  1829. * Get position of line (rang)
  1830. *
  1831. * @param int $rowid Id of line
  1832. * @return int Value of rang in table of lines
  1833. */
  1834. function getRangOfLine($rowid)
  1835. {
  1836. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1837. $sql.= ' WHERE rowid ='.$rowid;
  1838. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  1839. $resql = $this->db->query($sql);
  1840. if ($resql)
  1841. {
  1842. $row = $this->db->fetch_row($resql);
  1843. return $row[0];
  1844. }
  1845. }
  1846. /**
  1847. * Get rowid of the line relative to its position
  1848. *
  1849. * @param int $rang Rang value
  1850. * @return int Rowid of the line
  1851. */
  1852. function getIdOfLine($rang)
  1853. {
  1854. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1855. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1856. $sql.= ' AND rang = '.$rang;
  1857. $resql = $this->db->query($sql);
  1858. if ($resql)
  1859. {
  1860. $row = $this->db->fetch_row($resql);
  1861. return $row[0];
  1862. }
  1863. }
  1864. /**
  1865. * Get max value used for position of line (rang)
  1866. *
  1867. * @param int $fk_parent_line Parent line id
  1868. * @return int Max value of rang in table of lines
  1869. */
  1870. function line_max($fk_parent_line=0)
  1871. {
  1872. // Search the last rang with fk_parent_line
  1873. if ($fk_parent_line)
  1874. {
  1875. $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1876. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1877. $sql.= ' AND fk_parent_line = '.$fk_parent_line;
  1878. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  1879. $resql = $this->db->query($sql);
  1880. if ($resql)
  1881. {
  1882. $row = $this->db->fetch_row($resql);
  1883. if (! empty($row[0]))
  1884. {
  1885. return $row[0];
  1886. }
  1887. else
  1888. {
  1889. return $this->getRangOfLine($fk_parent_line);
  1890. }
  1891. }
  1892. }
  1893. // If not, search the last rang of element
  1894. else
  1895. {
  1896. $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1897. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1898. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  1899. $resql = $this->db->query($sql);
  1900. if ($resql)
  1901. {
  1902. $row = $this->db->fetch_row($resql);
  1903. return $row[0];
  1904. }
  1905. }
  1906. }
  1907. /**
  1908. * Update external ref of element
  1909. *
  1910. * @param string $ref_ext Update field ref_ext
  1911. * @return int <0 if KO, >0 if OK
  1912. */
  1913. function update_ref_ext($ref_ext)
  1914. {
  1915. if (! $this->table_element)
  1916. {
  1917. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  1918. return -1;
  1919. }
  1920. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1921. $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  1922. $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id;
  1923. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  1924. if ($this->db->query($sql))
  1925. {
  1926. $this->ref_ext = $ref_ext;
  1927. return 1;
  1928. }
  1929. else
  1930. {
  1931. $this->error=$this->db->error();
  1932. return -1;
  1933. }
  1934. }
  1935. /**
  1936. * Update note of element
  1937. *
  1938. * @param string $note New value for note
  1939. * @param string $suffix '', '_public' or '_private'
  1940. * @return int <0 if KO, >0 if OK
  1941. */
  1942. function update_note($note,$suffix='')
  1943. {
  1944. global $user;
  1945. if (! $this->table_element)
  1946. {
  1947. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  1948. return -1;
  1949. }
  1950. if (! in_array($suffix,array('','_public','_private')))
  1951. {
  1952. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  1953. return -2;
  1954. }
  1955. // Special cas
  1956. //var_dump($this->table_element);exit;
  1957. if ($this->table_element == 'product') $suffix='';
  1958. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1959. $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
  1960. $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id;
  1961. $sql.= " WHERE rowid =". $this->id;
  1962. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  1963. if ($this->db->query($sql))
  1964. {
  1965. if ($suffix == '_public') $this->note_public = $note;
  1966. else if ($suffix == '_private') $this->note_private = $note;
  1967. else
  1968. {
  1969. $this->note = $note; // deprecated
  1970. $this->note_private = $note;
  1971. }
  1972. return 1;
  1973. }
  1974. else
  1975. {
  1976. $this->error=$this->db->lasterror();
  1977. return -1;
  1978. }
  1979. }
  1980. /**
  1981. * Update public note (kept for backward compatibility)
  1982. *
  1983. * @param string $note New value for note
  1984. * @return int <0 if KO, >0 if OK
  1985. * @deprecated
  1986. * @see update_note()
  1987. */
  1988. function update_note_public($note)
  1989. {
  1990. return $this->update_note($note,'_public');
  1991. }
  1992. /**
  1993. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  1994. * Must be called at end of methods addline or updateline.
  1995. *
  1996. * @param int $exclspec >0 = Exclude special product (product_type=9)
  1997. * @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
  1998. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  1999. * @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.
  2000. * @return int <0 if KO, >0 if OK
  2001. */
  2002. function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null)
  2003. {
  2004. global $conf;
  2005. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2006. if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility
  2007. $forcedroundingmode=$roundingadjust;
  2008. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2009. elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
  2010. $error=0;
  2011. // Define constants to find lines to sum
  2012. $fieldtva='total_tva';
  2013. $fieldlocaltax1='total_localtax1';
  2014. $fieldlocaltax2='total_localtax2';
  2015. $fieldup='subprice';
  2016. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  2017. {
  2018. $fieldtva='tva';
  2019. $fieldup='pu_ht';
  2020. }
  2021. if ($this->element == 'expensereport')
  2022. {
  2023. $fieldup='value_unit';
  2024. }
  2025. $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,';
  2026. $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  2027. if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
  2028. $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  2029. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2030. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2031. if ($exclspec)
  2032. {
  2033. $product_field='product_type';
  2034. if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field
  2035. if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
  2036. }
  2037. $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
  2038. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2039. $resql = $this->db->query($sql);
  2040. if ($resql)
  2041. {
  2042. $this->total_ht = 0;
  2043. $this->total_tva = 0;
  2044. $this->total_localtax1 = 0;
  2045. $this->total_localtax2 = 0;
  2046. $this->total_ttc = 0;
  2047. $total_ht_by_vats = array();
  2048. $total_tva_by_vats = array();
  2049. $total_ttc_by_vats = array();
  2050. $this->multicurrency_total_ht = 0;
  2051. $this->multicurrency_total_tva = 0;
  2052. $this->multicurrency_total_ttc = 0;
  2053. $num = $this->db->num_rows($resql);
  2054. $i = 0;
  2055. while ($i < $num)
  2056. {
  2057. $obj = $this->db->fetch_object($resql);
  2058. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  2059. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  2060. if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
  2061. {
  2062. $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
  2063. $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);
  2064. $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
  2065. if ($diff)
  2066. {
  2067. $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  2068. 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);
  2069. $resqlfix=$this->db->query($sqlfix);
  2070. if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
  2071. $obj->total_tva = $tmpcal[1];
  2072. $obj->total_ttc = $tmpcal[2];
  2073. //
  2074. }
  2075. }
  2076. $this->total_ht += $obj->total_ht; // The only field visible at end of line detail
  2077. $this->total_tva += $obj->total_tva;
  2078. $this->total_localtax1 += $obj->total_localtax1;
  2079. $this->total_localtax2 += $obj->total_localtax2;
  2080. $this->total_ttc += $obj->total_ttc;
  2081. if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0;
  2082. if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
  2083. if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
  2084. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  2085. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  2086. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  2087. if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat
  2088. {
  2089. $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  2090. $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
  2091. //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";
  2092. if ($diff)
  2093. {
  2094. if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
  2095. $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;
  2096. 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);
  2097. $resqlfix=$this->db->query($sqlfix);
  2098. if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
  2099. $this->total_tva -= $diff;
  2100. $this->total_ttc -= $diff;
  2101. $total_tva_by_vats[$obj->vatrate] -= $diff;
  2102. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  2103. }
  2104. }
  2105. $i++;
  2106. }
  2107. // Add revenue stamp to total
  2108. $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0;
  2109. // Situations totals
  2110. if ($this->situation_cycle_ref && $this->situation_counter > 1) {
  2111. $prev_sits = $this->get_prev_sits();
  2112. foreach ($prev_sits as $sit) {
  2113. $this->total_ht -= $sit->total_ht;
  2114. $this->total_tva -= $sit->total_tva;
  2115. $this->total_localtax1 -= $sit->total_localtax1;
  2116. $this->total_localtax2 -= $sit->total_localtax2;
  2117. $this->total_ttc -= $sit->total_ttc;
  2118. }
  2119. }
  2120. // Multicurrency
  2121. $this->multicurrency_total_ht += $this->total_ht * $multicurrency_tx;
  2122. $this->multicurrency_total_tva += $this->total_tva * $multicurrency_tx;
  2123. $this->multicurrency_total_ttc += $this->total_ttc * $multicurrency_tx;
  2124. $this->db->free($resql);
  2125. // Now update global field total_ht, total_ttc and tva
  2126. $fieldht='total_ht';
  2127. $fieldtva='tva';
  2128. $fieldlocaltax1='localtax1';
  2129. $fieldlocaltax2='localtax2';
  2130. $fieldttc='total_ttc';
  2131. // Specific code for backward compatibility with old field names
  2132. if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total';
  2133. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
  2134. if ($this->element == 'propal') $fieldttc='total';
  2135. if ($this->element == 'expensereport') $fieldtva='total_tva';
  2136. if ($this->element == 'supplier_proposal') $fieldttc='total';
  2137. if (empty($nodatabaseupdate))
  2138. {
  2139. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  2140. $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
  2141. $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
  2142. $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
  2143. $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
  2144. $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
  2145. $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
  2146. $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
  2147. $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
  2148. $sql .= ' WHERE rowid = '.$this->id;
  2149. //print "xx".$sql;
  2150. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2151. $resql=$this->db->query($sql);
  2152. if (! $resql)
  2153. {
  2154. $error++;
  2155. $this->error=$this->db->lasterror();
  2156. $this->errors[]=$this->db->lasterror();
  2157. }
  2158. }
  2159. if (! $error)
  2160. {
  2161. return 1;
  2162. }
  2163. else
  2164. {
  2165. return -1;
  2166. }
  2167. }
  2168. else
  2169. {
  2170. dol_print_error($this->db,'Bad request in update_price');
  2171. return -1;
  2172. }
  2173. }
  2174. /**
  2175. * Add objects linked in llx_element_element.
  2176. *
  2177. * @param string $origin Linked element type
  2178. * @param int $origin_id Linked element id
  2179. * @return int <=0 if KO, >0 if OK
  2180. * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked
  2181. */
  2182. function add_object_linked($origin=null, $origin_id=null)
  2183. {
  2184. $origin = (! empty($origin) ? $origin : $this->origin);
  2185. $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
  2186. // Special case
  2187. if ($origin == 'order') $origin='commande';
  2188. if ($origin == 'invoice') $origin='facture';
  2189. $this->db->begin();
  2190. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  2191. $sql.= "fk_source";
  2192. $sql.= ", sourcetype";
  2193. $sql.= ", fk_target";
  2194. $sql.= ", targettype";
  2195. $sql.= ") VALUES (";
  2196. $sql.= $origin_id;
  2197. $sql.= ", '".$origin."'";
  2198. $sql.= ", ".$this->id;
  2199. $sql.= ", '".$this->element."'";
  2200. $sql.= ")";
  2201. dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
  2202. if ($this->db->query($sql))
  2203. {
  2204. $this->db->commit();
  2205. return 1;
  2206. }
  2207. else
  2208. {
  2209. $this->error=$this->db->lasterror();
  2210. $this->db->rollback();
  2211. return 0;
  2212. }
  2213. }
  2214. /**
  2215. * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds
  2216. * Possible usage for parameters:
  2217. * - all parameters empty -> we look all link to current object (current object can be source or target)
  2218. * - source id+type -> will get target list linked to source
  2219. * - target id+type -> will get source list linked to target
  2220. * - source id+type + target type -> will get target list of the type
  2221. * - target id+type + target source -> will get source list of the type
  2222. *
  2223. * @param int $sourceid Object source id (if not defined, id of object)
  2224. * @param string $sourcetype Object source type (if not defined, element name of object)
  2225. * @param int $targetid Object target id (if not defined, id of object)
  2226. * @param string $targettype Object target type (if not defined, elemennt name of object)
  2227. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  2228. * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type.
  2229. * @return void
  2230. * @see add_object_linked, updateObjectLinked, deleteObjectLinked
  2231. */
  2232. function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1)
  2233. {
  2234. global $conf;
  2235. $this->linkedObjectsIds=array();
  2236. $this->linkedObjects=array();
  2237. $justsource=false;
  2238. $justtarget=false;
  2239. $withtargettype=false;
  2240. $withsourcetype=false;
  2241. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
  2242. {
  2243. $justsource=true; // the source (id and type) is a search criteria
  2244. if (! empty($targettype)) $withtargettype=true;
  2245. }
  2246. if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
  2247. {
  2248. $justtarget=true; // the target (id and type) is a search criteria
  2249. if (! empty($sourcetype)) $withsourcetype=true;
  2250. }
  2251. $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
  2252. $targetid = (! empty($targetid) ? $targetid : $this->id);
  2253. $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
  2254. $targettype = (! empty($targettype) ? $targettype : $this->element);
  2255. /*if (empty($sourceid) && empty($targetid))
  2256. {
  2257. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  2258. return -1;
  2259. }*/
  2260. // Links between objects are stored in table element_element
  2261. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  2262. $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
  2263. $sql.= " WHERE ";
  2264. if ($justsource || $justtarget)
  2265. {
  2266. if ($justsource)
  2267. {
  2268. $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
  2269. if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
  2270. }
  2271. else if ($justtarget)
  2272. {
  2273. $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
  2274. if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
  2275. }
  2276. }
  2277. else
  2278. {
  2279. $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
  2280. $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
  2281. }
  2282. $sql .= ' ORDER BY sourcetype';
  2283. //print $sql;
  2284. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  2285. $resql = $this->db->query($sql);
  2286. if ($resql)
  2287. {
  2288. $num = $this->db->num_rows($resql);
  2289. $i = 0;
  2290. while ($i < $num)
  2291. {
  2292. $obj = $this->db->fetch_object($resql);
  2293. if ($justsource || $justtarget)
  2294. {
  2295. if ($justsource)
  2296. {
  2297. $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
  2298. }
  2299. else if ($justtarget)
  2300. {
  2301. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
  2302. }
  2303. }
  2304. else
  2305. {
  2306. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
  2307. {
  2308. $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
  2309. }
  2310. if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
  2311. {
  2312. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
  2313. }
  2314. }
  2315. $i++;
  2316. }
  2317. if (! empty($this->linkedObjectsIds))
  2318. {
  2319. foreach($this->linkedObjectsIds as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  2320. {
  2321. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  2322. $module = $element = $subelement = $objecttype;
  2323. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  2324. && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  2325. {
  2326. $module = $element = $regs[1];
  2327. $subelement = $regs[2];
  2328. }
  2329. $classpath = $element.'/class';
  2330. // To work with non standard classpath or module name
  2331. if ($objecttype == 'facture') {
  2332. $classpath = 'compta/facture/class';
  2333. }
  2334. else if ($objecttype == 'facturerec') {
  2335. $classpath = 'compta/facture/class'; $module = 'facture';
  2336. }
  2337. else if ($objecttype == 'propal') {
  2338. $classpath = 'comm/propal/class';
  2339. }
  2340. else if ($objecttype == 'supplier_proposal') {
  2341. $classpath = 'supplier_proposal/class';
  2342. }
  2343. else if ($objecttype == 'shipping') {
  2344. $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
  2345. }
  2346. else if ($objecttype == 'delivery') {
  2347. $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
  2348. }
  2349. else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  2350. $classpath = 'fourn/class'; $module = 'fournisseur';
  2351. }
  2352. else if ($objecttype == 'fichinter') {
  2353. $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
  2354. }
  2355. else if ($objecttype == 'subscription') {
  2356. $classpath = 'adherents/class'; $module = 'adherent';
  2357. }
  2358. // Set classfile
  2359. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  2360. if ($objecttype == 'order') {
  2361. $classfile = 'commande'; $classname = 'Commande';
  2362. }
  2363. else if ($objecttype == 'invoice_supplier') {
  2364. $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
  2365. }
  2366. else if ($objecttype == 'order_supplier') {
  2367. $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
  2368. }
  2369. else if ($objecttype == 'supplier_proposal') {
  2370. $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
  2371. }
  2372. else if ($objecttype == 'facturerec') {
  2373. $classfile = 'facture-rec'; $classname = 'FactureRec';
  2374. }
  2375. else if ($objecttype == 'subscription') {
  2376. $classfile = 'subscription'; $classname = 'Subscription';
  2377. }
  2378. // Here $module, $classfile and $classname are set
  2379. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
  2380. {
  2381. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  2382. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  2383. if (class_exists($classname))
  2384. {
  2385. foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element
  2386. {
  2387. $object = new $classname($this->db);
  2388. $ret = $object->fetch($objectid);
  2389. if ($ret >= 0)
  2390. {
  2391. $this->linkedObjects[$objecttype][$i] = $object;
  2392. }
  2393. }
  2394. }
  2395. }
  2396. }
  2397. }
  2398. }
  2399. else
  2400. {
  2401. dol_print_error($this->db);
  2402. }
  2403. }
  2404. /**
  2405. * Update object linked of a current object
  2406. *
  2407. * @param int $sourceid Object source id
  2408. * @param string $sourcetype Object source type
  2409. * @param int $targetid Object target id
  2410. * @param string $targettype Object target type
  2411. * @return int >0 if OK, <0 if KO
  2412. * @see add_object_linked, fetObjectLinked, deleteObjectLinked
  2413. */
  2414. function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='')
  2415. {
  2416. $updatesource=false;
  2417. $updatetarget=false;
  2418. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true;
  2419. else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true;
  2420. $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
  2421. if ($updatesource)
  2422. {
  2423. $sql.= "fk_source = ".$sourceid;
  2424. $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'";
  2425. $sql.= " WHERE fk_target = ".$this->id;
  2426. $sql.= " AND targettype = '".$this->db->escape($this->element)."'";
  2427. }
  2428. else if ($updatetarget)
  2429. {
  2430. $sql.= "fk_target = ".$targetid;
  2431. $sql.= ", targettype = '".$this->db->escape($targettype)."'";
  2432. $sql.= " WHERE fk_source = ".$this->id;
  2433. $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'";
  2434. }
  2435. dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
  2436. if ($this->db->query($sql))
  2437. {
  2438. return 1;
  2439. }
  2440. else
  2441. {
  2442. $this->error=$this->db->lasterror();
  2443. return -1;
  2444. }
  2445. }
  2446. /**
  2447. * Delete all links between an object $this
  2448. *
  2449. * @param int $sourceid Object source id
  2450. * @param string $sourcetype Object source type
  2451. * @param int $targetid Object target id
  2452. * @param string $targettype Object target type
  2453. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  2454. * @return int >0 if OK, <0 if KO
  2455. * @see add_object_linked, updateObjectLinked, fetchObjectLinked
  2456. */
  2457. function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
  2458. {
  2459. $deletesource=false;
  2460. $deletetarget=false;
  2461. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource=true;
  2462. else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $deletetarget=true;
  2463. $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
  2464. $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
  2465. $targetid = (! empty($targetid) ? $targetid : $this->id);
  2466. $targettype = (! empty($targettype) ? $targettype : $this->element);
  2467. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  2468. $sql.= " WHERE";
  2469. if ($rowid > 0)
  2470. {
  2471. $sql.=" rowid = ".$rowid;
  2472. }
  2473. else
  2474. {
  2475. if ($deletesource)
  2476. {
  2477. $sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2478. $sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
  2479. }
  2480. else if ($deletetarget)
  2481. {
  2482. $sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  2483. $sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
  2484. }
  2485. else
  2486. {
  2487. $sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
  2488. $sql.= " OR";
  2489. $sql.= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
  2490. }
  2491. }
  2492. dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
  2493. if ($this->db->query($sql))
  2494. {
  2495. return 1;
  2496. }
  2497. else
  2498. {
  2499. $this->error=$this->db->lasterror();
  2500. $this->errors[]=$this->error;
  2501. return -1;
  2502. }
  2503. }
  2504. /**
  2505. * Set status of an object
  2506. *
  2507. * @param int $status Status to set
  2508. * @param int $elementId Id of element to force (use this->id by default)
  2509. * @param string $elementType Type of element to force (use this->table_element by default)
  2510. * @return int <0 if KO, >0 if OK
  2511. */
  2512. function setStatut($status,$elementId=null,$elementType='')
  2513. {
  2514. global $user,$langs,$conf;
  2515. $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not.
  2516. $elementId = (!empty($elementId)?$elementId:$this->id);
  2517. $elementTable = (!empty($elementType)?$elementType:$this->table_element);
  2518. $this->db->begin();
  2519. $fieldstatus="fk_statut";
  2520. if ($elementTable == 'mailing') $fieldstatus="statut";
  2521. if ($elementTable == 'user') $fieldstatus="statut";
  2522. if ($elementTable == 'expensereport') $fieldstatus="fk_statut";
  2523. if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status";
  2524. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  2525. $sql.= " SET ".$fieldstatus." = ".$status;
  2526. // If status = 1 = validated, update also fk_user_valid
  2527. if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id;
  2528. $sql.= " WHERE rowid=".$elementId;
  2529. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  2530. if ($this->db->query($sql))
  2531. {
  2532. $error = 0;
  2533. $trigkey='';
  2534. if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  2535. if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  2536. if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  2537. if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE';
  2538. if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED';
  2539. if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED';
  2540. if ($trigkey)
  2541. {
  2542. // Appel des triggers
  2543. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  2544. $interface=new Interfaces($this->db);
  2545. $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf);
  2546. if ($result < 0) {
  2547. $error++; $this->errors=$interface->errors;
  2548. }
  2549. // Fin appel triggers
  2550. }
  2551. if (! $error)
  2552. {
  2553. $this->db->commit();
  2554. if (empty($savElementId)) // If the element we update was $this (so $elementId is null)
  2555. {
  2556. $this->statut = $status;
  2557. $this->status = $status;
  2558. }
  2559. return 1;
  2560. }
  2561. else
  2562. {
  2563. $this->db->rollback();
  2564. dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
  2565. return -1;
  2566. }
  2567. }
  2568. else
  2569. {
  2570. $this->error=$this->db->lasterror();
  2571. $this->db->rollback();
  2572. return -1;
  2573. }
  2574. }
  2575. /**
  2576. * Load type of canvas of an object if it exists
  2577. *
  2578. * @param int $id Record id
  2579. * @param string $ref Record ref
  2580. * @return int <0 if KO, 0 if nothing done, >0 if OK
  2581. */
  2582. function getCanvas($id=0,$ref='')
  2583. {
  2584. global $conf;
  2585. if (empty($id) && empty($ref)) return 0;
  2586. if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
  2587. // Clean parameters
  2588. $ref = trim($ref);
  2589. $sql = "SELECT rowid, canvas";
  2590. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  2591. $sql.= " WHERE entity IN (".getEntity($this->element, 1).")";
  2592. if (! empty($id)) $sql.= " AND rowid = ".$id;
  2593. if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
  2594. $resql = $this->db->query($sql);
  2595. if ($resql)
  2596. {
  2597. $obj = $this->db->fetch_object($resql);
  2598. if ($obj)
  2599. {
  2600. $this->canvas = $obj->canvas;
  2601. return 1;
  2602. }
  2603. else return 0;
  2604. }
  2605. else
  2606. {
  2607. dol_print_error($this->db);
  2608. return -1;
  2609. }
  2610. }
  2611. /**
  2612. * Get special code of a line
  2613. *
  2614. * @param int $lineid Id of line
  2615. * @return int Special code
  2616. */
  2617. function getSpecialCode($lineid)
  2618. {
  2619. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2620. $sql.= ' WHERE rowid = '.$lineid;
  2621. $resql = $this->db->query($sql);
  2622. if ($resql)
  2623. {
  2624. $row = $this->db->fetch_row($resql);
  2625. return $row[0];
  2626. }
  2627. }
  2628. /**
  2629. * Function to check if an object is used by others.
  2630. * Check is done into this->childtables. There is no check into llx_element_element.
  2631. *
  2632. * @param int $id Force id of object
  2633. * @return int <0 if KO, 0 if not used, >0 if already used
  2634. */
  2635. function isObjectUsed($id=0)
  2636. {
  2637. if (empty($id)) $id=$this->id;
  2638. // Check parameters
  2639. if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
  2640. {
  2641. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  2642. return -1;
  2643. }
  2644. // Test if child exists
  2645. $haschild=0;
  2646. foreach($this->childtables as $table)
  2647. {
  2648. // Check if third party can be deleted
  2649. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  2650. $sql.= " WHERE ".$this->fk_element." = ".$id;
  2651. $resql=$this->db->query($sql);
  2652. if ($resql)
  2653. {
  2654. $obj=$this->db->fetch_object($resql);
  2655. $haschild+=$obj->nb;
  2656. //print 'Found into table '.$table;
  2657. if ($haschild) break; // We found at least on, we stop here
  2658. }
  2659. else
  2660. {
  2661. $this->error=$this->db->lasterror();
  2662. return -1;
  2663. }
  2664. }
  2665. if ($haschild > 0)
  2666. {
  2667. $this->error="ErrorRecordHasChildren";
  2668. return $haschild;
  2669. }
  2670. else return 0;
  2671. }
  2672. /**
  2673. * Function to say how many lines object contains
  2674. *
  2675. * @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
  2676. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  2677. */
  2678. function hasProductsOrServices($predefined=-1)
  2679. {
  2680. $nb=0;
  2681. foreach($this->lines as $key => $val)
  2682. {
  2683. $qualified=0;
  2684. if ($predefined == -1) $qualified=1;
  2685. if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
  2686. if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
  2687. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
  2688. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
  2689. if ($qualified) $nb++;
  2690. }
  2691. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  2692. return $nb;
  2693. }
  2694. /**
  2695. * Function that returns the total amount HT of discounts applied for all lines.
  2696. *
  2697. * @return float
  2698. */
  2699. function getTotalDiscount()
  2700. {
  2701. $total_discount=0.00;
  2702. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  2703. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  2704. $sql.= " WHERE ".$this->fk_element." = ".$this->id;
  2705. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  2706. $resql = $this->db->query($sql);
  2707. if ($resql)
  2708. {
  2709. $num=$this->db->num_rows($resql);
  2710. $i=0;
  2711. while ($i < $num)
  2712. {
  2713. $obj = $this->db->fetch_object($resql);
  2714. $pu_ht = $obj->pu_ht;
  2715. $qty= $obj->qty;
  2716. $total_ht = $obj->total_ht;
  2717. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  2718. $total_discount += $total_discount_line;
  2719. $i++;
  2720. }
  2721. }
  2722. //print $total_discount; exit;
  2723. return price2num($total_discount);
  2724. }
  2725. /**
  2726. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  2727. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  2728. *
  2729. * @return array array('weight'=>...,'volume'=>...)
  2730. */
  2731. function getTotalWeightVolume()
  2732. {
  2733. $totalWeight = 0;
  2734. $totalVolume = 0;
  2735. // defined for shipment only
  2736. $totalOrdered = '';
  2737. // defined for shipment only
  2738. $totalToShip = '';
  2739. foreach ($this->lines as $line)
  2740. {
  2741. if (isset($line->qty_asked))
  2742. {
  2743. if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is ''
  2744. $totalOrdered+=$line->qty_asked; // defined for shipment only
  2745. }
  2746. if (isset($line->qty_shipped))
  2747. {
  2748. if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is ''
  2749. $totalToShip+=$line->qty_shipped; // defined for shipment only
  2750. }
  2751. // Define qty, weight, volume, weight_units, volume_units
  2752. if ($this->element == 'shipping') {
  2753. // for shipments
  2754. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  2755. }
  2756. else {
  2757. $qty = $line->qty ? $line->qty : 0;
  2758. }
  2759. $weight = $line->weight ? $line->weight : 0;
  2760. $volume = $line->volume ? $line->volume : 0;
  2761. $weight_units=$line->weight_units;
  2762. $volume_units=$line->volume_units;
  2763. $weightUnit=0;
  2764. $volumeUnit=0;
  2765. if (! empty($weight_units)) $weightUnit = $weight_units;
  2766. if (! empty($volume_units)) $volumeUnit = $volume_units;
  2767. if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is ''
  2768. if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is ''
  2769. //var_dump($line->volume_units);
  2770. if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  2771. {
  2772. $trueWeightUnit=pow(10, $weightUnit);
  2773. $totalWeight += $weight * $qty * $trueWeightUnit;
  2774. }
  2775. else
  2776. {
  2777. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  2778. }
  2779. if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  2780. {
  2781. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  2782. $trueVolumeUnit=pow(10, $volumeUnit);
  2783. //print $line->volume;
  2784. $totalVolume += $volume * $qty * $trueVolumeUnit;
  2785. }
  2786. else
  2787. {
  2788. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  2789. }
  2790. }
  2791. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  2792. }
  2793. /**
  2794. * Set extra parameters
  2795. *
  2796. * @return int <0 if KO, >0 if OK
  2797. */
  2798. function setExtraParameters()
  2799. {
  2800. $this->db->begin();
  2801. $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
  2802. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2803. $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  2804. $sql.= " WHERE rowid = ".$this->id;
  2805. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  2806. $resql = $this->db->query($sql);
  2807. if (! $resql)
  2808. {
  2809. $this->error=$this->db->lasterror();
  2810. $this->db->rollback();
  2811. return -1;
  2812. }
  2813. else
  2814. {
  2815. $this->db->commit();
  2816. return 1;
  2817. }
  2818. }
  2819. /**
  2820. * Return incoterms informations
  2821. * TODO Use a cache for label get
  2822. *
  2823. * @return string incoterms info
  2824. */
  2825. function display_incoterms()
  2826. {
  2827. $out = '';
  2828. $this->libelle_incoterms = '';
  2829. if (!empty($this->fk_incoterms))
  2830. {
  2831. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  2832. $result = $this->db->query($sql);
  2833. if ($result)
  2834. {
  2835. $res = $this->db->fetch_object($result);
  2836. $out .= $res->code;
  2837. }
  2838. }
  2839. $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
  2840. return $out;
  2841. }
  2842. /**
  2843. * Return incoterms informations for pdf display
  2844. *
  2845. * @return string incoterms info
  2846. */
  2847. function getIncotermsForPDF()
  2848. {
  2849. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  2850. $resql = $this->db->query($sql);
  2851. if ($resql)
  2852. {
  2853. $num = $this->db->num_rows($resql);
  2854. if ($num > 0)
  2855. {
  2856. $res = $this->db->fetch_object($resql);
  2857. return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
  2858. }
  2859. else
  2860. {
  2861. return '';
  2862. }
  2863. }
  2864. else
  2865. {
  2866. $this->errors[] = $this->db->lasterror();
  2867. return false;
  2868. }
  2869. }
  2870. /**
  2871. * Define incoterms values of current object
  2872. *
  2873. * @param int $id_incoterm Id of incoterm to set or '' to remove
  2874. * @param string $location location of incoterm
  2875. * @return int <0 if KO, >0 if OK
  2876. */
  2877. function setIncoterms($id_incoterm, $location)
  2878. {
  2879. if ($this->id && $this->table_element)
  2880. {
  2881. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  2882. $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
  2883. $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
  2884. $sql.= " WHERE rowid = " . $this->id;
  2885. dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
  2886. $resql=$this->db->query($sql);
  2887. if ($resql)
  2888. {
  2889. $this->fk_incoterms = $id_incoterm;
  2890. $this->location_incoterms = $location;
  2891. $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  2892. $res = $this->db->query($sql);
  2893. if ($res)
  2894. {
  2895. $obj = $this->db->fetch_object($res);
  2896. $this->libelle_incoterms = $obj->libelle;
  2897. }
  2898. return 1;
  2899. }
  2900. else
  2901. {
  2902. $this->errors[] = $this->db->lasterror();
  2903. return -1;
  2904. }
  2905. }
  2906. else return -1;
  2907. }
  2908. /**
  2909. * Return if a country is inside the EEC (European Economic Community)
  2910. * @deprecated
  2911. *
  2912. * @return boolean true = country inside EEC, false = country outside EEC
  2913. */
  2914. function isInEEC()
  2915. {
  2916. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2917. return isInEEC($this);
  2918. }
  2919. // --------------------
  2920. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  2921. // --------------------
  2922. /* This is to show add lines */
  2923. /**
  2924. * Show add free and predefined products/services form
  2925. *
  2926. * @param int $dateSelector 1=Show also date range input fields
  2927. * @param Societe $seller Object thirdparty who sell
  2928. * @param Societe $buyer Object thirdparty who buy
  2929. * @return void
  2930. */
  2931. function formAddObjectLine($dateSelector,$seller,$buyer)
  2932. {
  2933. global $conf,$user,$langs,$object,$hookmanager;
  2934. global $form,$bcnd,$var;
  2935. //Line extrafield
  2936. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  2937. $extrafieldsline = new ExtraFields($this->db);
  2938. $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
  2939. // Output template part (modules that overwrite templates must declare this into descriptor)
  2940. // Use global variables + $dateSelector + $seller and $buyer
  2941. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  2942. foreach($dirtpls as $reldir)
  2943. {
  2944. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  2945. if (empty($conf->file->strict_mode)) {
  2946. $res=@include $tpl;
  2947. } else {
  2948. $res=include $tpl; // for debug
  2949. }
  2950. if ($res) break;
  2951. }
  2952. }
  2953. /* This is to show array of line of details */
  2954. /**
  2955. * Return HTML table for object lines
  2956. * TODO Move this into an output class file (htmlline.class.php)
  2957. * If lines are into a template, title must also be into a template
  2958. * But for the moment we don't know if it'st possible as we keep a method available on overloaded objects.
  2959. *
  2960. * @param string $action Action code
  2961. * @param string $seller Object of seller third party
  2962. * @param string $buyer Object of buyer third party
  2963. * @param int $selected Object line selected
  2964. * @param int $dateSelector 1=Show also date range input fields
  2965. * @return void
  2966. */
  2967. function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
  2968. {
  2969. global $conf, $hookmanager, $langs, $user;
  2970. // TODO We should not use global var for this !
  2971. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  2972. // Define usemargins
  2973. $usemargins=0;
  2974. if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
  2975. $num = count($this->lines);
  2976. //Line extrafield
  2977. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  2978. $extrafieldsline = new ExtraFields($this->db);
  2979. $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
  2980. $parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
  2981. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2982. if (empty($reshook))
  2983. {
  2984. print '<tr class="liste_titre nodrag nodrop">';
  2985. if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
  2986. // Description
  2987. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  2988. if ($this->element == 'supplier_proposal')
  2989. {
  2990. print '<td class="linerefsupplier" align="right"><span id="title_fourn_ref">'.$langs->trans("SupplierProposalRefFourn").'</span></td>';
  2991. }
  2992. // VAT
  2993. print '<td class="linecolvat" align="right" width="80">'.$langs->trans('VAT').'</td>';
  2994. // Price HT
  2995. print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
  2996. // Multicurrency
  2997. if (!empty($conf->multicurrency->enabled)) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
  2998. if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
  2999. // Qty
  3000. print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
  3001. if($conf->global->PRODUCT_USE_UNITS)
  3002. {
  3003. print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
  3004. }
  3005. // Reduction short
  3006. print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
  3007. if ($this->situation_cycle_ref) {
  3008. print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
  3009. }
  3010. if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id))
  3011. {
  3012. if (!empty($user->rights->margins->creer))
  3013. {
  3014. if ($conf->global->MARGIN_TYPE == "1")
  3015. print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
  3016. else
  3017. print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
  3018. }
  3019. if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
  3020. print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
  3021. if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
  3022. print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
  3023. }
  3024. // Total HT
  3025. print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
  3026. // Multicurrency
  3027. if (!empty($conf->multicurrency->enabled)) print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
  3028. if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
  3029. print '<td class="linecoledit"></td>'; // No width to allow autodim
  3030. print '<td class="linecoldelete" width="10"></td>';
  3031. print '<td class="linecolmove" width="10"></td>';
  3032. print "</tr>\n";
  3033. }
  3034. $var = true;
  3035. $i = 0;
  3036. foreach ($this->lines as $line)
  3037. {
  3038. //Line extrafield
  3039. $line->fetch_optionals($line->id,$extralabelslines);
  3040. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3041. if (is_object($hookmanager)) // Old code is commented on preceding line.
  3042. {
  3043. if (empty($line->fk_parent_line))
  3044. {
  3045. $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
  3046. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3047. }
  3048. else
  3049. {
  3050. $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);
  3051. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3052. }
  3053. }
  3054. if (empty($reshook))
  3055. {
  3056. $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
  3057. }
  3058. $i++;
  3059. }
  3060. }
  3061. /**
  3062. * Return HTML content of a detail line
  3063. * TODO Move this into an output class file (htmlline.class.php)
  3064. *
  3065. * @param string $action GET/POST action
  3066. * @param CommonObjectLine $line Selected object line to output
  3067. * @param string $var Is it a an odd line (true)
  3068. * @param int $num Number of line (0)
  3069. * @param int $i I
  3070. * @param int $dateSelector 1=Show also date range input fields
  3071. * @param string $seller Object of seller third party
  3072. * @param string $buyer Object of buyer third party
  3073. * @param int $selected Object line selected
  3074. * @param int $extrafieldsline Object of extrafield line attribute
  3075. * @return void
  3076. */
  3077. function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
  3078. {
  3079. global $conf,$langs,$user,$object,$hookmanager;
  3080. global $form,$bc,$bcdd;
  3081. global $object_rights, $disableedit, $disablemove; // TODO We should not use global var for this !
  3082. $object_rights = $this->getRights();
  3083. $element=$this->element;
  3084. $text=''; $description=''; $type=0;
  3085. // Show product and description
  3086. $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
  3087. // Try to enhance type detection using date_start and date_end for free lines where type was not saved.
  3088. if (! empty($line->date_start)) $type=1; // deprecated
  3089. if (! empty($line->date_end)) $type=1; // deprecated
  3090. // Ligne en mode visu
  3091. if ($action != 'editline' || $selected != $line->id)
  3092. {
  3093. // Product
  3094. if ($line->fk_product > 0)
  3095. {
  3096. $product_static = new Product($this->db);
  3097. $product_static->fetch($line->fk_product);
  3098. $product_static->ref = $line->ref; //can change ref in hook
  3099. $product_static->label = $line->label; //can change label in hook
  3100. $text=$product_static->getNomUrl(1);
  3101. // Define output language and label
  3102. if (! empty($conf->global->MAIN_MULTILANGS))
  3103. {
  3104. if (! is_object($this->thirdparty))
  3105. {
  3106. dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  3107. return;
  3108. }
  3109. $prod = new Product($this->db);
  3110. $prod->fetch($line->fk_product);
  3111. $outputlangs = $langs;
  3112. $newlang='';
  3113. if (empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
  3114. if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang; // For language to language of customer
  3115. if (! empty($newlang))
  3116. {
  3117. $outputlangs = new Translate("",$conf);
  3118. $outputlangs->setDefaultLang($newlang);
  3119. }
  3120. $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  3121. }
  3122. else
  3123. {
  3124. $label = $line->product_label;
  3125. }
  3126. $text.= ' - '.(! empty($line->label)?$line->label:$label);
  3127. $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.
  3128. }
  3129. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
  3130. // Output template part (modules that overwrite templates must declare this into descriptor)
  3131. // Use global variables + $dateSelector + $seller and $buyer
  3132. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3133. foreach($dirtpls as $reldir)
  3134. {
  3135. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  3136. if (empty($conf->file->strict_mode)) {
  3137. $res=@include $tpl;
  3138. } else {
  3139. $res=include $tpl; // for debug
  3140. }
  3141. if ($res) break;
  3142. }
  3143. }
  3144. // Ligne en mode update
  3145. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
  3146. {
  3147. $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  3148. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("Label").'"';
  3149. else $placeholder=' title="'.$langs->trans("Label").'"';
  3150. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
  3151. // Output template part (modules that overwrite templates must declare this into descriptor)
  3152. // Use global variables + $dateSelector + $seller and $buyer
  3153. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3154. foreach($dirtpls as $reldir)
  3155. {
  3156. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  3157. if (empty($conf->file->strict_mode)) {
  3158. $res=@include $tpl;
  3159. } else {
  3160. $res=include $tpl; // for debug
  3161. }
  3162. if ($res) break;
  3163. }
  3164. }
  3165. }
  3166. /* This is to show array of line of details of source object */
  3167. /**
  3168. * Return HTML table table of source object lines
  3169. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3170. * If lines are into a template, title must also be into a template
  3171. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3172. *
  3173. * @return void
  3174. */
  3175. function printOriginLinesList()
  3176. {
  3177. global $langs, $hookmanager, $conf;
  3178. print '<tr class="liste_titre">';
  3179. print '<td>'.$langs->trans('Ref').'</td>';
  3180. print '<td>'.$langs->trans('Description').'</td>';
  3181. print '<td align="right">'.$langs->trans('VATRate').'</td>';
  3182. print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
  3183. if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  3184. print '<td align="right">'.$langs->trans('Qty').'</td>';
  3185. if($conf->global->PRODUCT_USE_UNITS)
  3186. {
  3187. print '<td align="left">'.$langs->trans('Unit').'</td>';
  3188. }
  3189. print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
  3190. $var = true;
  3191. $i = 0;
  3192. foreach ($this->lines as $line)
  3193. {
  3194. if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3195. {
  3196. if (empty($line->fk_parent_line))
  3197. {
  3198. $parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
  3199. $action='';
  3200. $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  3201. }
  3202. }
  3203. else
  3204. {
  3205. $this->printOriginLine($line,$var);
  3206. }
  3207. $i++;
  3208. }
  3209. }
  3210. /**
  3211. * Return HTML with a line of table array of source object lines
  3212. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3213. * If lines are into a template, title must also be into a template
  3214. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3215. *
  3216. * @param CommonObjectLine $line Line
  3217. * @param string $var Var
  3218. * @return void
  3219. */
  3220. function printOriginLine($line,$var)
  3221. {
  3222. global $langs, $conf;
  3223. //var_dump($line);
  3224. if (!empty($line->date_start))
  3225. {
  3226. $date_start=$line->date_start;
  3227. }
  3228. else
  3229. {
  3230. $date_start=$line->date_debut_prevue;
  3231. if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
  3232. }
  3233. if (!empty($line->date_end))
  3234. {
  3235. $date_end=$line->date_end;
  3236. }
  3237. else
  3238. {
  3239. $date_end=$line->date_fin_prevue;
  3240. if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
  3241. }
  3242. $this->tpl['label'] = '';
  3243. if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
  3244. if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object
  3245. {
  3246. $discount=new DiscountAbsolute($this->db);
  3247. $discount->fk_soc = $this->socid;
  3248. $this->tpl['label'].= $discount->getNomUrl(0,'discount');
  3249. }
  3250. else if (! empty($line->fk_product))
  3251. {
  3252. $productstatic = new Product($this->db);
  3253. $productstatic->id = $line->fk_product;
  3254. $productstatic->ref = $line->ref;
  3255. $productstatic->type = $line->fk_product_type;
  3256. $this->tpl['label'].= $productstatic->getNomUrl(1);
  3257. $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
  3258. // Dates
  3259. if ($line->product_type == 1 && ($date_start || $date_end))
  3260. {
  3261. $this->tpl['label'].= get_date_range($date_start,$date_end);
  3262. }
  3263. }
  3264. else
  3265. {
  3266. $this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
  3267. if (!empty($line->desc)) {
  3268. $this->tpl['label'].=$line->desc;
  3269. }else {
  3270. $this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
  3271. }
  3272. // Dates
  3273. if ($line->product_type == 1 && ($date_start || $date_end))
  3274. {
  3275. $this->tpl['label'].= get_date_range($date_start,$date_end);
  3276. }
  3277. }
  3278. if (! empty($line->desc))
  3279. {
  3280. if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object
  3281. {
  3282. $discount=new DiscountAbsolute($this->db);
  3283. $discount->fetch($line->fk_remise_except);
  3284. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
  3285. }
  3286. elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object
  3287. {
  3288. $discount=new DiscountAbsolute($this->db);
  3289. $discount->fetch($line->fk_remise_except);
  3290. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
  3291. }
  3292. elseif ($line->desc == '(EXCESS RECEIVED)')
  3293. {
  3294. $discount=new DiscountAbsolute($this->db);
  3295. $discount->fetch($line->fk_remise_except);
  3296. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
  3297. }
  3298. else
  3299. {
  3300. $this->tpl['description'] = dol_trunc($line->desc,60);
  3301. }
  3302. }
  3303. else
  3304. {
  3305. $this->tpl['description'] = '&nbsp;';
  3306. }
  3307. // VAT Rate
  3308. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  3309. if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
  3310. $this->tpl['price'] = price($line->subprice);
  3311. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  3312. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  3313. if($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $line->getLabelOfUnit('long');
  3314. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  3315. // Output template part (modules that overwrite templates must declare this into descriptor)
  3316. // Use global variables + $dateSelector + $seller and $buyer
  3317. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3318. foreach($dirtpls as $reldir)
  3319. {
  3320. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  3321. if (empty($conf->file->strict_mode)) {
  3322. $res=@include $tpl;
  3323. } else {
  3324. $res=include $tpl; // for debug
  3325. }
  3326. if ($res) break;
  3327. }
  3328. }
  3329. /**
  3330. * Add resources to the current object : add entry into llx_element_resources
  3331. * Need $this->element & $this->id
  3332. *
  3333. * @param int $resource_id Resource id
  3334. * @param string $resource_type 'resource'
  3335. * @param int $busy Busy or not
  3336. * @param int $mandatory Mandatory or not
  3337. * @return int <=0 if KO, >0 if OK
  3338. */
  3339. function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
  3340. {
  3341. $this->db->begin();
  3342. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  3343. $sql.= "resource_id";
  3344. $sql.= ", resource_type";
  3345. $sql.= ", element_id";
  3346. $sql.= ", element_type";
  3347. $sql.= ", busy";
  3348. $sql.= ", mandatory";
  3349. $sql.= ") VALUES (";
  3350. $sql.= $resource_id;
  3351. $sql.= ", '".$resource_type."'";
  3352. $sql.= ", '".$this->id."'";
  3353. $sql.= ", '".$this->element."'";
  3354. $sql.= ", '".$busy."'";
  3355. $sql.= ", '".$mandatory."'";
  3356. $sql.= ")";
  3357. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  3358. if ($this->db->query($sql))
  3359. {
  3360. $this->db->commit();
  3361. return 1;
  3362. }
  3363. else
  3364. {
  3365. $this->error=$this->db->lasterror();
  3366. $this->db->rollback();
  3367. return 0;
  3368. }
  3369. }
  3370. /**
  3371. * Delete a link to resource line
  3372. *
  3373. * @param int $rowid Id of resource line to delete
  3374. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  3375. * @param int $notrigger Disable all triggers
  3376. * @return int >0 if OK, <0 if KO
  3377. */
  3378. function delete_resource($rowid, $element, $notrigger=0)
  3379. {
  3380. global $user;
  3381. $this->db->begin();
  3382. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  3383. $sql.= " WHERE rowid=".$rowid;
  3384. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  3385. $resql=$this->db->query($sql);
  3386. if (! $resql)
  3387. {
  3388. $this->error=$this->db->lasterror();
  3389. $this->db->rollback();
  3390. return -1;
  3391. }
  3392. else
  3393. {
  3394. if (! $notrigger)
  3395. {
  3396. $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  3397. if ($result < 0) { $this->db->rollback(); return -1; }
  3398. }
  3399. $this->db->commit();
  3400. return 1;
  3401. }
  3402. }
  3403. /**
  3404. * Overwrite magic function to solve problem of cloning object that are kept as references
  3405. *
  3406. * @return void
  3407. */
  3408. function __clone()
  3409. {
  3410. // Force a copy of this->lines, otherwise it will point to same object.
  3411. if (isset($this->lines) && is_array($this->lines))
  3412. {
  3413. $nboflines=count($this->lines);
  3414. for($i=0; $i < $nboflines; $i++)
  3415. {
  3416. $this->lines[$i] = clone $this->lines[$i];
  3417. }
  3418. }
  3419. }
  3420. /**
  3421. * Common function for all objects extending CommonObject for generating documents
  3422. *
  3423. * @param string $modelspath Relative folder where generators are placed
  3424. * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
  3425. * @param Translate $outputlangs Language to use
  3426. * @param int $hidedetails 1 to hide details. 0 by default
  3427. * @param int $hidedesc 1 to hide product description. 0 by default
  3428. * @param int $hideref 1 to hide product reference. 0 by default
  3429. * @param null|array $moreparams Array to provide more information
  3430. * @return int >0 if OK, <0 if KO
  3431. */
  3432. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
  3433. {
  3434. global $conf, $langs;
  3435. $srctemplatepath='';
  3436. // Increase limit for PDF build
  3437. $err=error_reporting();
  3438. error_reporting(0);
  3439. @set_time_limit(120);
  3440. error_reporting($err);
  3441. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  3442. $tmp=explode(':',$modele,2);
  3443. if (! empty($tmp[1]))
  3444. {
  3445. $modele=$tmp[0];
  3446. $srctemplatepath=$tmp[1];
  3447. }
  3448. // Search template files
  3449. $file=''; $classname=''; $filefound=0;
  3450. $dirmodels=array('/');
  3451. if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
  3452. foreach($dirmodels as $reldir)
  3453. {
  3454. foreach(array('doc','pdf') as $prefix)
  3455. {
  3456. if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php
  3457. else $file = $prefix."_".$modele.".modules.php";
  3458. // On verifie l'emplacement du modele
  3459. $file=dol_buildpath($reldir.$modelspath.$file,0);
  3460. if (file_exists($file))
  3461. {
  3462. $filefound=1;
  3463. $classname=$prefix.'_'.$modele;
  3464. break;
  3465. }
  3466. }
  3467. if ($filefound) break;
  3468. }
  3469. // If generator was found
  3470. if ($filefound)
  3471. {
  3472. global $db; // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
  3473. require_once $file;
  3474. $obj = new $classname($this->db);
  3475. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  3476. if ($obj->type == 'odt' && empty($srctemplatepath))
  3477. {
  3478. $varfortemplatedir=$obj->scandir;
  3479. if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir))
  3480. {
  3481. $dirtoscan=$conf->global->$varfortemplatedir;
  3482. $listoffiles=array();
  3483. // Now we add first model found in directories scanned
  3484. $listofdir=explode(',',$dirtoscan);
  3485. foreach($listofdir as $key=>$tmpdir)
  3486. {
  3487. $tmpdir=trim($tmpdir);
  3488. $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
  3489. if (! $tmpdir) { unset($listofdir[$key]); continue; }
  3490. if (is_dir($tmpdir))
  3491. {
  3492. $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
  3493. if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
  3494. }
  3495. }
  3496. if (count($listoffiles))
  3497. {
  3498. foreach($listoffiles as $record)
  3499. {
  3500. $srctemplatepath=$record['fullname'];
  3501. break;
  3502. }
  3503. }
  3504. }
  3505. if (empty($srctemplatepath))
  3506. {
  3507. $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  3508. return -1;
  3509. }
  3510. }
  3511. if ($obj->type == 'odt' && ! empty($srctemplatepath))
  3512. {
  3513. if (! dol_is_file($srctemplatepath))
  3514. {
  3515. $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  3516. return -1;
  3517. }
  3518. }
  3519. // We save charset_output to restore it because write_file can change it if needed for
  3520. // output format that does not support UTF8.
  3521. $sav_charset_output=$outputlangs->charset_output;
  3522. if (in_array(get_class($this), array('Adherent')))
  3523. {
  3524. $arrayofrecords = array(); // The write_file of templates of adherent class need this
  3525. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  3526. }
  3527. else $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  3528. if ($resultwritefile > 0)
  3529. {
  3530. $outputlangs->charset_output=$sav_charset_output;
  3531. // We delete old preview
  3532. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3533. dol_delete_preview($this);
  3534. // Success in building document. We build meta file.
  3535. dol_meta_create($this);
  3536. return 1;
  3537. }
  3538. else
  3539. {
  3540. $outputlangs->charset_output=$sav_charset_output;
  3541. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  3542. return -1;
  3543. }
  3544. }
  3545. else
  3546. {
  3547. $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
  3548. dol_print_error('',$this->error);
  3549. return -1;
  3550. }
  3551. }
  3552. /**
  3553. * Build thumb
  3554. *
  3555. * @param string $file Path file in UTF8 to original file to create thumbs from.
  3556. * @return void
  3557. */
  3558. function addThumbs($file)
  3559. {
  3560. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  3561. require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  3562. $file_osencoded=dol_osencode($file);
  3563. if (file_exists($file_osencoded))
  3564. {
  3565. // Create small thumbs for company (Ratio is near 16/9)
  3566. // Used on logon for example
  3567. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  3568. // Create mini thumbs for company (Ratio is near 16/9)
  3569. // Used on menu or for setup page for example
  3570. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  3571. }
  3572. }
  3573. /* Functions common to commonobject and commonobjectline */
  3574. /* For default values */
  3575. /**
  3576. * Return the default value to use for a field when showing the create form of object.
  3577. * Return values in this order:
  3578. * 1) If parameter is available into POST, we return it first.
  3579. * 2) If not but an alternate value was provided as parameter of function, we return it.
  3580. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  3581. * 4) Return value found into database (TODO No yet implemented)
  3582. *
  3583. * @param string $fieldname Name of field
  3584. * @param string $alternatevalue Alternate value to use
  3585. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  3586. **/
  3587. function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
  3588. {
  3589. global $conf, $_POST;
  3590. // If param here has been posted, we use this value first.
  3591. if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
  3592. if (isset($alternatevalue)) return $alternatevalue;
  3593. $newelement=$this->element;
  3594. if ($newelement == 'facture') $newelement='invoice';
  3595. if ($newelement == 'commande') $newelement='order';
  3596. if (empty($newelement))
  3597. {
  3598. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  3599. return '';
  3600. }
  3601. $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
  3602. //var_dump($keyforfieldname);
  3603. if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
  3604. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  3605. }
  3606. /* For triggers */
  3607. /**
  3608. * Call trigger based on this instance.
  3609. * Some context information may also be provided into array property this->context.
  3610. * NB: Error from trigger are stacked in interface->errors
  3611. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  3612. *
  3613. * @param string $trigger_name trigger's name to execute
  3614. * @param User $user Object user
  3615. * @return int Result of run_triggers
  3616. */
  3617. function call_trigger($trigger_name, $user)
  3618. {
  3619. global $langs,$conf;
  3620. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  3621. $interface=new Interfaces($this->db);
  3622. $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
  3623. if ($result < 0)
  3624. {
  3625. if (!empty($this->errors))
  3626. {
  3627. $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.
  3628. }
  3629. else
  3630. {
  3631. $this->errors=$interface->errors;
  3632. }
  3633. }
  3634. return $result;
  3635. }
  3636. /* Functions for extrafields */
  3637. /**
  3638. * Function to get extra fields of a member into $this->array_options
  3639. * This method is in most cases called by method fetch of objects but you can call it separately.
  3640. *
  3641. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  3642. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  3643. * @return int <0 if error, 0 if no optionals to find nor found, 1 if a line is found and optional loaded
  3644. */
  3645. function fetch_optionals($rowid=null,$optionsArray=null)
  3646. {
  3647. if (empty($rowid)) $rowid=$this->id;
  3648. // To avoid SQL errors. Probably not the better solution though
  3649. if (!$this->table_element) {
  3650. return 0;
  3651. }
  3652. if (! is_array($optionsArray))
  3653. {
  3654. // $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  3655. // TODO Use of existing extrafield is not yet ready (must mutualize code that use extrafields in form first)
  3656. // global $extrafields;
  3657. //if (! is_object($extrafields))
  3658. //{
  3659. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3660. $extrafields = new ExtraFields($this->db);
  3661. //}
  3662. // Load array of extrafields for elementype = $this->table_element
  3663. if (empty($extrafields->attributes[$this->table_element]['loaded']))
  3664. {
  3665. $extrafields->fetch_name_optionals_label($this->table_element);
  3666. }
  3667. $optionsArray = $extrafields->attributes[$this->table_element]['label'];
  3668. }
  3669. // Request to get complementary values
  3670. if (count($optionsArray) > 0)
  3671. {
  3672. $sql = "SELECT rowid";
  3673. foreach ($optionsArray as $name => $label)
  3674. {
  3675. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
  3676. {
  3677. $sql.= ", ".$name;
  3678. }
  3679. }
  3680. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields";
  3681. $sql.= " WHERE fk_object = ".$rowid;
  3682. dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);
  3683. $resql=$this->db->query($sql);
  3684. if ($resql)
  3685. {
  3686. $numrows=$this->db->num_rows($resql);
  3687. if ($numrows)
  3688. {
  3689. $tab = $this->db->fetch_array($resql);
  3690. foreach ($tab as $key => $value)
  3691. {
  3692. // 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)
  3693. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
  3694. {
  3695. // we can add this attribute to object
  3696. $this->array_options["options_".$key]=$value;
  3697. }
  3698. }
  3699. }
  3700. $this->db->free($resql);
  3701. if ($numrows) return $numrows;
  3702. else return 0;
  3703. }
  3704. else
  3705. {
  3706. dol_print_error($this->db);
  3707. return -1;
  3708. }
  3709. }
  3710. return 0;
  3711. }
  3712. /**
  3713. * Delete all extra fields values for the current object.
  3714. *
  3715. * @return int <0 if KO, >0 if OK
  3716. */
  3717. function deleteExtraFields()
  3718. {
  3719. $this->db->begin();
  3720. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  3721. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  3722. $resql=$this->db->query($sql_del);
  3723. if (! $resql)
  3724. {
  3725. $this->error=$this->db->lasterror();
  3726. $this->db->rollback();
  3727. return -1;
  3728. }
  3729. else
  3730. {
  3731. $this->db->commit();
  3732. return 1;
  3733. }
  3734. }
  3735. /**
  3736. * Add/Update all extra fields values for the current object.
  3737. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  3738. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  3739. *
  3740. * @return int -1=error, O=did nothing, 1=OK
  3741. */
  3742. function insertExtraFields()
  3743. {
  3744. global $conf,$langs;
  3745. $error=0;
  3746. if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
  3747. if (! empty($this->array_options))
  3748. {
  3749. // Check parameters
  3750. $langs->load('admin');
  3751. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3752. $extrafields = new ExtraFields($this->db);
  3753. $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
  3754. //Eliminate copied source object extra_fields that do not exist in target object
  3755. $new_array_options=array();
  3756. foreach ($this->array_options as $key => $value) {
  3757. if (in_array(substr($key,8), array_keys($target_extrafields)))
  3758. $new_array_options[$key] = $value;
  3759. }
  3760. foreach($new_array_options as $key => $value)
  3761. {
  3762. $attributeKey = substr($key,8); // Remove 'options_' prefix
  3763. $attributeType = $extrafields->attribute_type[$attributeKey];
  3764. $attributeLabel = $extrafields->attribute_label[$attributeKey];
  3765. $attributeParam = $extrafields->attribute_param[$attributeKey];
  3766. switch ($attributeType)
  3767. {
  3768. case 'int':
  3769. if (!is_numeric($value) && $value!='')
  3770. {
  3771. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
  3772. return -1;
  3773. }
  3774. elseif ($value=='')
  3775. {
  3776. $this->array_options[$key] = null;
  3777. }
  3778. break;
  3779. case 'price':
  3780. $this->array_options[$key] = price2num($this->array_options[$key]);
  3781. break;
  3782. case 'date':
  3783. $this->array_options[$key]=$this->db->idate($this->array_options[$key]);
  3784. break;
  3785. case 'datetime':
  3786. $this->array_options[$key]=$this->db->idate($this->array_options[$key]);
  3787. break;
  3788. case 'link':
  3789. $param_list=array_keys($attributeParam ['options']);
  3790. // 0 : ObjectName
  3791. // 1 : classPath
  3792. $InfoFieldList = explode(":", $param_list[0]);
  3793. dol_include_once($InfoFieldList[1]);
  3794. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  3795. {
  3796. $object = new $InfoFieldList[0]($this->db);
  3797. if ($value)
  3798. {
  3799. if (is_numeric($value)) $res=$object->fetch($value);
  3800. else $res=$object->fetch('',$value);
  3801. if ($res > 0) $this->array_options[$key]=$object->id;
  3802. else
  3803. {
  3804. $this->error="Ref '".$value."' for object '".$object->element."' not found";
  3805. $this->db->rollback();
  3806. return -1;
  3807. }
  3808. }
  3809. }
  3810. else
  3811. {
  3812. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  3813. }
  3814. break;
  3815. }
  3816. }
  3817. $this->db->begin();
  3818. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id;
  3819. dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
  3820. $this->db->query($sql_del);
  3821. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."_extrafields (fk_object";
  3822. foreach($new_array_options as $key => $value)
  3823. {
  3824. $attributeKey = substr($key,8); // Remove 'options_' prefix
  3825. // Add field of attribut
  3826. if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate
  3827. $sql.=",".$attributeKey;
  3828. }
  3829. $sql .= ") VALUES (".$this->id;
  3830. foreach($new_array_options as $key => $value)
  3831. {
  3832. $attributeKey = substr($key,8); // Remove 'options_' prefix
  3833. // Add field o fattribut
  3834. if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate)
  3835. {
  3836. if ($this->array_options[$key] != '')
  3837. {
  3838. $sql.=",'".$this->db->escape($this->array_options[$key])."'";
  3839. }
  3840. else
  3841. {
  3842. $sql.=",null";
  3843. }
  3844. }
  3845. }
  3846. $sql.=")";
  3847. dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
  3848. $resql = $this->db->query($sql);
  3849. if (! $resql)
  3850. {
  3851. $this->error=$this->db->lasterror();
  3852. $this->db->rollback();
  3853. return -1;
  3854. }
  3855. else
  3856. {
  3857. $this->db->commit();
  3858. return 1;
  3859. }
  3860. }
  3861. else return 0;
  3862. }
  3863. /**
  3864. * Update an exta field value for the current object.
  3865. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  3866. * This function delte record with all extrafields and insert them again from the array $this->array_options.
  3867. *
  3868. * @param string $key Key of the extrafield
  3869. * @return int -1=error, O=did nothing, 1=OK
  3870. */
  3871. function updateExtraField($key)
  3872. {
  3873. global $conf,$langs;
  3874. $error=0;
  3875. if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
  3876. if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
  3877. {
  3878. // Check parameters
  3879. $langs->load('admin');
  3880. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3881. $extrafields = new ExtraFields($this->db);
  3882. $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
  3883. $value=$this->array_options["options_".$key];
  3884. $attributeType = $extrafields->attribute_type[$key];
  3885. $attributeLabel = $extrafields->attribute_label[$key];
  3886. $attributeParam = $extrafields->attribute_param[$key];
  3887. switch ($attributeType)
  3888. {
  3889. case 'int':
  3890. if (!is_numeric($value) && $value!='')
  3891. {
  3892. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
  3893. return -1;
  3894. }
  3895. elseif ($value=='')
  3896. {
  3897. $this->array_options["options_".$key] = null;
  3898. }
  3899. break;
  3900. case 'price':
  3901. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  3902. break;
  3903. case 'date':
  3904. $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
  3905. break;
  3906. case 'datetime':
  3907. $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
  3908. break;
  3909. case 'link':
  3910. $param_list=array_keys($attributeParam ['options']);
  3911. // 0 : ObjectName
  3912. // 1 : classPath
  3913. $InfoFieldList = explode(":", $param_list[0]);
  3914. dol_include_once($InfoFieldList[1]);
  3915. $object = new $InfoFieldList[0]($this->db);
  3916. if ($value)
  3917. {
  3918. $object->fetch(0,$value);
  3919. $this->array_options["options_".$key]=$object->id;
  3920. }
  3921. break;
  3922. }
  3923. $this->db->begin();
  3924. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
  3925. $sql .= " WHERE fk_object = ".$this->id;
  3926. $resql = $this->db->query($sql);
  3927. if (! $resql)
  3928. {
  3929. $this->error=$this->db->lasterror();
  3930. $this->db->rollback();
  3931. return -1;
  3932. }
  3933. else
  3934. {
  3935. $this->db->commit();
  3936. return 1;
  3937. }
  3938. }
  3939. else return 0;
  3940. }
  3941. /**
  3942. * Function to show lines of extrafields with output datas
  3943. *
  3944. * @param Extrafields $extrafields Extrafield Object
  3945. * @param string $mode Show output (view) or input (edit) for extrafield
  3946. * @param array $params Optional parameters
  3947. * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  3948. *
  3949. * @return string
  3950. */
  3951. function showOptionals($extrafields, $mode='view', $params=null, $keyprefix='')
  3952. {
  3953. global $_POST, $conf, $langs;
  3954. $out = '';
  3955. if (count($extrafields->attribute_label) > 0)
  3956. {
  3957. $out .= "\n";
  3958. $out .= '<!-- showOptionalsInput --> ';
  3959. $out .= "\n";
  3960. $e = 0;
  3961. foreach($extrafields->attribute_label as $key=>$label)
  3962. {
  3963. if (is_array($params) && count($params)>0) {
  3964. if (array_key_exists('colspan',$params)) {
  3965. $colspan=$params['colspan'];
  3966. }
  3967. }else {
  3968. $colspan='3';
  3969. }
  3970. switch($mode) {
  3971. case "view":
  3972. $value=$this->array_options["options_".$key];
  3973. break;
  3974. case "edit":
  3975. if (isset($_POST["options_" . $key])) {
  3976. if (is_array($_POST["options_" . $key])) {
  3977. // $_POST["options"] is an array but following code expects a comma separated string
  3978. $value = implode(",", $_POST["options_" . $key]);
  3979. } else {
  3980. $value = $_POST["options_" . $key];
  3981. }
  3982. } else {
  3983. $value = $this->array_options["options_" . $key];
  3984. }
  3985. break;
  3986. }
  3987. if ($extrafields->attribute_type[$key] == 'separate')
  3988. {
  3989. $out .= $extrafields->showSeparator($key);
  3990. }
  3991. else
  3992. {
  3993. $csstyle='';
  3994. $class=(!empty($extrafields->attribute_hidden[$key]) ? 'class="hideobject" ' : '');
  3995. if (is_array($params) && count($params)>0) {
  3996. if (array_key_exists('style',$params)) {
  3997. $csstyle=$params['style'];
  3998. }
  3999. }
  4000. if ( !empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
  4001. {
  4002. $out .= '<tr '.$class.$csstyle.' class="'.$this->element.'_extras_'.$key.'">';
  4003. $colspan='0';
  4004. }
  4005. else
  4006. {
  4007. $out .= '<tr '.$class.$csstyle.' class="'.$this->element.'_extras_'.$key.'">';
  4008. }
  4009. // Convert date into timestamp format
  4010. if (in_array($extrafields->attribute_type[$key],array('date','datetime')))
  4011. {
  4012. $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]);
  4013. }
  4014. if($extrafields->attribute_required[$key])
  4015. $label = '<span'.($mode != 'view' ? ' class="fieldrequired"':'').'>'.$label.'</span>';
  4016. $out .= '<td>'.$langs->trans($label).'</td>';
  4017. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  4018. $out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
  4019. switch($mode) {
  4020. case "view":
  4021. $out .= $extrafields->showOutputField($key, $value);
  4022. break;
  4023. case "edit":
  4024. $out .= $extrafields->showInputField($key, $value, '', $keyprefix, '', 0, $this->id);
  4025. break;
  4026. }
  4027. $out .= '</td>';
  4028. if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
  4029. else $out .= '</tr>';
  4030. $e++;
  4031. }
  4032. }
  4033. $out .= "\n";
  4034. // Add code to manage list depending on others
  4035. if (! empty($conf->use_javascript_ajax))
  4036. $out .= '
  4037. <script type="text/javascript">
  4038. jQuery(document).ready(function() {
  4039. function showOptions(child_list, parent_list)
  4040. {
  4041. var val = $("select[name=\"options_"+parent_list+"\"]").val();
  4042. var parentVal = parent_list + ":" + val;
  4043. if(val > 0) {
  4044. $("select[name=\""+child_list+"\"] option[parent]").hide();
  4045. $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
  4046. } else {
  4047. $("select[name=\""+child_list+"\"] option").show();
  4048. }
  4049. }
  4050. function setListDependencies() {
  4051. jQuery("select option[parent]").parent().each(function() {
  4052. var child_list = $(this).attr("name");
  4053. var parent = $(this).find("option[parent]:first").attr("parent");
  4054. var infos = parent.split(":");
  4055. var parent_list = infos[0];
  4056. $("select[name=\""+parent_list+"\"]").change(function() {
  4057. showOptions(child_list, parent_list);
  4058. });
  4059. });
  4060. }
  4061. setListDependencies();
  4062. });
  4063. </script>'."\n";
  4064. $out .= '<!-- /showOptionalsInput --> '."\n";
  4065. }
  4066. return $out;
  4067. }
  4068. /**
  4069. * Returns the rights used for this class
  4070. * @return stdClass
  4071. */
  4072. public function getRights()
  4073. {
  4074. global $user;
  4075. $element = $this->element;
  4076. if ($element == 'facturerec') $element='facture';
  4077. return $user->rights->{$element};
  4078. }
  4079. /**
  4080. * Function used to replace a thirdparty id with another one.
  4081. * This function is meant to be called from replaceThirdparty with the appropiate tables
  4082. * Column name fk_soc MUST be used to identify thirdparties
  4083. *
  4084. * @param DoliDB $db Database handler
  4085. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  4086. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  4087. * @param string[] $tables Tables that need to be changed
  4088. * @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)
  4089. * @return bool
  4090. */
  4091. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
  4092. {
  4093. foreach ($tables as $table)
  4094. {
  4095. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
  4096. if (! $db->query($sql))
  4097. {
  4098. 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.
  4099. //$this->errors = $db->lasterror();
  4100. return false;
  4101. }
  4102. }
  4103. return true;
  4104. }
  4105. /**
  4106. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  4107. * set buy price = sell price if ForceBuyingPriceIfNull configured,
  4108. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  4109. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  4110. * else set min buy price as buy price
  4111. *
  4112. * @param float $unitPrice product unit price
  4113. * @param float $discountPercent line discount percent
  4114. * @param int $fk_product product id
  4115. *
  4116. * @return float <0 if ko, buyprice if ok
  4117. */
  4118. public function defineBuyPrice($unitPrice = 0, $discountPercent = 0, $fk_product = 0)
  4119. {
  4120. global $conf;
  4121. $buyPrice = 0;
  4122. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
  4123. {
  4124. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  4125. }
  4126. else
  4127. {
  4128. // Get cost price for margin calculation
  4129. if (! empty($fk_product))
  4130. {
  4131. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
  4132. {
  4133. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4134. $product = new Product($this->db);
  4135. $result = $product->fetch($fk_product);
  4136. if ($result <= 0)
  4137. {
  4138. $this->errors[] = 'ErrorProductIdDoesNotExists';
  4139. return -1;
  4140. }
  4141. if ($product->cost_price > 0)
  4142. {
  4143. $buyPrice = $product->cost_price;
  4144. }
  4145. else if ($product->pmp > 0)
  4146. {
  4147. $buyPrice = $product->pmp;
  4148. }
  4149. }
  4150. else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
  4151. {
  4152. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4153. $product = new Product($this->db);
  4154. $result = $product->fetch($fk_product);
  4155. if ($result <= 0)
  4156. {
  4157. $this->errors[] = 'ErrorProductIdDoesNotExists';
  4158. return -1;
  4159. }
  4160. if ($product->pmp > 0)
  4161. {
  4162. $buyPrice = $product->pmp;
  4163. }
  4164. }
  4165. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
  4166. {
  4167. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  4168. $productFournisseur = new ProductFournisseur($this->db);
  4169. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
  4170. {
  4171. $buyPrice = $productFournisseur->fourn_unitprice;
  4172. }
  4173. else if ($result < 0)
  4174. {
  4175. $this->errors[] = $productFournisseur->error;
  4176. return -2;
  4177. }
  4178. }
  4179. }
  4180. }
  4181. return $buyPrice;
  4182. }
  4183. /**
  4184. * Function test if type is date
  4185. *
  4186. * @param array $info content informations of field
  4187. * @return bool
  4188. */
  4189. protected function isDate($info)
  4190. {
  4191. if(isset($info['type']) && $info['type']=='date') return true;
  4192. else return false;
  4193. }
  4194. /**
  4195. * Function test if type is array
  4196. *
  4197. * @param array $info content informations of field
  4198. * @return bool
  4199. */
  4200. protected function isArray($info)
  4201. {
  4202. if(is_array($info))
  4203. {
  4204. if(isset($info['type']) && $info['type']=='array') return true;
  4205. else return false;
  4206. }
  4207. else return false;
  4208. }
  4209. /**
  4210. * Function test if type is null
  4211. *
  4212. * @param array $info content informations of field
  4213. * @return bool
  4214. */
  4215. protected function isNull($info)
  4216. {
  4217. if(is_array($info))
  4218. {
  4219. if(isset($info['type']) && $info['type']=='null') return true;
  4220. else return false;
  4221. }
  4222. else return false;
  4223. }
  4224. /**
  4225. * Function test if type is integer
  4226. *
  4227. * @param array $info content informations of field
  4228. * @return bool
  4229. */
  4230. protected function isInt($info)
  4231. {
  4232. if(is_array($info))
  4233. {
  4234. if(isset($info['type']) && ($info['type']=='int' || $info['type']=='integer' )) return true;
  4235. else return false;
  4236. }
  4237. else return false;
  4238. }
  4239. /**
  4240. * Function test if type is float
  4241. *
  4242. * @param array $info content informations of field
  4243. * @return bool
  4244. */
  4245. protected function isFloat($info)
  4246. {
  4247. if(is_array($info))
  4248. {
  4249. if(isset($info['type']) && $info['type']=='float') return true;
  4250. else return false;
  4251. }
  4252. else return false;
  4253. }
  4254. /**
  4255. * Function test if type is text
  4256. *
  4257. * @param array $info content informations of field
  4258. * @return bool
  4259. */
  4260. protected function isText($info)
  4261. {
  4262. if(is_array($info))
  4263. {
  4264. if(isset($info['type']) && $info['type']=='text') return true;
  4265. else return false;
  4266. }
  4267. else return false;
  4268. }
  4269. /**
  4270. * Function test if is indexed
  4271. *
  4272. * @param array $info content informations of field
  4273. * @return bool
  4274. */
  4275. protected function isIndex($info)
  4276. {
  4277. if(is_array($info))
  4278. {
  4279. if(isset($info['index']) && $info['index']==true) return true;
  4280. else return false;
  4281. }
  4282. else return false;
  4283. }
  4284. /**
  4285. * Function to prepare the values to insert
  4286. *
  4287. * @return array
  4288. */
  4289. private function set_save_query()
  4290. {
  4291. $query=array();
  4292. foreach ($this->fields as $field=>$info)
  4293. {
  4294. if($this->isDate($info))
  4295. {
  4296. if(empty($this->{$field}))
  4297. {
  4298. $query[$field] = NULL;
  4299. }
  4300. else
  4301. {
  4302. $query[$field] = $this->db->idate($this->{$field});
  4303. }
  4304. }
  4305. else if($this->isArray($info))
  4306. {
  4307. $query[$field] = serialize($this->{$field});
  4308. }
  4309. else if($this->isInt($info))
  4310. {
  4311. $query[$field] = (int) price2num($this->{$field});
  4312. }
  4313. else if($this->isFloat($info))
  4314. {
  4315. $query[$field] = (double) price2num($this->{$field});
  4316. }
  4317. elseif($this->isNull($info))
  4318. {
  4319. $query[$field] = (is_null($this->{$field}) || (empty($this->{$field}) && $this->{$field}!==0 && $this->{$field}!=='0') ? null : $this->{$field});
  4320. }
  4321. else
  4322. {
  4323. $query[$field] = $this->{$field};
  4324. }
  4325. }
  4326. return $query;
  4327. }
  4328. /**
  4329. * Create object into database
  4330. *
  4331. * @param User $user User that creates
  4332. * @param bool $notrigger false=launch triggers after, true=disable triggers
  4333. *
  4334. * @return int <0 if KO, Id of created object if OK
  4335. */
  4336. public function createCommon(User $user, $notrigger = false)
  4337. {
  4338. $fields = array_merge(array('datec'=>$this->db->idate(dol_now())), $this->set_save_query());
  4339. foreach ($fields as $k => $v) {
  4340. $keys[] = $k;
  4341. $values[] = $this->quote($v);
  4342. }
  4343. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'
  4344. ( '.implode( ",", $keys ).' )
  4345. VALUES ( '.implode( ",", $values ).' ) ';
  4346. $res = $this->db->query( $sql );
  4347. if($res===false) {
  4348. return false;
  4349. }
  4350. // TODO Add triggers
  4351. return true;
  4352. }
  4353. /**
  4354. * Function to load data into current object this
  4355. *
  4356. * @param stdClass $obj Contain data of object from database
  4357. */
  4358. private function set_vars_by_db(&$obj)
  4359. {
  4360. foreach ($this->fields as $field => $info)
  4361. {
  4362. if($this->isDate($info))
  4363. {
  4364. if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
  4365. else $this->{$field} = strtotime($obj->{$field});
  4366. }
  4367. elseif($this->isArray($info))
  4368. {
  4369. $this->{$field} = @unserialize($obj->{$field});
  4370. // Hack for data not in UTF8
  4371. if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field}));
  4372. }
  4373. elseif($this->isInt($info))
  4374. {
  4375. $this->{$field} = (int) $obj->{$field};
  4376. }
  4377. elseif($this->isFloat($info))
  4378. {
  4379. $this->{$field} = (double) $obj->{$field};
  4380. }
  4381. elseif($this->isNull($info))
  4382. {
  4383. $val = $obj->{$field};
  4384. // zero is not null
  4385. $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
  4386. }
  4387. else
  4388. {
  4389. $this->{$field} = $obj->{$field};
  4390. }
  4391. }
  4392. }
  4393. /**
  4394. * Function to concat keys of fields
  4395. *
  4396. * @return string
  4397. */
  4398. private function get_field_list()
  4399. {
  4400. $keys = array_keys($this->fields);
  4401. return implode(',', $keys);
  4402. }
  4403. /**
  4404. * Load object in memory from the database
  4405. *
  4406. * @param int $id Id object
  4407. * @param string $ref Ref
  4408. *
  4409. * @return int <0 if KO, 0 if not found, >0 if OK
  4410. */
  4411. public function fetchCommon($id, $ref = null)
  4412. {
  4413. if (empty($id) && empty($ref)) return false;
  4414. $sql = 'SELECT '.$this->get_field_list().', datec, tms';
  4415. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  4416. if(!empty($id)) $sql.= ' WHERE rowid = '.$id;
  4417. else $sql.= ' WHERE ref = \''.$this->quote($ref).'\'';
  4418. $res = $this->db->query($sql);
  4419. if ($res)
  4420. {
  4421. if ($obj = $this->db->fetch_object($res))
  4422. {
  4423. $this->id = $id;
  4424. $this->set_vars_by_db($obj);
  4425. $this->datec = $this->db->idate($obj->datec);
  4426. $this->tms = $this->db->idate($obj->tms);
  4427. return $this->id;
  4428. }
  4429. else
  4430. {
  4431. $this->error = $this->db->lasterror();
  4432. $this->errors[] = $this->error;
  4433. return -1;
  4434. }
  4435. }
  4436. else
  4437. {
  4438. $this->error = $this->db->lasterror();
  4439. $this->errors[] = $this->error;
  4440. return -1;
  4441. }
  4442. }
  4443. /**
  4444. * Update object into database
  4445. *
  4446. * @param User $user User that modifies
  4447. * @param bool $notrigger false=launch triggers after, true=disable triggers
  4448. *
  4449. * @return int <0 if KO, >0 if OK
  4450. */
  4451. public function updateCommon(User $user, $notrigger = false)
  4452. {
  4453. $fields = $this->set_save_query();
  4454. foreach ($fields as $k => $v) {
  4455. if (is_array($key)){
  4456. $i=array_search($k, $key);
  4457. if ( $i !== false) {
  4458. $where[] = $key[$i].'=' . $this->quote( $v ) ;
  4459. continue;
  4460. }
  4461. } else {
  4462. if ( $k == $key) {
  4463. $where[] = $k.'=' .$this->quote( $v ) ;
  4464. continue;
  4465. }
  4466. }
  4467. $tmp[] = $k.'='.$this->quote($v);
  4468. }
  4469. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
  4470. $res = $this->db->query( $sql );
  4471. if($res===false) {
  4472. //error
  4473. return false;
  4474. }
  4475. // TODO Add triggers
  4476. return true;
  4477. }
  4478. /**
  4479. * Delete object in database
  4480. *
  4481. * @param User $user User that deletes
  4482. * @param bool $notrigger false=launch triggers after, true=disable triggers
  4483. *
  4484. * @return int <0 if KO, >0 if OK
  4485. */
  4486. public function deleteCommon(User $user, $notrigger = false)
  4487. {
  4488. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
  4489. $res = $this->db->query( $sql );
  4490. if($res===false) {
  4491. return false;
  4492. }
  4493. // TODO Add triggers
  4494. return true;
  4495. }
  4496. /**
  4497. * Add quote to field value if necessary
  4498. *
  4499. * @param string|int $value value to protect
  4500. * @return string|int
  4501. */
  4502. protected function quote($value) {
  4503. if(is_null($value)) return 'NULL';
  4504. else if(is_numeric($value)) return $value;
  4505. else return "'".$this->db->escape( $value )."'";
  4506. }
  4507. }