commonobject.class.php 241 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384
  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-2015 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  6. * Copyright (C) 2011-2018 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  9. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  10. * Copyright (C) 2015 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
  11. * Copyright (C) 2016 Bahfir abbes <dolipar@dolipar.org>
  12. * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
  13. * Copyright (C) 2017 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  15. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/core/class/commonobject.class.php
  33. * \ingroup core
  34. * \brief File of parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  35. */
  36. /**
  37. * Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
  38. */
  39. abstract class CommonObject
  40. {
  41. /**
  42. * @var DoliDb Database handler (result of a new DoliDB)
  43. */
  44. public $db;
  45. /**
  46. * @var int The object identifier
  47. */
  48. public $id;
  49. /**
  50. * @var string Error string
  51. * @see errors
  52. */
  53. public $error;
  54. /**
  55. * @var string[] Array of error strings
  56. */
  57. public $errors=array();
  58. /**
  59. * @var string ID to identify managed object
  60. */
  61. public $element;
  62. /**
  63. * @var string Name of table without prefix where object is stored
  64. */
  65. public $table_element;
  66. /**
  67. * @var int Name of subtable line
  68. */
  69. public $table_element_line='';
  70. /**
  71. * @var string Key value used to track if data is coming from import wizard
  72. */
  73. public $import_key;
  74. /**
  75. * @var mixed Contains data to manage extrafields
  76. */
  77. public $array_options=array();
  78. /**
  79. * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked
  80. */
  81. public $linkedObjectsIds;
  82. /**
  83. * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked
  84. */
  85. public $linkedObjects;
  86. /**
  87. * @var Object To store a cloned copy of object before to edit it and keep track of old properties
  88. */
  89. public $oldcopy;
  90. /**
  91. * @var string Column name of the ref field.
  92. */
  93. protected $table_ref_field = '';
  94. // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
  95. /**
  96. * @var array<string,mixed> Can be used to pass information when only object is provided to method
  97. */
  98. public $context=array();
  99. /**
  100. * @var string Contains canvas name if record is an alternative canvas record
  101. */
  102. public $canvas;
  103. /**
  104. * @var Project The related project
  105. * @see fetch_projet()
  106. */
  107. public $project;
  108. /**
  109. * @var int The related project ID
  110. * @see setProject(), project
  111. */
  112. public $fk_project;
  113. /**
  114. * @deprecated
  115. * @see project
  116. */
  117. public $projet;
  118. /**
  119. * @var Contact a related contact
  120. * @see fetch_contact()
  121. */
  122. public $contact;
  123. /**
  124. * @var int The related contact ID
  125. * @see fetch_contact()
  126. */
  127. public $contact_id;
  128. /**
  129. * @var Societe A related thirdparty
  130. * @see fetch_thirdparty()
  131. */
  132. public $thirdparty;
  133. /**
  134. * @var User A related user
  135. * @see fetch_user()
  136. */
  137. public $user;
  138. /**
  139. * @var string The type of originating object ('commande', 'facture', ...)
  140. * @see fetch_origin()
  141. */
  142. public $origin;
  143. /**
  144. * @var int The id of originating object
  145. * @see fetch_origin()
  146. */
  147. public $origin_id;
  148. /**
  149. * @var string The object's reference
  150. */
  151. public $ref;
  152. /**
  153. * @var string The object's previous reference
  154. */
  155. public $ref_previous;
  156. /**
  157. * @var string The object's next reference
  158. */
  159. public $ref_next;
  160. /**
  161. * @var string An external reference for the object
  162. */
  163. public $ref_ext;
  164. /**
  165. * @var int The object's status
  166. * @see setStatut()
  167. */
  168. public $statut;
  169. /**
  170. * @var string
  171. * @see getFullAddress()
  172. */
  173. public $country;
  174. /**
  175. * @var int
  176. * @see getFullAddress(), country
  177. */
  178. public $country_id;
  179. /**
  180. * @var string
  181. * @see getFullAddress(), isInEEC(), country
  182. */
  183. public $country_code;
  184. /**
  185. * @var string
  186. * @see getFullAddress()
  187. */
  188. public $state;
  189. /**
  190. * @var int
  191. * @see getFullAddress(), state
  192. */
  193. public $state_id;
  194. /**
  195. * @var string
  196. * @see getFullAddress(), state
  197. */
  198. public $state_code;
  199. /**
  200. * @var string
  201. * @see getFullAddress(), region
  202. */
  203. public $region;
  204. /**
  205. * @var string
  206. * @see getFullAddress(), region
  207. */
  208. public $region_code;
  209. /**
  210. * @var int
  211. * @see fetch_barcode()
  212. */
  213. public $barcode_type;
  214. /**
  215. * @var string
  216. * @see fetch_barcode(), barcode_type
  217. */
  218. public $barcode_type_code;
  219. /**
  220. * @var string
  221. * @see fetch_barcode(), barcode_type
  222. */
  223. public $barcode_type_label;
  224. /**
  225. * @var string
  226. * @see fetch_barcode(), barcode_type
  227. */
  228. public $barcode_type_coder;
  229. /**
  230. * @var int Payment method ID (cheque, cash, ...)
  231. * @see setPaymentMethods()
  232. */
  233. public $mode_reglement_id;
  234. /**
  235. * @var int Payment terms ID
  236. * @see setPaymentTerms()
  237. */
  238. public $cond_reglement_id;
  239. /**
  240. * @var int Payment terms ID
  241. * @deprecated Kept for compatibility
  242. * @see cond_reglement_id;
  243. */
  244. public $cond_reglement;
  245. /**
  246. * @var int Delivery address ID
  247. * @deprecated
  248. * @see setDeliveryAddress()
  249. */
  250. public $fk_delivery_address;
  251. /**
  252. * @var int Shipping method ID
  253. * @see setShippingMethod()
  254. */
  255. public $shipping_method_id;
  256. /**
  257. * @var string
  258. * @see SetDocModel()
  259. */
  260. public $modelpdf;
  261. /**
  262. * @var int Bank account ID
  263. * @see SetBankAccount()
  264. */
  265. public $fk_account;
  266. /**
  267. * @var string Public note
  268. * @see update_note()
  269. */
  270. public $note_public;
  271. /**
  272. * @var string Private note
  273. * @see update_note()
  274. */
  275. public $note_private;
  276. /**
  277. * @deprecated
  278. * @see note_public
  279. */
  280. public $note;
  281. /**
  282. * @var float Total amount before taxes
  283. * @see update_price()
  284. */
  285. public $total_ht;
  286. /**
  287. * @var float Total VAT amount
  288. * @see update_price()
  289. */
  290. public $total_tva;
  291. /**
  292. * @var float Total local tax 1 amount
  293. * @see update_price()
  294. */
  295. public $total_localtax1;
  296. /**
  297. * @var float Total local tax 2 amount
  298. * @see update_price()
  299. */
  300. public $total_localtax2;
  301. /**
  302. * @var float Total amount with taxes
  303. * @see update_price()
  304. */
  305. public $total_ttc;
  306. /**
  307. * @var CommonObjectLine[]
  308. */
  309. public $lines;
  310. /**
  311. * @var mixed Contains comments
  312. * @see fetchComments()
  313. */
  314. public $comments=array();
  315. /**
  316. * @var int
  317. * @see setIncoterms()
  318. */
  319. public $fk_incoterms;
  320. /**
  321. * @var string
  322. * @see SetIncoterms()
  323. */
  324. public $libelle_incoterms;
  325. /**
  326. * @var string
  327. * @see display_incoterms()
  328. */
  329. public $location_incoterms;
  330. public $name;
  331. public $lastname;
  332. public $firstname;
  333. public $civility_id;
  334. // Dates
  335. public $date_creation; // Date creation
  336. public $date_validation; // Date validation
  337. public $date_modification; // Date last change (tms field)
  338. // No constructor as it is an abstract class
  339. /**
  340. * Check an object id/ref exists
  341. * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
  342. *
  343. * @param string $element String of element ('product', 'facture', ...)
  344. * @param int $id Id of object
  345. * @param string $ref Ref of object to check
  346. * @param string $ref_ext Ref ext of object to check
  347. * @return int <0 if KO, 0 if OK but not found, >0 if OK and exists
  348. */
  349. static function isExistingObject($element, $id, $ref='', $ref_ext='')
  350. {
  351. global $db,$conf;
  352. $sql = "SELECT rowid, ref, ref_ext";
  353. $sql.= " FROM ".MAIN_DB_PREFIX.$element;
  354. $sql.= " WHERE entity IN (".getEntity($element).")" ;
  355. if ($id > 0) $sql.= " AND rowid = ".$db->escape($id);
  356. else if ($ref) $sql.= " AND ref = '".$db->escape($ref)."'";
  357. else if ($ref_ext) $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'";
  358. else {
  359. $error='ErrorWrongParameters';
  360. dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
  361. return -1;
  362. }
  363. if ($ref || $ref_ext) $sql.= " AND entity = ".$conf->entity;
  364. dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
  365. $resql = $db->query($sql);
  366. if ($resql)
  367. {
  368. $num=$db->num_rows($resql);
  369. if ($num > 0) return 1;
  370. else return 0;
  371. }
  372. return -1;
  373. }
  374. /**
  375. * Method to output saved errors
  376. *
  377. * @return string String with errors
  378. */
  379. function errorsToString()
  380. {
  381. return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
  382. }
  383. /**
  384. * Return full name (civility+' '+name+' '+lastname)
  385. *
  386. * @param Translate $langs Language object for translation of civility (used only if option is 1)
  387. * @param int $option 0=No option, 1=Add civility
  388. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
  389. * @param int $maxlen Maximum length
  390. * @return string String with full name
  391. */
  392. function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
  393. {
  394. //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
  395. $lastname=$this->lastname;
  396. $firstname=$this->firstname;
  397. 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:'')))));
  398. $ret='';
  399. if ($option && $this->civility_id)
  400. {
  401. if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
  402. else $ret.=$this->civility_id.' ';
  403. }
  404. $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder);
  405. return dol_trunc($ret,$maxlen);
  406. }
  407. /**
  408. * Return full address of contact
  409. *
  410. * @param int $withcountry 1=Add country into address string
  411. * @param string $sep Separator to use to build string
  412. * @param int $withregion 1=Add region into address string
  413. * @return string Full address string
  414. */
  415. function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
  416. {
  417. if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
  418. {
  419. require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
  420. $tmparray=getCountry($this->country_id,'all');
  421. $this->country_code=$tmparray['code'];
  422. $this->country =$tmparray['label'];
  423. }
  424. if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
  425. {
  426. require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
  427. $tmparray=getState($this->state_id,'all',0,1);
  428. $this->state_code =$tmparray['code'];
  429. $this->state =$tmparray['label'];
  430. $this->region_code =$tmparray['region_code'];
  431. $this->region =$tmparray['region'];
  432. }
  433. return dol_format_address($this, $withcountry, $sep);
  434. }
  435. /**
  436. * Return full address for banner
  437. *
  438. * @param string $htmlkey HTML id to make banner content unique
  439. * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member)
  440. * @return string Full address string
  441. */
  442. function getBannerAddress($htmlkey, $object)
  443. {
  444. global $conf, $langs;
  445. $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
  446. $contactid=0;
  447. $thirdpartyid=0;
  448. if ($this->element == 'societe')
  449. {
  450. $thirdpartyid=$this->id;
  451. }
  452. if ($this->element == 'contact')
  453. {
  454. $contactid=$this->id;
  455. $thirdpartyid=$object->fk_soc;
  456. }
  457. if ($this->element == 'user')
  458. {
  459. $contactid=$this->contact_id;
  460. $thirdpartyid=$object->fk_soc;
  461. }
  462. $out='<!-- BEGIN part to show address block -->';
  463. $outdone=0;
  464. $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
  465. if ($coords)
  466. {
  467. if (! empty($conf->use_javascript_ajax))
  468. {
  469. $namecoords = $this->getFullName($langs,1).'<br>'.$coords;
  470. // hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
  471. $out.='<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
  472. $out.=img_picto($langs->trans("Address"), 'object_address.png');
  473. $out.='</a> ';
  474. }
  475. $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
  476. $outdone++;
  477. }
  478. 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
  479. && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
  480. {
  481. if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
  482. $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
  483. }
  484. else {
  485. $out.=($outdone?' - ':'').$this->state;
  486. }
  487. $outdone++;
  488. }
  489. 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>':'');
  490. if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
  491. $out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
  492. }
  493. if (! empty($this->phone_pro)) {
  494. $out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
  495. }
  496. if (! empty($this->phone_mobile)) {
  497. $out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
  498. }
  499. if (! empty($this->phone_perso)) {
  500. $out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
  501. }
  502. if (! empty($this->office_phone)) {
  503. $out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
  504. }
  505. if (! empty($this->user_mobile)) {
  506. $out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
  507. }
  508. if (! empty($this->fax)) {
  509. $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
  510. }
  511. if (! empty($this->office_fax)) {
  512. $out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
  513. }
  514. $out.='<div style="clear: both;"></div>';
  515. $outdone=0;
  516. if (! empty($this->email))
  517. {
  518. $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
  519. $outdone++;
  520. }
  521. if (! empty($this->url))
  522. {
  523. $out.=dol_print_url($this->url,'_goout',0,1);
  524. $outdone++;
  525. }
  526. $out.='<div style="clear: both;">';
  527. if (! empty($conf->socialnetworks->enabled))
  528. {
  529. if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
  530. $outdone++;
  531. }
  532. if (! empty($conf->socialnetworks->enabled))
  533. {
  534. if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
  535. $outdone++;
  536. }
  537. if (! empty($conf->socialnetworks->enabled))
  538. {
  539. if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
  540. $outdone++;
  541. }
  542. $out.='</div>';
  543. $out.='<!-- END Part to show address block -->';
  544. return $out;
  545. }
  546. /**
  547. * Return the link of last main doc file for direct public download.
  548. *
  549. * @param string $modulepart Module related to document
  550. * @param int $initsharekey Init the share key if it was not yet defined
  551. * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file
  552. * @return string Link or empty string if there is no download link
  553. */
  554. function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
  555. {
  556. global $user, $dolibarr_main_url_root;
  557. if (empty($this->last_main_doc))
  558. {
  559. return ''; // No way to known which document name to use
  560. }
  561. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  562. $ecmfile=new EcmFiles($this->db);
  563. $result = $ecmfile->fetch(0, '', $this->last_main_doc);
  564. if ($result < 0)
  565. {
  566. $this->error = $ecmfile->error;
  567. $this->errors = $ecmfile->errors;
  568. return -1;
  569. }
  570. if (empty($ecmfile->id))
  571. {
  572. // Add entry into index
  573. if ($initsharekey)
  574. {
  575. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  576. // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
  577. /*
  578. $ecmfile->filepath = $rel_dir;
  579. $ecmfile->filename = $filename;
  580. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  581. $ecmfile->fullpath_orig = '';
  582. $ecmfile->gen_or_uploaded = 'generated';
  583. $ecmfile->description = ''; // indexed content
  584. $ecmfile->keyword = ''; // keyword content
  585. $ecmfile->share = getRandomPassword(true);
  586. $result = $ecmfile->create($user);
  587. if ($result < 0)
  588. {
  589. $this->error = $ecmfile->error;
  590. $this->errors = $ecmfile->errors;
  591. }
  592. */
  593. }
  594. else return '';
  595. }
  596. elseif (empty($ecmfile->share))
  597. {
  598. // Add entry into index
  599. if ($initsharekey)
  600. {
  601. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  602. $ecmfile->share = getRandomPassword(true);
  603. $ecmfile->update($user);
  604. }
  605. else return '';
  606. }
  607. // Define $urlwithroot
  608. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  609. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  610. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  611. $forcedownload=0;
  612. $paramlink='';
  613. //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
  614. //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
  615. //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
  616. if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share; // Hash for public share
  617. if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
  618. if ($relativelink)
  619. {
  620. $linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
  621. }
  622. else
  623. {
  624. $linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
  625. }
  626. // Here $ecmfile->share is defined
  627. return $linktoreturn;
  628. }
  629. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  630. /**
  631. * Add a link between element $this->element and a contact
  632. *
  633. * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
  634. * @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
  635. * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
  636. * @param int $notrigger Disable all triggers
  637. * @return int <0 if KO, >0 if OK
  638. */
  639. function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
  640. {
  641. // phpcs:enable
  642. global $user,$langs;
  643. dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
  644. // Check parameters
  645. if ($fk_socpeople <= 0)
  646. {
  647. $langs->load("errors");
  648. $this->error=$langs->trans("ErrorWrongValueForParameterX","1");
  649. dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
  650. return -1;
  651. }
  652. if (! $type_contact)
  653. {
  654. $langs->load("errors");
  655. $this->error=$langs->trans("ErrorWrongValueForParameterX","2");
  656. dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
  657. return -2;
  658. }
  659. $id_type_contact=0;
  660. if (is_numeric($type_contact))
  661. {
  662. $id_type_contact=$type_contact;
  663. }
  664. else
  665. {
  666. // We look for id type_contact
  667. $sql = "SELECT tc.rowid";
  668. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  669. $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
  670. $sql.= " AND tc.source='".$this->db->escape($source)."'";
  671. $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
  672. //print $sql;
  673. $resql=$this->db->query($sql);
  674. if ($resql)
  675. {
  676. $obj = $this->db->fetch_object($resql);
  677. if ($obj) $id_type_contact=$obj->rowid;
  678. }
  679. }
  680. if ($id_type_contact == 0)
  681. {
  682. $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
  683. dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
  684. return -3;
  685. }
  686. $datecreate = dol_now();
  687. // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
  688. $TListeContacts=$this->liste_contact(-1, $source);
  689. $already_added=false;
  690. if(!empty($TListeContacts)) {
  691. foreach($TListeContacts as $array_contact) {
  692. if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
  693. $already_added=true;
  694. break;
  695. }
  696. }
  697. }
  698. if(!$already_added) {
  699. $this->db->begin();
  700. // Insert into database
  701. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
  702. $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
  703. $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
  704. $sql.= "'".$this->db->idate($datecreate)."'";
  705. $sql.= ", 4, ". $id_type_contact;
  706. $sql.= ")";
  707. $resql=$this->db->query($sql);
  708. if ($resql)
  709. {
  710. if (! $notrigger)
  711. {
  712. $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
  713. if ($result < 0)
  714. {
  715. $this->db->rollback();
  716. return -1;
  717. }
  718. }
  719. $this->db->commit();
  720. return 1;
  721. }
  722. else
  723. {
  724. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  725. {
  726. $this->error=$this->db->errno();
  727. $this->db->rollback();
  728. echo 'err rollback';
  729. return -2;
  730. }
  731. else
  732. {
  733. $this->error=$this->db->error();
  734. $this->db->rollback();
  735. return -1;
  736. }
  737. }
  738. } else return 0;
  739. }
  740. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  741. /**
  742. * Copy contact from one element to current
  743. *
  744. * @param CommonObject $objFrom Source element
  745. * @param string $source Nature of contact ('internal' or 'external')
  746. * @return int >0 if OK, <0 if KO
  747. */
  748. function copy_linked_contact($objFrom, $source='internal')
  749. {
  750. // phpcs:enable
  751. $contacts = $objFrom->liste_contact(-1, $source);
  752. foreach($contacts as $contact)
  753. {
  754. if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
  755. {
  756. $this->error=$this->db->lasterror();
  757. return -1;
  758. }
  759. }
  760. return 1;
  761. }
  762. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  763. /**
  764. * Update a link to contact line
  765. *
  766. * @param int $rowid Id of line contact-element
  767. * @param int $statut New status of link
  768. * @param int $type_contact_id Id of contact type (not modified if 0)
  769. * @param int $fk_socpeople Id of soc_people to update (not modified if 0)
  770. * @return int <0 if KO, >= 0 if OK
  771. */
  772. function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
  773. {
  774. // phpcs:enable
  775. // Insert into database
  776. $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
  777. $sql.= " statut = ".$statut;
  778. if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
  779. if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
  780. $sql.= " where rowid = ".$rowid;
  781. $resql=$this->db->query($sql);
  782. if ($resql)
  783. {
  784. return 0;
  785. }
  786. else
  787. {
  788. $this->error=$this->db->lasterror();
  789. return -1;
  790. }
  791. }
  792. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  793. /**
  794. * Delete a link to contact line
  795. *
  796. * @param int $rowid Id of contact link line to delete
  797. * @param int $notrigger Disable all triggers
  798. * @return int >0 if OK, <0 if KO
  799. */
  800. function delete_contact($rowid, $notrigger=0)
  801. {
  802. // phpcs:enable
  803. global $user;
  804. $this->db->begin();
  805. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  806. $sql.= " WHERE rowid =".$rowid;
  807. dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
  808. if ($this->db->query($sql))
  809. {
  810. if (! $notrigger)
  811. {
  812. $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
  813. if ($result < 0) { $this->db->rollback(); return -1; }
  814. }
  815. $this->db->commit();
  816. return 1;
  817. }
  818. else
  819. {
  820. $this->error=$this->db->lasterror();
  821. $this->db->rollback();
  822. return -1;
  823. }
  824. }
  825. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  826. /**
  827. * Delete all links between an object $this and all its contacts
  828. *
  829. * @param string $source '' or 'internal' or 'external'
  830. * @param string $code Type of contact (code or id)
  831. * @return int >0 if OK, <0 if KO
  832. */
  833. function delete_linked_contact($source='',$code='')
  834. {
  835. // phpcs:enable
  836. $temp = array();
  837. $typeContact = $this->liste_type_contact($source,'',0,0,$code);
  838. foreach($typeContact as $key => $value)
  839. {
  840. array_push($temp,$key);
  841. }
  842. $listId = implode(",", $temp);
  843. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
  844. $sql.= " WHERE element_id = ".$this->id;
  845. if ($listId)
  846. $sql.= " AND fk_c_type_contact IN (".$listId.")";
  847. dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
  848. if ($this->db->query($sql))
  849. {
  850. return 1;
  851. }
  852. else
  853. {
  854. $this->error=$this->db->lasterror();
  855. return -1;
  856. }
  857. }
  858. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  859. /**
  860. * Get array of all contacts for an object
  861. *
  862. * @param int $statut Status of links to get (-1=all)
  863. * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
  864. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  865. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  866. * @return array|int Array of contacts, -1 if error
  867. */
  868. function liste_contact($statut=-1,$source='external',$list=0,$code='')
  869. {
  870. // phpcs:enable
  871. global $langs;
  872. $tab=array();
  873. $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
  874. if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
  875. if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
  876. $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  877. $sql.= ", tc.source, tc.element, tc.code, tc.libelle";
  878. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
  879. $sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
  880. if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
  881. if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
  882. $sql.= " WHERE ec.element_id =".$this->id;
  883. $sql.= " AND ec.fk_c_type_contact=tc.rowid";
  884. $sql.= " AND tc.element='".$this->db->escape($this->element)."'";
  885. if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
  886. if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
  887. if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
  888. $sql.= " AND tc.active=1";
  889. if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
  890. $sql.=" ORDER BY t.lastname ASC";
  891. dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
  892. $resql=$this->db->query($sql);
  893. if ($resql)
  894. {
  895. $num=$this->db->num_rows($resql);
  896. $i=0;
  897. while ($i < $num)
  898. {
  899. $obj = $this->db->fetch_object($resql);
  900. if (! $list)
  901. {
  902. $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  903. $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
  904. $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
  905. 'nom'=>$obj->lastname, // For backward compatibility
  906. 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
  907. 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
  908. }
  909. else
  910. {
  911. $tab[$i]=$obj->id;
  912. }
  913. $i++;
  914. }
  915. return $tab;
  916. }
  917. else
  918. {
  919. $this->error=$this->db->lasterror();
  920. dol_print_error($this->db);
  921. return -1;
  922. }
  923. }
  924. /**
  925. * Update status of a contact linked to object
  926. *
  927. * @param int $rowid Id of link between object and contact
  928. * @return int <0 if KO, >=0 if OK
  929. */
  930. function swapContactStatus($rowid)
  931. {
  932. $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
  933. $sql.= " tc.code, tc.libelle";
  934. //$sql.= ", s.fk_soc";
  935. $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
  936. //$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
  937. $sql.= " WHERE ec.rowid =".$rowid;
  938. $sql.= " AND ec.fk_c_type_contact=tc.rowid";
  939. $sql.= " AND tc.element = '".$this->db->escape($this->element)."'";
  940. dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
  941. $resql=$this->db->query($sql);
  942. if ($resql)
  943. {
  944. $obj = $this->db->fetch_object($resql);
  945. $newstatut = ($obj->statut == 4) ? 5 : 4;
  946. $result = $this->update_contact($rowid, $newstatut);
  947. $this->db->free($resql);
  948. return $result;
  949. }
  950. else
  951. {
  952. $this->error=$this->db->error();
  953. dol_print_error($this->db);
  954. return -1;
  955. }
  956. }
  957. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  958. /**
  959. * Return array with list of possible values for type of contacts
  960. *
  961. * @param string $source 'internal', 'external' or 'all'
  962. * @param string $order Sort order by : 'position', 'code', 'rowid'...
  963. * @param int $option 0=Return array id->label, 1=Return array code->label
  964. * @param int $activeonly 0=all status of contact, 1=only the active
  965. * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE')
  966. * @return array Array list of type of contacts (id->label if option=0, code->label if option=1)
  967. */
  968. function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
  969. {
  970. // phpcs:enable
  971. global $langs;
  972. if (empty($order)) $order='position';
  973. if ($order == 'position') $order.=',code';
  974. $tab = array();
  975. $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
  976. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
  977. $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
  978. if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
  979. if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'";
  980. if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'";
  981. $sql.= $this->db->order($order,'ASC');
  982. //print "sql=".$sql;
  983. $resql=$this->db->query($sql);
  984. if ($resql)
  985. {
  986. $num=$this->db->num_rows($resql);
  987. $i=0;
  988. while ($i < $num)
  989. {
  990. $obj = $this->db->fetch_object($resql);
  991. $transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
  992. $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
  993. if (empty($option)) $tab[$obj->rowid]=$libelle_type;
  994. else $tab[$obj->code]=$libelle_type;
  995. $i++;
  996. }
  997. return $tab;
  998. }
  999. else
  1000. {
  1001. $this->error=$this->db->lasterror();
  1002. //dol_print_error($this->db);
  1003. return null;
  1004. }
  1005. }
  1006. /**
  1007. * Return id of contacts for a source and a contact code.
  1008. * Example: contact client de facturation ('external', 'BILLING')
  1009. * Example: contact client de livraison ('external', 'SHIPPING')
  1010. * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
  1011. *
  1012. * @param string $source 'external' or 'internal'
  1013. * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
  1014. * @param int $status limited to a certain status
  1015. * @return array List of id for such contacts
  1016. */
  1017. function getIdContact($source,$code,$status=0)
  1018. {
  1019. global $conf;
  1020. $result=array();
  1021. $i=0;
  1022. //cas particulier pour les expeditions
  1023. if($this->element=='shipping' && $this->origin_id != 0) {
  1024. $id=$this->origin_id;
  1025. $element='commande';
  1026. } else {
  1027. $id=$this->id;
  1028. $element=$this->element;
  1029. }
  1030. $sql = "SELECT ec.fk_socpeople";
  1031. $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
  1032. if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
  1033. if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
  1034. $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
  1035. $sql.= " WHERE ec.element_id = ".$id;
  1036. $sql.= " AND ec.fk_socpeople = c.rowid";
  1037. if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")";
  1038. if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")";
  1039. $sql.= " AND ec.fk_c_type_contact = tc.rowid";
  1040. $sql.= " AND tc.element = '".$element."'";
  1041. $sql.= " AND tc.source = '".$source."'";
  1042. $sql.= " AND tc.code = '".$code."'";
  1043. $sql.= " AND tc.active = 1";
  1044. if ($status) $sql.= " AND ec.statut = ".$status;
  1045. dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
  1046. $resql=$this->db->query($sql);
  1047. if ($resql)
  1048. {
  1049. while ($obj = $this->db->fetch_object($resql))
  1050. {
  1051. $result[$i]=$obj->fk_socpeople;
  1052. $i++;
  1053. }
  1054. }
  1055. else
  1056. {
  1057. $this->error=$this->db->error();
  1058. return null;
  1059. }
  1060. return $result;
  1061. }
  1062. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1063. /**
  1064. * Load object contact with id=$this->contactid into $this->contact
  1065. *
  1066. * @param int $contactid Id du contact. Use this->contactid if empty.
  1067. * @return int <0 if KO, >0 if OK
  1068. */
  1069. function fetch_contact($contactid=null)
  1070. {
  1071. // phpcs:enable
  1072. if (empty($contactid)) $contactid=$this->contactid;
  1073. if (empty($contactid)) return 0;
  1074. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1075. $contact = new Contact($this->db);
  1076. $result=$contact->fetch($contactid);
  1077. $this->contact = $contact;
  1078. return $result;
  1079. }
  1080. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1081. /**
  1082. * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
  1083. *
  1084. * @param int $force_thirdparty_id Force thirdparty id
  1085. * @return int <0 if KO, >0 if OK
  1086. */
  1087. function fetch_thirdparty($force_thirdparty_id=0)
  1088. {
  1089. // phpcs:enable
  1090. global $conf;
  1091. if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
  1092. return 0;
  1093. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1094. $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
  1095. if ($force_thirdparty_id)
  1096. $idtofetch = $force_thirdparty_id;
  1097. if ($idtofetch) {
  1098. $thirdparty = new Societe($this->db);
  1099. $result = $thirdparty->fetch($idtofetch);
  1100. $this->thirdparty = $thirdparty;
  1101. // Use first price level if level not defined for third party
  1102. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
  1103. $this->thirdparty->price_level = 1;
  1104. }
  1105. return $result;
  1106. } else
  1107. return -1;
  1108. }
  1109. /**
  1110. * Looks for an object with ref matching the wildcard provided
  1111. * It does only work when $this->table_ref_field is set
  1112. *
  1113. * @param string $ref Wildcard
  1114. * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
  1115. */
  1116. public function fetchOneLike($ref)
  1117. {
  1118. if (!$this->table_ref_field) {
  1119. return 0;
  1120. }
  1121. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
  1122. $query = $this->db->query($sql);
  1123. if (!$this->db->num_rows($query)) {
  1124. return 0;
  1125. }
  1126. $result = $this->db->fetch_object($query);
  1127. return $this->fetch($result->rowid);
  1128. }
  1129. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1130. /**
  1131. * Load data for barcode into properties ->barcode_type*
  1132. * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
  1133. * if it is not defined, ->element must be defined to know default barcode type.
  1134. *
  1135. * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
  1136. */
  1137. function fetch_barcode()
  1138. {
  1139. // phpcs:enable
  1140. global $conf;
  1141. dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
  1142. $idtype=$this->barcode_type;
  1143. 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
  1144. {
  1145. if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
  1146. else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
  1147. else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
  1148. }
  1149. if ($idtype > 0)
  1150. {
  1151. 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
  1152. {
  1153. $sql = "SELECT rowid, code, libelle as label, coder";
  1154. $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
  1155. $sql.= " WHERE rowid = ".$idtype;
  1156. dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
  1157. $resql = $this->db->query($sql);
  1158. if ($resql)
  1159. {
  1160. $obj = $this->db->fetch_object($resql);
  1161. $this->barcode_type = $obj->rowid;
  1162. $this->barcode_type_code = $obj->code;
  1163. $this->barcode_type_label = $obj->label;
  1164. $this->barcode_type_coder = $obj->coder;
  1165. return 1;
  1166. }
  1167. else
  1168. {
  1169. dol_print_error($this->db);
  1170. return -1;
  1171. }
  1172. }
  1173. }
  1174. return 0;
  1175. }
  1176. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1177. /**
  1178. * Load the project with id $this->fk_project into this->project
  1179. *
  1180. * @return int <0 if KO, >=0 if OK
  1181. */
  1182. function fetch_projet()
  1183. {
  1184. // phpcs:enable
  1185. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  1186. if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility
  1187. if (empty($this->fk_project)) return 0;
  1188. $project = new Project($this->db);
  1189. $result = $project->fetch($this->fk_project);
  1190. $this->projet = $project; // deprecated
  1191. $this->project = $project;
  1192. return $result;
  1193. }
  1194. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1195. /**
  1196. * Load the product with id $this->fk_product into this->product
  1197. *
  1198. * @return int <0 if KO, >=0 if OK
  1199. */
  1200. function fetch_product()
  1201. {
  1202. // phpcs:enable
  1203. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1204. if (empty($this->fk_product)) return 0;
  1205. $product = new Product($this->db);
  1206. $result = $product->fetch($this->fk_product);
  1207. $this->product = $product;
  1208. return $result;
  1209. }
  1210. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1211. /**
  1212. * Load the user with id $userid into this->user
  1213. *
  1214. * @param int $userid Id du contact
  1215. * @return int <0 if KO, >0 if OK
  1216. */
  1217. function fetch_user($userid)
  1218. {
  1219. // phpcs:enable
  1220. $user = new User($this->db);
  1221. $result=$user->fetch($userid);
  1222. $this->user = $user;
  1223. return $result;
  1224. }
  1225. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1226. /**
  1227. * Read linked origin object
  1228. *
  1229. * @return void
  1230. */
  1231. function fetch_origin()
  1232. {
  1233. // phpcs:enable
  1234. if ($this->origin == 'shipping') $this->origin = 'expedition';
  1235. if ($this->origin == 'delivery') $this->origin = 'livraison';
  1236. $origin = $this->origin;
  1237. $classname = ucfirst($origin);
  1238. $this->$origin = new $classname($this->db);
  1239. $this->$origin->fetch($this->origin_id);
  1240. }
  1241. /**
  1242. * Load object from specific field
  1243. *
  1244. * @param string $table Table element or element line
  1245. * @param string $field Field selected
  1246. * @param string $key Import key
  1247. * @param string $element Element name
  1248. * @return int <0 if KO, >0 if OK
  1249. */
  1250. function fetchObjectFrom($table, $field, $key, $element = null)
  1251. {
  1252. global $conf;
  1253. $result=false;
  1254. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
  1255. $sql.= " WHERE ".$field." = '".$key."'";
  1256. if (! empty($element)) {
  1257. $sql.= " AND entity IN (".getEntity($element).")";
  1258. } else {
  1259. $sql.= " AND entity = ".$conf->entity;
  1260. }
  1261. dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
  1262. $resql = $this->db->query($sql);
  1263. if ($resql)
  1264. {
  1265. $row = $this->db->fetch_row($resql);
  1266. // Test for avoid error -1
  1267. if ($row[0] > 0) {
  1268. $result = $this->fetch($row[0]);
  1269. }
  1270. }
  1271. return $result;
  1272. }
  1273. /**
  1274. * Getter generic. Load value from a specific field
  1275. *
  1276. * @param string $table Table of element or element line
  1277. * @param int $id Element id
  1278. * @param string $field Field selected
  1279. * @return int <0 if KO, >0 if OK
  1280. */
  1281. function getValueFrom($table, $id, $field)
  1282. {
  1283. $result=false;
  1284. if (!empty($id) && !empty($field) && !empty($table)) {
  1285. $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
  1286. $sql.= " WHERE rowid = ".$id;
  1287. dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
  1288. $resql = $this->db->query($sql);
  1289. if ($resql)
  1290. {
  1291. $row = $this->db->fetch_row($resql);
  1292. $result = $row[0];
  1293. }
  1294. }
  1295. return $result;
  1296. }
  1297. /**
  1298. * Setter generic. Update a specific field into database.
  1299. * Warning: Trigger is run only if param trigkey is provided.
  1300. *
  1301. * @param string $field Field to update
  1302. * @param mixed $value New value
  1303. * @param string $table To force other table element or element line (should not be used)
  1304. * @param int $id To force other object id (should not be used)
  1305. * @param string $format Data format ('text', 'date'). 'text' is used if not defined
  1306. * @param string $id_field To force rowid field name. 'rowid' is used if not defined
  1307. * @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'
  1308. * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY')
  1309. * @param string $fk_user_field Name of field to save user id making change
  1310. * @return int <0 if KO, >0 if OK
  1311. * @see updateExtraField
  1312. */
  1313. function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
  1314. {
  1315. global $user,$langs,$conf;
  1316. if (empty($table)) $table=$this->table_element;
  1317. if (empty($id)) $id=$this->id;
  1318. if (empty($format)) $format='text';
  1319. if (empty($id_field)) $id_field='rowid';
  1320. $error=0;
  1321. $this->db->begin();
  1322. // Special case
  1323. if ($table == 'product' && $field == 'note_private') $field='note';
  1324. if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
  1325. $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
  1326. if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'";
  1327. else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value);
  1328. else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
  1329. if ($fk_user_field)
  1330. {
  1331. if (! empty($fuser) && is_object($fuser)) $sql.=", ".$fk_user_field." = ".$fuser->id;
  1332. elseif (empty($fuser) || $fuser != 'none') $sql.=", ".$fk_user_field." = ".$user->id;
  1333. }
  1334. $sql.= " WHERE ".$id_field." = ".$id;
  1335. dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
  1336. $resql = $this->db->query($sql);
  1337. if ($resql)
  1338. {
  1339. if ($trigkey)
  1340. {
  1341. // call trigger with updated object values
  1342. if (empty($this->fields) && method_exists($this, 'fetch'))
  1343. {
  1344. $result = $this->fetch($id);
  1345. }
  1346. else
  1347. {
  1348. $result = $this->fetchCommon($id);
  1349. }
  1350. if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
  1351. if ($result < 0) $error++;
  1352. }
  1353. if (! $error)
  1354. {
  1355. if (property_exists($this, $field)) $this->$field = $value;
  1356. $this->db->commit();
  1357. return 1;
  1358. }
  1359. else
  1360. {
  1361. $this->db->rollback();
  1362. return -2;
  1363. }
  1364. }
  1365. else
  1366. {
  1367. $this->error=$this->db->lasterror();
  1368. $this->db->rollback();
  1369. return -1;
  1370. }
  1371. }
  1372. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1373. /**
  1374. * Load properties id_previous and id_next by comparing $fieldid with $this->ref
  1375. *
  1376. * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
  1377. * @param string $fieldid Name of field to use for the select MAX and MIN
  1378. * @param int $nodbprefix Do not include DB prefix to forge table name
  1379. * @return int <0 if KO, >0 if OK
  1380. */
  1381. function load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
  1382. {
  1383. // phpcs:enable
  1384. global $conf, $user;
  1385. if (! $this->table_element)
  1386. {
  1387. dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
  1388. return -1;
  1389. }
  1390. if ($fieldid == 'none') return 1;
  1391. // Security on socid
  1392. $socid = 0;
  1393. if ($user->societe_id > 0) $socid = $user->societe_id;
  1394. // this->ismultientitymanaged contains
  1395. // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  1396. $alias = 's';
  1397. if ($this->element == 'societe') $alias = 'te';
  1398. $sql = "SELECT MAX(te.".$fieldid.")";
  1399. $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1400. if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1401. $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1402. }
  1403. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity
  1404. else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1405. else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1406. if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
  1407. $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1408. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id;
  1409. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
  1410. if (! empty($filter))
  1411. {
  1412. if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility
  1413. $sql.=$filter;
  1414. }
  1415. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
  1416. else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1417. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1418. if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1419. if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1420. $sql.= " AND te.entity IS NOT NULL"; // Show all users
  1421. } else {
  1422. $sql.= " AND ug.fk_user = te.rowid";
  1423. $sql.= " AND ug.entity IN (".getEntity($this->element).")";
  1424. }
  1425. } else {
  1426. $sql.= ' AND te.entity IN ('.getEntity($this->element).')';
  1427. }
  1428. }
  1429. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid;
  1430. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
  1431. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid;
  1432. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1433. $result = $this->db->query($sql);
  1434. if (! $result)
  1435. {
  1436. $this->error=$this->db->lasterror();
  1437. return -1;
  1438. }
  1439. $row = $this->db->fetch_row($result);
  1440. $this->ref_previous = $row[0];
  1441. $sql = "SELECT MIN(te.".$fieldid.")";
  1442. $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
  1443. if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1444. $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  1445. }
  1446. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity
  1447. else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
  1448. else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
  1449. if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
  1450. $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
  1451. if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id;
  1452. if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
  1453. if (! empty($filter))
  1454. {
  1455. if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility
  1456. $sql.=$filter;
  1457. }
  1458. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
  1459. else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
  1460. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1461. if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1462. if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
  1463. $sql.= " AND te.entity IS NOT NULL"; // Show all users
  1464. } else {
  1465. $sql.= " AND ug.fk_user = te.rowid";
  1466. $sql.= " AND ug.entity IN (".getEntity($this->element).")";
  1467. }
  1468. } else {
  1469. $sql.= ' AND te.entity IN ('.getEntity($this->element).')';
  1470. }
  1471. }
  1472. if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid;
  1473. if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
  1474. if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid;
  1475. //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
  1476. // 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
  1477. $result = $this->db->query($sql);
  1478. if (! $result)
  1479. {
  1480. $this->error=$this->db->lasterror();
  1481. return -2;
  1482. }
  1483. $row = $this->db->fetch_row($result);
  1484. $this->ref_next = $row[0];
  1485. return 1;
  1486. }
  1487. /**
  1488. * Return list of id of contacts of object
  1489. *
  1490. * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
  1491. * @return array Array of id of contacts (if source=external or internal)
  1492. * Array of id of third parties with at least one contact on object (if source=thirdparty)
  1493. */
  1494. function getListContactId($source='external')
  1495. {
  1496. $contactAlreadySelected = array();
  1497. $tab = $this->liste_contact(-1,$source);
  1498. $num=count($tab);
  1499. $i = 0;
  1500. while ($i < $num)
  1501. {
  1502. if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
  1503. else $contactAlreadySelected[$i] = $tab[$i]['id'];
  1504. $i++;
  1505. }
  1506. return $contactAlreadySelected;
  1507. }
  1508. /**
  1509. * Link element with a project
  1510. *
  1511. * @param int $projectid Project id to link element to
  1512. * @return int <0 if KO, >0 if OK
  1513. */
  1514. function setProject($projectid)
  1515. {
  1516. if (! $this->table_element)
  1517. {
  1518. dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR);
  1519. return -1;
  1520. }
  1521. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1522. if ($this->table_element == 'actioncomm')
  1523. {
  1524. if ($projectid) $sql.= ' SET fk_project = '.$projectid;
  1525. else $sql.= ' SET fk_project = NULL';
  1526. $sql.= ' WHERE id = '.$this->id;
  1527. }
  1528. else
  1529. {
  1530. if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
  1531. else $sql.= ' SET fk_projet = NULL';
  1532. $sql.= ' WHERE rowid = '.$this->id;
  1533. }
  1534. dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
  1535. if ($this->db->query($sql))
  1536. {
  1537. $this->fk_project = $projectid;
  1538. return 1;
  1539. }
  1540. else
  1541. {
  1542. dol_print_error($this->db);
  1543. return -1;
  1544. }
  1545. }
  1546. /**
  1547. * Change the payments methods
  1548. *
  1549. * @param int $id Id of new payment method
  1550. * @return int >0 if OK, <0 if KO
  1551. */
  1552. function setPaymentMethods($id)
  1553. {
  1554. dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
  1555. if ($this->statut >= 0 || $this->element == 'societe')
  1556. {
  1557. // TODO uniformize field name
  1558. $fieldname = 'fk_mode_reglement';
  1559. if ($this->element == 'societe') $fieldname = 'mode_reglement';
  1560. if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
  1561. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1562. $sql .= ' SET '.$fieldname.' = '.$id;
  1563. $sql .= ' WHERE rowid='.$this->id;
  1564. if ($this->db->query($sql))
  1565. {
  1566. $this->mode_reglement_id = $id;
  1567. // for supplier
  1568. if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
  1569. return 1;
  1570. }
  1571. else
  1572. {
  1573. dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
  1574. $this->error=$this->db->error();
  1575. return -1;
  1576. }
  1577. }
  1578. else
  1579. {
  1580. dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
  1581. $this->error='Status of the object is incompatible '.$this->statut;
  1582. return -2;
  1583. }
  1584. }
  1585. /**
  1586. * Change the multicurrency code
  1587. *
  1588. * @param string $code multicurrency code
  1589. * @return int >0 if OK, <0 if KO
  1590. */
  1591. function setMulticurrencyCode($code)
  1592. {
  1593. dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')');
  1594. if ($this->statut >= 0 || $this->element == 'societe')
  1595. {
  1596. $fieldname = 'multicurrency_code';
  1597. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1598. $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
  1599. $sql .= ' WHERE rowid='.$this->id;
  1600. if ($this->db->query($sql))
  1601. {
  1602. $this->multicurrency_code = $code;
  1603. list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
  1604. if ($rate) $this->setMulticurrencyRate($rate,2);
  1605. return 1;
  1606. }
  1607. else
  1608. {
  1609. dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
  1610. $this->error=$this->db->error();
  1611. return -1;
  1612. }
  1613. }
  1614. else
  1615. {
  1616. dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
  1617. $this->error='Status of the object is incompatible '.$this->statut;
  1618. return -2;
  1619. }
  1620. }
  1621. /**
  1622. * Change the multicurrency rate
  1623. *
  1624. * @param double $rate multicurrency rate
  1625. * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency
  1626. * @return int >0 if OK, <0 if KO
  1627. */
  1628. function setMulticurrencyRate($rate, $mode=1)
  1629. {
  1630. dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')');
  1631. if ($this->statut >= 0 || $this->element == 'societe')
  1632. {
  1633. $fieldname = 'multicurrency_tx';
  1634. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1635. $sql .= ' SET '.$fieldname.' = '.$rate;
  1636. $sql .= ' WHERE rowid='.$this->id;
  1637. if ($this->db->query($sql))
  1638. {
  1639. $this->multicurrency_tx = $rate;
  1640. // Update line price
  1641. if (!empty($this->lines))
  1642. {
  1643. foreach ($this->lines as &$line)
  1644. {
  1645. if($mode == 1) {
  1646. $line->subprice = 0;
  1647. }
  1648. switch ($this->element) {
  1649. case 'propal':
  1650. $this->updateline(
  1651. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1652. ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1653. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
  1654. $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1655. );
  1656. break;
  1657. case 'commande':
  1658. $this->updateline(
  1659. $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1660. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
  1661. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1662. $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1663. );
  1664. break;
  1665. case 'facture':
  1666. $this->updateline(
  1667. $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1668. $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
  1669. $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
  1670. $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
  1671. );
  1672. break;
  1673. case 'supplier_proposal':
  1674. $this->updateline(
  1675. $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
  1676. ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
  1677. $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
  1678. $line->ref_fourn, $line->multicurrency_subprice
  1679. );
  1680. break;
  1681. case 'order_supplier':
  1682. $this->updateline(
  1683. $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
  1684. $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
  1685. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1686. );
  1687. break;
  1688. case 'invoice_supplier':
  1689. $this->updateline(
  1690. $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
  1691. $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
  1692. $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
  1693. );
  1694. break;
  1695. default:
  1696. dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
  1697. break;
  1698. }
  1699. }
  1700. }
  1701. return 1;
  1702. }
  1703. else
  1704. {
  1705. dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
  1706. $this->error=$this->db->error();
  1707. return -1;
  1708. }
  1709. }
  1710. else
  1711. {
  1712. dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
  1713. $this->error='Status of the object is incompatible '.$this->statut;
  1714. return -2;
  1715. }
  1716. }
  1717. /**
  1718. * Change the payments terms
  1719. *
  1720. * @param int $id Id of new payment terms
  1721. * @return int >0 if OK, <0 if KO
  1722. */
  1723. function setPaymentTerms($id)
  1724. {
  1725. dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
  1726. if ($this->statut >= 0 || $this->element == 'societe')
  1727. {
  1728. // TODO uniformize field name
  1729. $fieldname = 'fk_cond_reglement';
  1730. if ($this->element == 'societe') $fieldname = 'cond_reglement';
  1731. if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
  1732. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1733. $sql .= ' SET '.$fieldname.' = '.$id;
  1734. $sql .= ' WHERE rowid='.$this->id;
  1735. if ($this->db->query($sql))
  1736. {
  1737. $this->cond_reglement_id = $id;
  1738. // for supplier
  1739. if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
  1740. $this->cond_reglement = $id; // for compatibility
  1741. return 1;
  1742. }
  1743. else
  1744. {
  1745. dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
  1746. $this->error=$this->db->error();
  1747. return -1;
  1748. }
  1749. }
  1750. else
  1751. {
  1752. dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
  1753. $this->error='Status of the object is incompatible '.$this->statut;
  1754. return -2;
  1755. }
  1756. }
  1757. /**
  1758. * Define delivery address
  1759. * @deprecated
  1760. *
  1761. * @param int $id Address id
  1762. * @return int <0 si ko, >0 si ok
  1763. */
  1764. function setDeliveryAddress($id)
  1765. {
  1766. $fieldname = 'fk_delivery_address';
  1767. if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
  1768. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
  1769. $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
  1770. if ($this->db->query($sql))
  1771. {
  1772. $this->fk_delivery_address = $id;
  1773. return 1;
  1774. }
  1775. else
  1776. {
  1777. $this->error=$this->db->error();
  1778. dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
  1779. return -1;
  1780. }
  1781. }
  1782. /**
  1783. * Change the shipping method
  1784. *
  1785. * @param int $shipping_method_id Id of shipping method
  1786. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1787. * @param User $userused Object user
  1788. *
  1789. * @return int 1 if OK, 0 if KO
  1790. */
  1791. function setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
  1792. {
  1793. global $user;
  1794. if (empty($userused)) $userused=$user;
  1795. $error = 0;
  1796. if (! $this->table_element) {
  1797. dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR);
  1798. return -1;
  1799. }
  1800. $this->db->begin();
  1801. if ($shipping_method_id<0) $shipping_method_id='NULL';
  1802. dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
  1803. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1804. $sql.= " SET fk_shipping_method = ".$shipping_method_id;
  1805. $sql.= " WHERE rowid=".$this->id;
  1806. $resql = $this->db->query($sql);
  1807. if (! $resql) {
  1808. dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
  1809. $this->error = $this->db->lasterror();
  1810. $error++;
  1811. } else {
  1812. if (!$notrigger)
  1813. {
  1814. // Call trigger
  1815. $this->context=array('shippingmethodupdate'=>1);
  1816. $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
  1817. if ($result < 0) $error++;
  1818. // End call trigger
  1819. }
  1820. }
  1821. if ($error)
  1822. {
  1823. $this->db->rollback();
  1824. return -1;
  1825. } else {
  1826. $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id;
  1827. $this->db->commit();
  1828. return 1;
  1829. }
  1830. }
  1831. /**
  1832. * Change the warehouse
  1833. *
  1834. * @param int $warehouse_id Id of warehouse
  1835. * @return int 1 if OK, 0 if KO
  1836. */
  1837. function setWarehouse($warehouse_id)
  1838. {
  1839. if (! $this->table_element) {
  1840. dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR);
  1841. return -1;
  1842. }
  1843. if ($warehouse_id<0) $warehouse_id='NULL';
  1844. dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
  1845. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1846. $sql.= " SET fk_warehouse = ".$warehouse_id;
  1847. $sql.= " WHERE rowid=".$this->id;
  1848. if ($this->db->query($sql)) {
  1849. $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id;
  1850. return 1;
  1851. } else {
  1852. dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
  1853. $this->error=$this->db->error();
  1854. return 0;
  1855. }
  1856. }
  1857. /**
  1858. * Set last model used by doc generator
  1859. *
  1860. * @param User $user User object that make change
  1861. * @param string $modelpdf Modele name
  1862. * @return int <0 if KO, >0 if OK
  1863. */
  1864. function setDocModel($user, $modelpdf)
  1865. {
  1866. if (! $this->table_element)
  1867. {
  1868. dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR);
  1869. return -1;
  1870. }
  1871. $newmodelpdf=dol_trunc($modelpdf,255);
  1872. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1873. $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
  1874. $sql.= " WHERE rowid = ".$this->id;
  1875. // if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
  1876. // if ($this->element == 'propal') $sql.= " AND fk_statut = 0";
  1877. dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
  1878. $resql=$this->db->query($sql);
  1879. if ($resql)
  1880. {
  1881. $this->modelpdf=$modelpdf;
  1882. return 1;
  1883. }
  1884. else
  1885. {
  1886. dol_print_error($this->db);
  1887. return 0;
  1888. }
  1889. }
  1890. /**
  1891. * Change the bank account
  1892. *
  1893. * @param int $fk_account Id of bank account
  1894. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1895. * @param User $userused Object user
  1896. * @return int 1 if OK, 0 if KO
  1897. */
  1898. function setBankAccount($fk_account, $notrigger=false, $userused=null)
  1899. {
  1900. global $user;
  1901. if (empty($userused)) $userused=$user;
  1902. $error = 0;
  1903. if (! $this->table_element) {
  1904. dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR);
  1905. return -1;
  1906. }
  1907. $this->db->begin();
  1908. if ($fk_account<0) $fk_account='NULL';
  1909. dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
  1910. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1911. $sql.= " SET fk_account = ".$fk_account;
  1912. $sql.= " WHERE rowid=".$this->id;
  1913. $resql = $this->db->query($sql);
  1914. if (! $resql)
  1915. {
  1916. dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
  1917. $this->error = $this->db->lasterror();
  1918. $error++;
  1919. }
  1920. else
  1921. {
  1922. if (!$notrigger)
  1923. {
  1924. // Call trigger
  1925. $this->context=array('bankaccountupdate'=>1);
  1926. $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
  1927. if ($result < 0) $error++;
  1928. // End call trigger
  1929. }
  1930. }
  1931. if ($error)
  1932. {
  1933. $this->db->rollback();
  1934. return -1;
  1935. }
  1936. else
  1937. {
  1938. $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
  1939. $this->db->commit();
  1940. return 1;
  1941. }
  1942. }
  1943. // TODO: Move line related operations to CommonObjectLine?
  1944. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1945. /**
  1946. * Save a new position (field rang) for details lines.
  1947. * You can choose to set position for lines with already a position or lines without any position defined.
  1948. *
  1949. * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines.
  1950. * @param string $rowidorder ASC or DESC
  1951. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  1952. * @return int <0 if KO, >0 if OK
  1953. */
  1954. function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
  1955. {
  1956. // phpcs:enable
  1957. if (! $this->table_element_line)
  1958. {
  1959. dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR);
  1960. return -1;
  1961. }
  1962. if (! $this->fk_element)
  1963. {
  1964. dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR);
  1965. return -1;
  1966. }
  1967. // Count number of lines to reorder (according to choice $renum)
  1968. $nl=0;
  1969. $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1970. $sql.= ' WHERE '.$this->fk_element.'='.$this->id;
  1971. if (! $renum) $sql.= ' AND rang = 0';
  1972. if ($renum) $sql.= ' AND rang <> 0';
  1973. dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
  1974. $resql = $this->db->query($sql);
  1975. if ($resql)
  1976. {
  1977. $row = $this->db->fetch_row($resql);
  1978. $nl = $row[0];
  1979. }
  1980. else dol_print_error($this->db);
  1981. if ($nl > 0)
  1982. {
  1983. // The goal of this part is to reorder all lines, with all children lines sharing the same
  1984. // counter that parents.
  1985. $rows=array();
  1986. // We first search all lines that are parent lines (for multilevel details lines)
  1987. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  1988. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  1989. if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL';
  1990. $sql.= ' ORDER BY rang ASC, rowid '.$rowidorder;
  1991. dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
  1992. $resql = $this->db->query($sql);
  1993. if ($resql)
  1994. {
  1995. $i=0;
  1996. $num = $this->db->num_rows($resql);
  1997. while ($i < $num)
  1998. {
  1999. $row = $this->db->fetch_row($resql);
  2000. $rows[] = $row[0]; // Add parent line into array rows
  2001. $childrens = $this->getChildrenOfLine($row[0]);
  2002. if (! empty($childrens))
  2003. {
  2004. foreach($childrens as $child)
  2005. {
  2006. array_push($rows, $child);
  2007. }
  2008. }
  2009. $i++;
  2010. }
  2011. // Now we set a new number for each lines (parent and children with children included into parent tree)
  2012. if (! empty($rows))
  2013. {
  2014. foreach($rows as $key => $row)
  2015. {
  2016. $this->updateRangOfLine($row, ($key+1));
  2017. }
  2018. }
  2019. }
  2020. else
  2021. {
  2022. dol_print_error($this->db);
  2023. }
  2024. }
  2025. return 1;
  2026. }
  2027. /**
  2028. * Get children of line
  2029. *
  2030. * @param int $id Id of parent line
  2031. * @return array Array with list of children lines id
  2032. */
  2033. function getChildrenOfLine($id)
  2034. {
  2035. $rows=array();
  2036. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2037. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2038. $sql.= ' AND fk_parent_line = '.$id;
  2039. $sql.= ' ORDER BY rang ASC';
  2040. dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
  2041. $resql = $this->db->query($sql);
  2042. if ($resql)
  2043. {
  2044. $i=0;
  2045. $num = $this->db->num_rows($resql);
  2046. while ($i < $num)
  2047. {
  2048. $row = $this->db->fetch_row($resql);
  2049. $rows[$i] = $row[0];
  2050. $i++;
  2051. }
  2052. }
  2053. return $rows;
  2054. }
  2055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2056. /**
  2057. * Update a line to have a lower rank
  2058. *
  2059. * @param int $rowid Id of line
  2060. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2061. * @return void
  2062. */
  2063. function line_up($rowid, $fk_parent_line=true)
  2064. {
  2065. // phpcs:enable
  2066. $this->line_order(false, 'ASC', $fk_parent_line);
  2067. // Get rang of line
  2068. $rang = $this->getRangOfLine($rowid);
  2069. // Update position of line
  2070. $this->updateLineUp($rowid, $rang);
  2071. }
  2072. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2073. /**
  2074. * Update a line to have a higher rank
  2075. *
  2076. * @param int $rowid Id of line
  2077. * @param boolean $fk_parent_line Table with fk_parent_line field or not
  2078. * @return void
  2079. */
  2080. function line_down($rowid, $fk_parent_line=true)
  2081. {
  2082. // phpcs:enable
  2083. $this->line_order(false, 'ASC', $fk_parent_line);
  2084. // Get rang of line
  2085. $rang = $this->getRangOfLine($rowid);
  2086. // Get max value for rang
  2087. $max = $this->line_max();
  2088. // Update position of line
  2089. $this->updateLineDown($rowid, $rang, $max);
  2090. }
  2091. /**
  2092. * Update position of line (rang)
  2093. *
  2094. * @param int $rowid Id of line
  2095. * @param int $rang Position
  2096. * @return void
  2097. */
  2098. function updateRangOfLine($rowid,$rang)
  2099. {
  2100. $fieldposition = 'rang';
  2101. if ($this->table_element_line == 'ecm_files') $fieldposition = 'position';
  2102. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
  2103. $sql.= ' WHERE rowid = '.$rowid;
  2104. dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
  2105. if (! $this->db->query($sql))
  2106. {
  2107. dol_print_error($this->db);
  2108. }
  2109. }
  2110. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2111. /**
  2112. * Update position of line with ajax (rang)
  2113. *
  2114. * @param array $rows Array of rows
  2115. * @return void
  2116. */
  2117. function line_ajaxorder($rows)
  2118. {
  2119. // phpcs:enable
  2120. $num = count($rows);
  2121. for ($i = 0 ; $i < $num ; $i++)
  2122. {
  2123. $this->updateRangOfLine($rows[$i], ($i+1));
  2124. }
  2125. }
  2126. /**
  2127. * Update position of line up (rang)
  2128. *
  2129. * @param int $rowid Id of line
  2130. * @param int $rang Position
  2131. * @return void
  2132. */
  2133. function updateLineUp($rowid,$rang)
  2134. {
  2135. if ($rang > 1 )
  2136. {
  2137. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ;
  2138. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2139. $sql.= ' AND rang = '.($rang - 1);
  2140. if ($this->db->query($sql) )
  2141. {
  2142. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1);
  2143. $sql.= ' WHERE rowid = '.$rowid;
  2144. if (! $this->db->query($sql) )
  2145. {
  2146. dol_print_error($this->db);
  2147. }
  2148. }
  2149. else
  2150. {
  2151. dol_print_error($this->db);
  2152. }
  2153. }
  2154. }
  2155. /**
  2156. * Update position of line down (rang)
  2157. *
  2158. * @param int $rowid Id of line
  2159. * @param int $rang Position
  2160. * @param int $max Max
  2161. * @return void
  2162. */
  2163. function updateLineDown($rowid,$rang,$max)
  2164. {
  2165. if ($rang < $max)
  2166. {
  2167. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang;
  2168. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2169. $sql.= ' AND rang = '.($rang+1);
  2170. if ($this->db->query($sql) )
  2171. {
  2172. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1);
  2173. $sql.= ' WHERE rowid = '.$rowid;
  2174. if (! $this->db->query($sql) )
  2175. {
  2176. dol_print_error($this->db);
  2177. }
  2178. }
  2179. else
  2180. {
  2181. dol_print_error($this->db);
  2182. }
  2183. }
  2184. }
  2185. /**
  2186. * Get position of line (rang)
  2187. *
  2188. * @param int $rowid Id of line
  2189. * @return int Value of rang in table of lines
  2190. */
  2191. function getRangOfLine($rowid)
  2192. {
  2193. $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2194. $sql.= ' WHERE rowid ='.$rowid;
  2195. dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
  2196. $resql = $this->db->query($sql);
  2197. if ($resql)
  2198. {
  2199. $row = $this->db->fetch_row($resql);
  2200. return $row[0];
  2201. }
  2202. }
  2203. /**
  2204. * Get rowid of the line relative to its position
  2205. *
  2206. * @param int $rang Rang value
  2207. * @return int Rowid of the line
  2208. */
  2209. function getIdOfLine($rang)
  2210. {
  2211. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2212. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2213. $sql.= ' AND rang = '.$rang;
  2214. $resql = $this->db->query($sql);
  2215. if ($resql)
  2216. {
  2217. $row = $this->db->fetch_row($resql);
  2218. return $row[0];
  2219. }
  2220. }
  2221. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2222. /**
  2223. * Get max value used for position of line (rang)
  2224. *
  2225. * @param int $fk_parent_line Parent line id
  2226. * @return int Max value of rang in table of lines
  2227. */
  2228. function line_max($fk_parent_line=0)
  2229. {
  2230. // phpcs:enable
  2231. // Search the last rang with fk_parent_line
  2232. if ($fk_parent_line)
  2233. {
  2234. $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2235. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2236. $sql.= ' AND fk_parent_line = '.$fk_parent_line;
  2237. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2238. $resql = $this->db->query($sql);
  2239. if ($resql)
  2240. {
  2241. $row = $this->db->fetch_row($resql);
  2242. if (! empty($row[0]))
  2243. {
  2244. return $row[0];
  2245. }
  2246. else
  2247. {
  2248. return $this->getRangOfLine($fk_parent_line);
  2249. }
  2250. }
  2251. }
  2252. // If not, search the last rang of element
  2253. else
  2254. {
  2255. $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2256. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2257. dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
  2258. $resql = $this->db->query($sql);
  2259. if ($resql)
  2260. {
  2261. $row = $this->db->fetch_row($resql);
  2262. return $row[0];
  2263. }
  2264. }
  2265. }
  2266. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2267. /**
  2268. * Update external ref of element
  2269. *
  2270. * @param string $ref_ext Update field ref_ext
  2271. * @return int <0 if KO, >0 if OK
  2272. */
  2273. function update_ref_ext($ref_ext)
  2274. {
  2275. // phpcs:enable
  2276. if (! $this->table_element)
  2277. {
  2278. dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
  2279. return -1;
  2280. }
  2281. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2282. $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
  2283. $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id;
  2284. dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
  2285. if ($this->db->query($sql))
  2286. {
  2287. $this->ref_ext = $ref_ext;
  2288. return 1;
  2289. }
  2290. else
  2291. {
  2292. $this->error=$this->db->error();
  2293. return -1;
  2294. }
  2295. }
  2296. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2297. /**
  2298. * Update note of element
  2299. *
  2300. * @param string $note New value for note
  2301. * @param string $suffix '', '_public' or '_private'
  2302. * @return int <0 if KO, >0 if OK
  2303. */
  2304. function update_note($note, $suffix='')
  2305. {
  2306. // phpcs:enable
  2307. global $user;
  2308. if (! $this->table_element)
  2309. {
  2310. $this->error='update_note was called on objet with property table_element not defined';
  2311. dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
  2312. return -1;
  2313. }
  2314. if (! in_array($suffix,array('','_public','_private')))
  2315. {
  2316. $this->error='update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
  2317. dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
  2318. return -2;
  2319. }
  2320. // Special cas
  2321. //var_dump($this->table_element);exit;
  2322. if ($this->table_element == 'product') $suffix='';
  2323. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  2324. $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
  2325. $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id;
  2326. $sql.= " WHERE rowid =". $this->id;
  2327. dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
  2328. if ($this->db->query($sql))
  2329. {
  2330. if ($suffix == '_public') $this->note_public = $note;
  2331. else if ($suffix == '_private') $this->note_private = $note;
  2332. else
  2333. {
  2334. $this->note = $note; // deprecated
  2335. $this->note_private = $note;
  2336. }
  2337. return 1;
  2338. }
  2339. else
  2340. {
  2341. $this->error=$this->db->lasterror();
  2342. return -1;
  2343. }
  2344. }
  2345. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2346. /**
  2347. * Update public note (kept for backward compatibility)
  2348. *
  2349. * @param string $note New value for note
  2350. * @return int <0 if KO, >0 if OK
  2351. * @deprecated
  2352. * @see update_note()
  2353. */
  2354. function update_note_public($note)
  2355. {
  2356. // phpcs:enable
  2357. return $this->update_note($note,'_public');
  2358. }
  2359. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2360. /**
  2361. * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
  2362. * Must be called at end of methods addline or updateline.
  2363. *
  2364. * @param int $exclspec >0 = Exclude special product (product_type=9)
  2365. * @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
  2366. * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object.
  2367. * @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.
  2368. * @return int <0 if KO, >0 if OK
  2369. */
  2370. function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null)
  2371. {
  2372. // phpcs:enable
  2373. global $conf, $hookmanager, $action;
  2374. // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
  2375. $MODULE = "";
  2376. if ($this->element == 'propal')
  2377. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
  2378. elseif ($this->element == 'order')
  2379. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
  2380. elseif ($this->element == 'facture')
  2381. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
  2382. elseif ($this->element == 'facture_fourn')
  2383. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
  2384. elseif ($this->element == 'order_supplier')
  2385. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
  2386. elseif ($this->element == 'supplier_proposal')
  2387. $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
  2388. if (! empty($MODULE)) {
  2389. if (! empty($conf->global->$MODULE)) {
  2390. $modsactivated = explode(',', $conf->global->$MODULE);
  2391. foreach ($modsactivated as $mod) {
  2392. if ($conf->$mod->enabled)
  2393. return 1; // update was disabled by specific setup
  2394. }
  2395. }
  2396. }
  2397. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2398. if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility
  2399. $forcedroundingmode=$roundingadjust;
  2400. if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
  2401. elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
  2402. $error=0;
  2403. $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
  2404. // Define constants to find lines to sum
  2405. $fieldtva='total_tva';
  2406. $fieldlocaltax1='total_localtax1';
  2407. $fieldlocaltax2='total_localtax2';
  2408. $fieldup='subprice';
  2409. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  2410. {
  2411. $fieldtva='tva';
  2412. $fieldup='pu_ht';
  2413. }
  2414. if ($this->element == 'expensereport')
  2415. {
  2416. $fieldup='value_unit';
  2417. }
  2418. $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,';
  2419. $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
  2420. if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
  2421. $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  2422. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  2423. $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
  2424. if ($exclspec)
  2425. {
  2426. $product_field='product_type';
  2427. if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field
  2428. if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
  2429. }
  2430. $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
  2431. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2432. $resql = $this->db->query($sql);
  2433. if ($resql)
  2434. {
  2435. $this->total_ht = 0;
  2436. $this->total_tva = 0;
  2437. $this->total_localtax1 = 0;
  2438. $this->total_localtax2 = 0;
  2439. $this->total_ttc = 0;
  2440. $total_ht_by_vats = array();
  2441. $total_tva_by_vats = array();
  2442. $total_ttc_by_vats = array();
  2443. $this->multicurrency_total_ht = 0;
  2444. $this->multicurrency_total_tva = 0;
  2445. $this->multicurrency_total_ttc = 0;
  2446. $num = $this->db->num_rows($resql);
  2447. $i = 0;
  2448. while ($i < $num)
  2449. {
  2450. $obj = $this->db->fetch_object($resql);
  2451. // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
  2452. $parameters=array('fk_element' => $obj->rowid);
  2453. $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2454. if (empty($reshook) && $forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
  2455. {
  2456. $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
  2457. $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);
  2458. $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
  2459. if ($diff)
  2460. {
  2461. $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
  2462. 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);
  2463. $resqlfix=$this->db->query($sqlfix);
  2464. if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
  2465. $obj->total_tva = $tmpcal[1];
  2466. $obj->total_ttc = $tmpcal[2];
  2467. //
  2468. }
  2469. }
  2470. $this->total_ht += $obj->total_ht; // The field visible at end of line detail
  2471. $this->total_tva += $obj->total_tva;
  2472. $this->total_localtax1 += $obj->total_localtax1;
  2473. $this->total_localtax2 += $obj->total_localtax2;
  2474. $this->total_ttc += $obj->total_ttc;
  2475. $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
  2476. $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
  2477. $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
  2478. if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0;
  2479. if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
  2480. if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
  2481. $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
  2482. $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
  2483. $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
  2484. if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
  2485. {
  2486. $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
  2487. $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
  2488. //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";
  2489. if ($diff)
  2490. {
  2491. if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
  2492. $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;
  2493. 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);
  2494. $resqlfix=$this->db->query($sqlfix);
  2495. if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
  2496. $this->total_tva -= $diff;
  2497. $this->total_ttc -= $diff;
  2498. $total_tva_by_vats[$obj->vatrate] -= $diff;
  2499. $total_ttc_by_vats[$obj->vatrate] -= $diff;
  2500. }
  2501. }
  2502. $i++;
  2503. }
  2504. // Add revenue stamp to total
  2505. $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0;
  2506. $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0;
  2507. // Situations totals
  2508. if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE )
  2509. {
  2510. $prev_sits = $this->get_prev_sits();
  2511. foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
  2512. $this->total_ht -= $sit->total_ht;
  2513. $this->total_tva -= $sit->total_tva;
  2514. $this->total_localtax1 -= $sit->total_localtax1;
  2515. $this->total_localtax2 -= $sit->total_localtax2;
  2516. $this->total_ttc -= $sit->total_ttc;
  2517. $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
  2518. $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
  2519. $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
  2520. }
  2521. }
  2522. $this->db->free($resql);
  2523. // Now update global field total_ht, total_ttc and tva
  2524. $fieldht='total_ht';
  2525. $fieldtva='tva';
  2526. $fieldlocaltax1='localtax1';
  2527. $fieldlocaltax2='localtax2';
  2528. $fieldttc='total_ttc';
  2529. // Specific code for backward compatibility with old field names
  2530. if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total';
  2531. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
  2532. if ($this->element == 'propal') $fieldttc='total';
  2533. if ($this->element == 'expensereport') $fieldtva='total_tva';
  2534. if ($this->element == 'supplier_proposal') $fieldttc='total';
  2535. if (empty($nodatabaseupdate))
  2536. {
  2537. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
  2538. $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
  2539. $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
  2540. $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
  2541. $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
  2542. $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
  2543. $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
  2544. $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
  2545. $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
  2546. $sql .= ' WHERE rowid = '.$this->id;
  2547. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2548. $resql=$this->db->query($sql);
  2549. if (! $resql)
  2550. {
  2551. $error++;
  2552. $this->error=$this->db->lasterror();
  2553. $this->errors[]=$this->db->lasterror();
  2554. }
  2555. }
  2556. if (! $error)
  2557. {
  2558. return 1;
  2559. }
  2560. else
  2561. {
  2562. return -1;
  2563. }
  2564. }
  2565. else
  2566. {
  2567. dol_print_error($this->db,'Bad request in update_price');
  2568. return -1;
  2569. }
  2570. }
  2571. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2572. /**
  2573. * Add objects linked in llx_element_element.
  2574. *
  2575. * @param string $origin Linked element type
  2576. * @param int $origin_id Linked element id
  2577. * @return int <=0 if KO, >0 if OK
  2578. * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked
  2579. */
  2580. function add_object_linked($origin=null, $origin_id=null)
  2581. {
  2582. // phpcs:enable
  2583. $origin = (! empty($origin) ? $origin : $this->origin);
  2584. $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
  2585. // Special case
  2586. if ($origin == 'order') $origin='commande';
  2587. if ($origin == 'invoice') $origin='facture';
  2588. if ($origin == 'invoice_template') $origin='facturerec';
  2589. $this->db->begin();
  2590. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
  2591. $sql.= "fk_source";
  2592. $sql.= ", sourcetype";
  2593. $sql.= ", fk_target";
  2594. $sql.= ", targettype";
  2595. $sql.= ") VALUES (";
  2596. $sql.= $origin_id;
  2597. $sql.= ", '".$this->db->escape($origin)."'";
  2598. $sql.= ", ".$this->id;
  2599. $sql.= ", '".$this->db->escape($this->element)."'";
  2600. $sql.= ")";
  2601. dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
  2602. if ($this->db->query($sql))
  2603. {
  2604. $this->db->commit();
  2605. return 1;
  2606. }
  2607. else
  2608. {
  2609. $this->error=$this->db->lasterror();
  2610. $this->db->rollback();
  2611. return 0;
  2612. }
  2613. }
  2614. /**
  2615. * Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
  2616. * this->linkedObjectsIds array and
  2617. * this->linkedObjects array if $loadalsoobjects = 1
  2618. * Possible usage for parameters:
  2619. * - all parameters empty -> we look all link to current object (current object can be source or target)
  2620. * - source id+type -> will get target list linked to source
  2621. * - target id+type -> will get source list linked to target
  2622. * - source id+type + target type -> will get target list of the type
  2623. * - target id+type + target source -> will get source list of the type
  2624. *
  2625. * @param int $sourceid Object source id (if not defined, id of object)
  2626. * @param string $sourcetype Object source type (if not defined, element name of object)
  2627. * @param int $targetid Object target id (if not defined, id of object)
  2628. * @param string $targettype Object target type (if not defined, elemennt name of object)
  2629. * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
  2630. * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
  2631. * @param string $orderby SQL 'ORDER BY' clause
  2632. * @param int $loadalsoobjects Load also array this->linkedObjects (Use 0 to increase performances)
  2633. * @return int <0 if KO, >0 if OK
  2634. * @see add_object_linked, updateObjectLinked, deleteObjectLinked
  2635. */
  2636. function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
  2637. {
  2638. global $conf;
  2639. $this->linkedObjectsIds=array();
  2640. $this->linkedObjects=array();
  2641. $justsource=false;
  2642. $justtarget=false;
  2643. $withtargettype=false;
  2644. $withsourcetype=false;
  2645. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
  2646. {
  2647. $justsource=true; // the source (id and type) is a search criteria
  2648. if (! empty($targettype)) $withtargettype=true;
  2649. }
  2650. if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
  2651. {
  2652. $justtarget=true; // the target (id and type) is a search criteria
  2653. if (! empty($sourcetype)) $withsourcetype=true;
  2654. }
  2655. $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
  2656. $targetid = (! empty($targetid) ? $targetid : $this->id);
  2657. $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
  2658. $targettype = (! empty($targettype) ? $targettype : $this->element);
  2659. /*if (empty($sourceid) && empty($targetid))
  2660. {
  2661. dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
  2662. return -1;
  2663. }*/
  2664. // Links between objects are stored in table element_element
  2665. $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
  2666. $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
  2667. $sql.= " WHERE ";
  2668. if ($justsource || $justtarget)
  2669. {
  2670. if ($justsource)
  2671. {
  2672. $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
  2673. if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
  2674. }
  2675. else if ($justtarget)
  2676. {
  2677. $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
  2678. if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
  2679. }
  2680. }
  2681. else
  2682. {
  2683. $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
  2684. $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
  2685. }
  2686. $sql .= ' ORDER BY '.$orderby;
  2687. dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
  2688. $resql = $this->db->query($sql);
  2689. if ($resql)
  2690. {
  2691. $num = $this->db->num_rows($resql);
  2692. $i = 0;
  2693. while ($i < $num)
  2694. {
  2695. $obj = $this->db->fetch_object($resql);
  2696. if ($justsource || $justtarget)
  2697. {
  2698. if ($justsource)
  2699. {
  2700. $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
  2701. }
  2702. else if ($justtarget)
  2703. {
  2704. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
  2705. }
  2706. }
  2707. else
  2708. {
  2709. if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
  2710. {
  2711. $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
  2712. }
  2713. if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
  2714. {
  2715. $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
  2716. }
  2717. }
  2718. $i++;
  2719. }
  2720. if (! empty($this->linkedObjectsIds))
  2721. {
  2722. $tmparray = $this->linkedObjectsIds;
  2723. foreach($tmparray as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
  2724. {
  2725. // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
  2726. $module = $element = $subelement = $objecttype;
  2727. if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
  2728. && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  2729. {
  2730. $module = $element = $regs[1];
  2731. $subelement = $regs[2];
  2732. }
  2733. $classpath = $element.'/class';
  2734. // To work with non standard classpath or module name
  2735. if ($objecttype == 'facture') {
  2736. $classpath = 'compta/facture/class';
  2737. }
  2738. else if ($objecttype == 'facturerec') {
  2739. $classpath = 'compta/facture/class'; $module = 'facture';
  2740. }
  2741. else if ($objecttype == 'propal') {
  2742. $classpath = 'comm/propal/class';
  2743. }
  2744. else if ($objecttype == 'supplier_proposal') {
  2745. $classpath = 'supplier_proposal/class';
  2746. }
  2747. else if ($objecttype == 'shipping') {
  2748. $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
  2749. }
  2750. else if ($objecttype == 'delivery') {
  2751. $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
  2752. }
  2753. else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
  2754. $classpath = 'fourn/class'; $module = 'fournisseur';
  2755. }
  2756. else if ($objecttype == 'fichinter') {
  2757. $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
  2758. }
  2759. else if ($objecttype == 'subscription') {
  2760. $classpath = 'adherents/class'; $module = 'adherent';
  2761. }
  2762. // Set classfile
  2763. $classfile = strtolower($subelement); $classname = ucfirst($subelement);
  2764. if ($objecttype == 'order') {
  2765. $classfile = 'commande'; $classname = 'Commande';
  2766. }
  2767. else if ($objecttype == 'invoice_supplier') {
  2768. $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
  2769. }
  2770. else if ($objecttype == 'order_supplier') {
  2771. $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
  2772. }
  2773. else if ($objecttype == 'supplier_proposal') {
  2774. $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
  2775. }
  2776. else if ($objecttype == 'facturerec') {
  2777. $classfile = 'facture-rec'; $classname = 'FactureRec';
  2778. }
  2779. else if ($objecttype == 'subscription') {
  2780. $classfile = 'subscription'; $classname = 'Subscription';
  2781. }
  2782. // Here $module, $classfile and $classname are set
  2783. if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
  2784. {
  2785. if ($loadalsoobjects)
  2786. {
  2787. dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
  2788. //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
  2789. if (class_exists($classname))
  2790. {
  2791. foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element
  2792. {
  2793. $object = new $classname($this->db);
  2794. $ret = $object->fetch($objectid);
  2795. if ($ret >= 0)
  2796. {
  2797. $this->linkedObjects[$objecttype][$i] = $object;
  2798. }
  2799. }
  2800. }
  2801. }
  2802. }
  2803. else
  2804. {
  2805. unset($this->linkedObjectsIds[$objecttype]);
  2806. }
  2807. }
  2808. }
  2809. return 1;
  2810. }
  2811. else
  2812. {
  2813. dol_print_error($this->db);
  2814. return -1;
  2815. }
  2816. }
  2817. /**
  2818. * Update object linked of a current object
  2819. *
  2820. * @param int $sourceid Object source id
  2821. * @param string $sourcetype Object source type
  2822. * @param int $targetid Object target id
  2823. * @param string $targettype Object target type
  2824. * @return int >0 if OK, <0 if KO
  2825. * @see add_object_linked, fetObjectLinked, deleteObjectLinked
  2826. */
  2827. function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='')
  2828. {
  2829. $updatesource=false;
  2830. $updatetarget=false;
  2831. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true;
  2832. else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true;
  2833. $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
  2834. if ($updatesource)
  2835. {
  2836. $sql.= "fk_source = ".$sourceid;
  2837. $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'";
  2838. $sql.= " WHERE fk_target = ".$this->id;
  2839. $sql.= " AND targettype = '".$this->db->escape($this->element)."'";
  2840. }
  2841. else if ($updatetarget)
  2842. {
  2843. $sql.= "fk_target = ".$targetid;
  2844. $sql.= ", targettype = '".$this->db->escape($targettype)."'";
  2845. $sql.= " WHERE fk_source = ".$this->id;
  2846. $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'";
  2847. }
  2848. dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
  2849. if ($this->db->query($sql))
  2850. {
  2851. return 1;
  2852. }
  2853. else
  2854. {
  2855. $this->error=$this->db->lasterror();
  2856. return -1;
  2857. }
  2858. }
  2859. /**
  2860. * Delete all links between an object $this
  2861. *
  2862. * @param int $sourceid Object source id
  2863. * @param string $sourcetype Object source type
  2864. * @param int $targetid Object target id
  2865. * @param string $targettype Object target type
  2866. * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
  2867. * @return int >0 if OK, <0 if KO
  2868. * @see add_object_linked, updateObjectLinked, fetchObjectLinked
  2869. */
  2870. function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
  2871. {
  2872. $deletesource=false;
  2873. $deletetarget=false;
  2874. if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource=true;
  2875. else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $deletetarget=true;
  2876. $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
  2877. $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
  2878. $targetid = (! empty($targetid) ? $targetid : $this->id);
  2879. $targettype = (! empty($targettype) ? $targettype : $this->element);
  2880. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  2881. $sql.= " WHERE";
  2882. if ($rowid > 0)
  2883. {
  2884. $sql.=" rowid = ".$rowid;
  2885. }
  2886. else
  2887. {
  2888. if ($deletesource)
  2889. {
  2890. $sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
  2891. $sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
  2892. }
  2893. else if ($deletetarget)
  2894. {
  2895. $sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
  2896. $sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
  2897. }
  2898. else
  2899. {
  2900. $sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
  2901. $sql.= " OR";
  2902. $sql.= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
  2903. }
  2904. }
  2905. dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
  2906. if ($this->db->query($sql))
  2907. {
  2908. return 1;
  2909. }
  2910. else
  2911. {
  2912. $this->error=$this->db->lasterror();
  2913. $this->errors[]=$this->error;
  2914. return -1;
  2915. }
  2916. }
  2917. /**
  2918. * Set status of an object
  2919. *
  2920. * @param int $status Status to set
  2921. * @param int $elementId Id of element to force (use this->id by default)
  2922. * @param string $elementType Type of element to force (use this->table_element by default)
  2923. * @param string $trigkey Trigger key to use for trigger
  2924. * @return int <0 if KO, >0 if OK
  2925. */
  2926. function setStatut($status, $elementId=null, $elementType='', $trigkey='')
  2927. {
  2928. global $user,$langs,$conf;
  2929. $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not.
  2930. $elementId = (!empty($elementId)?$elementId:$this->id);
  2931. $elementTable = (!empty($elementType)?$elementType:$this->table_element);
  2932. $this->db->begin();
  2933. $fieldstatus="fk_statut";
  2934. if ($elementTable == 'facture_rec') $fieldstatus="suspended";
  2935. if ($elementTable == 'mailing') $fieldstatus="statut";
  2936. if ($elementTable == 'cronjob') $fieldstatus="status";
  2937. if ($elementTable == 'user') $fieldstatus="statut";
  2938. if ($elementTable == 'expensereport') $fieldstatus="fk_statut";
  2939. if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status";
  2940. $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
  2941. $sql.= " SET ".$fieldstatus." = ".$status;
  2942. // If status = 1 = validated, update also fk_user_valid
  2943. if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id;
  2944. $sql.= " WHERE rowid=".$elementId;
  2945. dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
  2946. if ($this->db->query($sql))
  2947. {
  2948. $error = 0;
  2949. // Try autoset of trigkey
  2950. if (empty($trigkey))
  2951. {
  2952. if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
  2953. if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
  2954. if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
  2955. if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE';
  2956. if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED';
  2957. if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED';
  2958. }
  2959. if ($trigkey)
  2960. {
  2961. // Appel des triggers
  2962. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  2963. $interface=new Interfaces($this->db);
  2964. $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf);
  2965. if ($result < 0) {
  2966. $error++; $this->errors=$interface->errors;
  2967. }
  2968. // Fin appel triggers
  2969. }
  2970. if (! $error)
  2971. {
  2972. $this->db->commit();
  2973. if (empty($savElementId)) // If the element we update was $this (so $elementId is null)
  2974. {
  2975. $this->statut = $status;
  2976. $this->status = $status;
  2977. }
  2978. return 1;
  2979. }
  2980. else
  2981. {
  2982. $this->db->rollback();
  2983. dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
  2984. return -1;
  2985. }
  2986. }
  2987. else
  2988. {
  2989. $this->error=$this->db->lasterror();
  2990. $this->db->rollback();
  2991. return -1;
  2992. }
  2993. }
  2994. /**
  2995. * Load type of canvas of an object if it exists
  2996. *
  2997. * @param int $id Record id
  2998. * @param string $ref Record ref
  2999. * @return int <0 if KO, 0 if nothing done, >0 if OK
  3000. */
  3001. function getCanvas($id=0,$ref='')
  3002. {
  3003. global $conf;
  3004. if (empty($id) && empty($ref)) return 0;
  3005. if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
  3006. // Clean parameters
  3007. $ref = trim($ref);
  3008. $sql = "SELECT rowid, canvas";
  3009. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  3010. $sql.= " WHERE entity IN (".getEntity($this->element).")";
  3011. if (! empty($id)) $sql.= " AND rowid = ".$id;
  3012. if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
  3013. $resql = $this->db->query($sql);
  3014. if ($resql)
  3015. {
  3016. $obj = $this->db->fetch_object($resql);
  3017. if ($obj)
  3018. {
  3019. $this->canvas = $obj->canvas;
  3020. return 1;
  3021. }
  3022. else return 0;
  3023. }
  3024. else
  3025. {
  3026. dol_print_error($this->db);
  3027. return -1;
  3028. }
  3029. }
  3030. /**
  3031. * Get special code of a line
  3032. *
  3033. * @param int $lineid Id of line
  3034. * @return int Special code
  3035. */
  3036. function getSpecialCode($lineid)
  3037. {
  3038. $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
  3039. $sql.= ' WHERE rowid = '.$lineid;
  3040. $resql = $this->db->query($sql);
  3041. if ($resql)
  3042. {
  3043. $row = $this->db->fetch_row($resql);
  3044. return $row[0];
  3045. }
  3046. }
  3047. /**
  3048. * Function to check if an object is used by others.
  3049. * Check is done into this->childtables. There is no check into llx_element_element.
  3050. *
  3051. * @param int $id Force id of object
  3052. * @return int <0 if KO, 0 if not used, >0 if already used
  3053. */
  3054. function isObjectUsed($id=0)
  3055. {
  3056. global $langs;
  3057. if (empty($id)) $id=$this->id;
  3058. // Check parameters
  3059. if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
  3060. {
  3061. dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
  3062. return -1;
  3063. }
  3064. $arraytoscan = $this->childtables;
  3065. // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
  3066. $tmparray=array_keys($this->childtables);
  3067. if (is_numeric($tmparray[0]))
  3068. {
  3069. $arraytoscan = array_flip($this->childtables);
  3070. }
  3071. // Test if child exists
  3072. $haschild=0;
  3073. foreach($arraytoscan as $table => $elementname)
  3074. {
  3075. //print $id.'-'.$table.'-'.$elementname.'<br>';
  3076. // Check if third party can be deleted
  3077. $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
  3078. $sql.= " WHERE ".$this->fk_element." = ".$id;
  3079. $resql=$this->db->query($sql);
  3080. if ($resql)
  3081. {
  3082. $obj=$this->db->fetch_object($resql);
  3083. if ($obj->nb > 0)
  3084. {
  3085. $langs->load("errors");
  3086. //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
  3087. $haschild += $obj->nb;
  3088. if (is_numeric($elementname)) // old usage
  3089. {
  3090. $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
  3091. }
  3092. else // new usage: $elementname=Translation key
  3093. {
  3094. $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
  3095. }
  3096. break; // We found at least one, we stop here
  3097. }
  3098. }
  3099. else
  3100. {
  3101. $this->errors[]=$this->db->lasterror();
  3102. return -1;
  3103. }
  3104. }
  3105. if ($haschild > 0)
  3106. {
  3107. $this->errors[]="ErrorRecordHasChildren";
  3108. return $haschild;
  3109. }
  3110. else return 0;
  3111. }
  3112. /**
  3113. * Function to say how many lines object contains
  3114. *
  3115. * @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
  3116. * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found
  3117. */
  3118. function hasProductsOrServices($predefined=-1)
  3119. {
  3120. $nb=0;
  3121. foreach($this->lines as $key => $val)
  3122. {
  3123. $qualified=0;
  3124. if ($predefined == -1) $qualified=1;
  3125. if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
  3126. if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
  3127. if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
  3128. if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
  3129. if ($qualified) $nb++;
  3130. }
  3131. dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
  3132. return $nb;
  3133. }
  3134. /**
  3135. * Function that returns the total amount HT of discounts applied for all lines.
  3136. *
  3137. * @return float
  3138. */
  3139. function getTotalDiscount()
  3140. {
  3141. $total_discount=0.00;
  3142. $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
  3143. $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
  3144. $sql.= " WHERE ".$this->fk_element." = ".$this->id;
  3145. dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
  3146. $resql = $this->db->query($sql);
  3147. if ($resql)
  3148. {
  3149. $num=$this->db->num_rows($resql);
  3150. $i=0;
  3151. while ($i < $num)
  3152. {
  3153. $obj = $this->db->fetch_object($resql);
  3154. $pu_ht = $obj->pu_ht;
  3155. $qty= $obj->qty;
  3156. $total_ht = $obj->total_ht;
  3157. $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
  3158. $total_discount += $total_discount_line;
  3159. $i++;
  3160. }
  3161. }
  3162. //print $total_discount; exit;
  3163. return price2num($total_discount);
  3164. }
  3165. /**
  3166. * Return into unit=0, the calculated total of weight and volume of all lines * qty
  3167. * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
  3168. *
  3169. * @return array array('weight'=>...,'volume'=>...)
  3170. */
  3171. function getTotalWeightVolume()
  3172. {
  3173. $totalWeight = 0;
  3174. $totalVolume = 0;
  3175. // defined for shipment only
  3176. $totalOrdered = '';
  3177. // defined for shipment only
  3178. $totalToShip = '';
  3179. foreach ($this->lines as $line)
  3180. {
  3181. if (isset($line->qty_asked))
  3182. {
  3183. if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is ''
  3184. $totalOrdered+=$line->qty_asked; // defined for shipment only
  3185. }
  3186. if (isset($line->qty_shipped))
  3187. {
  3188. if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is ''
  3189. $totalToShip+=$line->qty_shipped; // defined for shipment only
  3190. }
  3191. // Define qty, weight, volume, weight_units, volume_units
  3192. if ($this->element == 'shipping') {
  3193. // for shipments
  3194. $qty = $line->qty_shipped ? $line->qty_shipped : 0;
  3195. }
  3196. else {
  3197. $qty = $line->qty ? $line->qty : 0;
  3198. }
  3199. $weight = $line->weight ? $line->weight : 0;
  3200. $volume = $line->volume ? $line->volume : 0;
  3201. $weight_units=$line->weight_units;
  3202. $volume_units=$line->volume_units;
  3203. $weightUnit=0;
  3204. $volumeUnit=0;
  3205. if (! empty($weight_units)) $weightUnit = $weight_units;
  3206. if (! empty($volume_units)) $volumeUnit = $volume_units;
  3207. if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is ''
  3208. if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is ''
  3209. //var_dump($line->volume_units);
  3210. if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3211. {
  3212. $trueWeightUnit=pow(10, $weightUnit);
  3213. $totalWeight += $weight * $qty * $trueWeightUnit;
  3214. }
  3215. else {
  3216. if ($weight_units == 99) {
  3217. // conversion 1 Pound = 0.45359237 KG
  3218. $trueWeightUnit = 0.45359237;
  3219. $totalWeight += $weight * $qty * $trueWeightUnit;
  3220. } elseif ($weight_units == 98) {
  3221. // conversion 1 Ounce = 0.0283495 KG
  3222. $trueWeightUnit = 0.0283495;
  3223. $totalWeight += $weight * $qty * $trueWeightUnit;
  3224. }
  3225. else
  3226. $totalWeight += $weight * $qty; // This may be wrong if we mix different units
  3227. }
  3228. if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
  3229. {
  3230. //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
  3231. $trueVolumeUnit=pow(10, $volumeUnit);
  3232. //print $line->volume;
  3233. $totalVolume += $volume * $qty * $trueVolumeUnit;
  3234. }
  3235. else
  3236. {
  3237. $totalVolume += $volume * $qty; // This may be wrong if we mix different units
  3238. }
  3239. }
  3240. return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
  3241. }
  3242. /**
  3243. * Set extra parameters
  3244. *
  3245. * @return int <0 if KO, >0 if OK
  3246. */
  3247. function setExtraParameters()
  3248. {
  3249. $this->db->begin();
  3250. $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
  3251. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  3252. $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
  3253. $sql.= " WHERE rowid = ".$this->id;
  3254. dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
  3255. $resql = $this->db->query($sql);
  3256. if (! $resql)
  3257. {
  3258. $this->error=$this->db->lasterror();
  3259. $this->db->rollback();
  3260. return -1;
  3261. }
  3262. else
  3263. {
  3264. $this->db->commit();
  3265. return 1;
  3266. }
  3267. }
  3268. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3269. /**
  3270. * Return incoterms informations
  3271. * TODO Use a cache for label get
  3272. *
  3273. * @return string incoterms info
  3274. */
  3275. function display_incoterms()
  3276. {
  3277. // phpcs:enable
  3278. $out = '';
  3279. $this->libelle_incoterms = '';
  3280. if (!empty($this->fk_incoterms))
  3281. {
  3282. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  3283. $result = $this->db->query($sql);
  3284. if ($result)
  3285. {
  3286. $res = $this->db->fetch_object($result);
  3287. $out .= $res->code;
  3288. }
  3289. }
  3290. $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
  3291. return $out;
  3292. }
  3293. /**
  3294. * Return incoterms informations for pdf display
  3295. *
  3296. * @return string incoterms info
  3297. */
  3298. function getIncotermsForPDF()
  3299. {
  3300. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  3301. $resql = $this->db->query($sql);
  3302. if ($resql)
  3303. {
  3304. $num = $this->db->num_rows($resql);
  3305. if ($num > 0)
  3306. {
  3307. $res = $this->db->fetch_object($resql);
  3308. return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
  3309. }
  3310. else
  3311. {
  3312. return '';
  3313. }
  3314. }
  3315. else
  3316. {
  3317. $this->errors[] = $this->db->lasterror();
  3318. return false;
  3319. }
  3320. }
  3321. /**
  3322. * Define incoterms values of current object
  3323. *
  3324. * @param int $id_incoterm Id of incoterm to set or '' to remove
  3325. * @param string $location location of incoterm
  3326. * @return int <0 if KO, >0 if OK
  3327. */
  3328. function setIncoterms($id_incoterm, $location)
  3329. {
  3330. if ($this->id && $this->table_element)
  3331. {
  3332. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  3333. $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
  3334. $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
  3335. $sql.= " WHERE rowid = " . $this->id;
  3336. dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
  3337. $resql=$this->db->query($sql);
  3338. if ($resql)
  3339. {
  3340. $this->fk_incoterms = $id_incoterm;
  3341. $this->location_incoterms = $location;
  3342. $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
  3343. $res = $this->db->query($sql);
  3344. if ($res)
  3345. {
  3346. $obj = $this->db->fetch_object($res);
  3347. $this->libelle_incoterms = $obj->libelle;
  3348. }
  3349. return 1;
  3350. }
  3351. else
  3352. {
  3353. $this->errors[] = $this->db->lasterror();
  3354. return -1;
  3355. }
  3356. }
  3357. else return -1;
  3358. }
  3359. // --------------------
  3360. // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
  3361. // --------------------
  3362. /* This is to show add lines */
  3363. /**
  3364. * Show add free and predefined products/services form
  3365. *
  3366. * @param int $dateSelector 1=Show also date range input fields
  3367. * @param Societe $seller Object thirdparty who sell
  3368. * @param Societe $buyer Object thirdparty who buy
  3369. * @return void
  3370. */
  3371. function formAddObjectLine($dateSelector, $seller, $buyer)
  3372. {
  3373. global $conf,$user,$langs,$object,$hookmanager;
  3374. global $form,$bcnd,$var;
  3375. // Line extrafield
  3376. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3377. $extrafieldsline = new ExtraFields($this->db);
  3378. $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
  3379. // Output template part (modules that overwrite templates must declare this into descriptor)
  3380. // Use global variables + $dateSelector + $seller and $buyer
  3381. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3382. foreach($dirtpls as $reldir)
  3383. {
  3384. $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
  3385. if (empty($conf->file->strict_mode)) {
  3386. $res=@include $tpl;
  3387. } else {
  3388. $res=include $tpl; // for debug
  3389. }
  3390. if ($res) break;
  3391. }
  3392. }
  3393. /* This is to show array of line of details */
  3394. /**
  3395. * Return HTML table for object lines
  3396. * TODO Move this into an output class file (htmlline.class.php)
  3397. * If lines are into a template, title must also be into a template
  3398. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3399. *
  3400. * @param string $action Action code
  3401. * @param string $seller Object of seller third party
  3402. * @param string $buyer Object of buyer third party
  3403. * @param int $selected Object line selected
  3404. * @param int $dateSelector 1=Show also date range input fields
  3405. * @return void
  3406. */
  3407. function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
  3408. {
  3409. global $conf, $hookmanager, $langs, $user;
  3410. // TODO We should not use global var for this !
  3411. global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
  3412. // Define usemargins
  3413. $usemargins=0;
  3414. if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
  3415. $num = count($this->lines);
  3416. // Line extrafield
  3417. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  3418. $extrafieldsline = new ExtraFields($this->db);
  3419. $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
  3420. $parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
  3421. $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3422. if (empty($reshook))
  3423. {
  3424. // Title line
  3425. print "<thead>\n";
  3426. print '<tr class="liste_titre nodrag nodrop">';
  3427. // Adds a line numbering column
  3428. if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
  3429. // Description
  3430. print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
  3431. if ($this->element == 'supplier_proposal' || $this->element == 'order_supplier' || $this->element == 'invoice_supplier')
  3432. {
  3433. print '<td class="linerefsupplier"><span id="title_fourn_ref">'.$langs->trans("SupplierRef").'</span></td>';
  3434. }
  3435. // VAT
  3436. print '<td class="linecolvat" align="right" width="80">'.$langs->trans('VAT').'</td>';
  3437. // Price HT
  3438. print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
  3439. // Multicurrency
  3440. if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
  3441. if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
  3442. // Qty
  3443. print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
  3444. if($conf->global->PRODUCT_USE_UNITS)
  3445. {
  3446. print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
  3447. }
  3448. // Reduction short
  3449. print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
  3450. if ($this->situation_cycle_ref) {
  3451. print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
  3452. }
  3453. if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id))
  3454. {
  3455. if (!empty($user->rights->margins->creer))
  3456. {
  3457. if ($conf->global->MARGIN_TYPE == "1")
  3458. print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
  3459. else
  3460. print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
  3461. }
  3462. if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
  3463. print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
  3464. if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
  3465. print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
  3466. }
  3467. // Total HT
  3468. print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
  3469. // Multicurrency
  3470. if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
  3471. if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
  3472. print '<td class="linecoledit"></td>'; // No width to allow autodim
  3473. print '<td class="linecoldelete" width="10"></td>';
  3474. print '<td class="linecolmove" width="10"></td>';
  3475. if($action == 'selectlines')
  3476. {
  3477. print '<td class="linecolcheckall" align="center">';
  3478. print '<input type="checkbox" class="linecheckboxtoggle" />';
  3479. print '<script type="text/javascript">$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';
  3480. print '</td>';
  3481. }
  3482. print "</tr>\n";
  3483. print "</thead>\n";
  3484. }
  3485. $var = true;
  3486. $i = 0;
  3487. print "<tbody>\n";
  3488. foreach ($this->lines as $line)
  3489. {
  3490. //Line extrafield
  3491. $line->fetch_optionals();
  3492. //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3493. if (is_object($hookmanager)) // Old code is commented on preceding line.
  3494. {
  3495. if (empty($line->fk_parent_line))
  3496. {
  3497. $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
  3498. $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3499. }
  3500. else
  3501. {
  3502. $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);
  3503. $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3504. }
  3505. }
  3506. if (empty($reshook))
  3507. {
  3508. $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
  3509. }
  3510. $i++;
  3511. }
  3512. print "</tbody>\n";
  3513. }
  3514. /**
  3515. * Return HTML content of a detail line
  3516. * TODO Move this into an output class file (htmlline.class.php)
  3517. *
  3518. * @param string $action GET/POST action
  3519. * @param CommonObjectLine $line Selected object line to output
  3520. * @param string $var Is it a an odd line (true)
  3521. * @param int $num Number of line (0)
  3522. * @param int $i I
  3523. * @param int $dateSelector 1=Show also date range input fields
  3524. * @param string $seller Object of seller third party
  3525. * @param string $buyer Object of buyer third party
  3526. * @param int $selected Object line selected
  3527. * @param int $extrafieldsline Object of extrafield line attribute
  3528. * @return void
  3529. */
  3530. function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
  3531. {
  3532. global $conf,$langs,$user,$object,$hookmanager;
  3533. global $form,$bc,$bcdd;
  3534. global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
  3535. $object_rights = $this->getRights();
  3536. $element=$this->element;
  3537. $text=''; $description=''; $type=0;
  3538. // Show product and description
  3539. $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
  3540. // Try to enhance type detection using date_start and date_end for free lines where type was not saved.
  3541. if (! empty($line->date_start)) $type=1; // deprecated
  3542. if (! empty($line->date_end)) $type=1; // deprecated
  3543. // Ligne en mode visu
  3544. if ($action != 'editline' || $selected != $line->id)
  3545. {
  3546. // Product
  3547. if ($line->fk_product > 0)
  3548. {
  3549. $product_static = new Product($this->db);
  3550. $product_static->fetch($line->fk_product);
  3551. $product_static->ref = $line->ref; //can change ref in hook
  3552. $product_static->label = $line->label; //can change label in hook
  3553. $text=$product_static->getNomUrl(1);
  3554. // Define output language and label
  3555. if (! empty($conf->global->MAIN_MULTILANGS))
  3556. {
  3557. if (! is_object($this->thirdparty))
  3558. {
  3559. dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
  3560. return;
  3561. }
  3562. $prod = new Product($this->db);
  3563. $prod->fetch($line->fk_product);
  3564. $outputlangs = $langs;
  3565. $newlang='';
  3566. if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
  3567. if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang; // For language to language of customer
  3568. if (! empty($newlang))
  3569. {
  3570. $outputlangs = new Translate("",$conf);
  3571. $outputlangs->setDefaultLang($newlang);
  3572. }
  3573. $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
  3574. }
  3575. else
  3576. {
  3577. $label = $line->product_label;
  3578. }
  3579. $text.= ' - '.(! empty($line->label)?$line->label:$label);
  3580. $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.
  3581. }
  3582. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
  3583. // Output template part (modules that overwrite templates must declare this into descriptor)
  3584. // Use global variables + $dateSelector + $seller and $buyer
  3585. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3586. foreach($dirtpls as $reldir)
  3587. {
  3588. $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
  3589. if (empty($conf->file->strict_mode)) {
  3590. $res=@include $tpl;
  3591. } else {
  3592. $res=include $tpl; // for debug
  3593. }
  3594. if ($res) break;
  3595. }
  3596. }
  3597. // Ligne en mode update
  3598. if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
  3599. {
  3600. $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
  3601. $placeholder=' placeholder="'.$langs->trans("Label").'"';
  3602. $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
  3603. // Output template part (modules that overwrite templates must declare this into descriptor)
  3604. // Use global variables + $dateSelector + $seller and $buyer
  3605. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3606. foreach($dirtpls as $reldir)
  3607. {
  3608. $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
  3609. if (empty($conf->file->strict_mode)) {
  3610. $res=@include $tpl;
  3611. } else {
  3612. $res=include $tpl; // for debug
  3613. }
  3614. if ($res) break;
  3615. }
  3616. }
  3617. }
  3618. /* This is to show array of line of details of source object */
  3619. /**
  3620. * Return HTML table table of source object lines
  3621. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3622. * If lines are into a template, title must also be into a template
  3623. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  3624. *
  3625. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  3626. * @return void
  3627. */
  3628. function printOriginLinesList($restrictlist='')
  3629. {
  3630. global $langs, $hookmanager, $conf;
  3631. print '<tr class="liste_titre">';
  3632. print '<td>'.$langs->trans('Ref').'</td>';
  3633. print '<td>'.$langs->trans('Description').'</td>';
  3634. print '<td align="right">'.$langs->trans('VATRate').'</td>';
  3635. print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
  3636. if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
  3637. print '<td align="right">'.$langs->trans('Qty').'</td>';
  3638. if($conf->global->PRODUCT_USE_UNITS)
  3639. {
  3640. print '<td align="left">'.$langs->trans('Unit').'</td>';
  3641. }
  3642. print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
  3643. $var = true;
  3644. $i = 0;
  3645. if (! empty($this->lines))
  3646. {
  3647. foreach ($this->lines as $line)
  3648. {
  3649. if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
  3650. {
  3651. if (empty($line->fk_parent_line))
  3652. {
  3653. $parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
  3654. $action='';
  3655. $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  3656. }
  3657. }
  3658. else
  3659. {
  3660. $this->printOriginLine($line, $var, $restrictlist);
  3661. }
  3662. $i++;
  3663. }
  3664. }
  3665. }
  3666. /**
  3667. * Return HTML with a line of table array of source object lines
  3668. * TODO Move this and previous function into output html class file (htmlline.class.php).
  3669. * If lines are into a template, title must also be into a template
  3670. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  3671. *
  3672. * @param CommonObjectLine $line Line
  3673. * @param string $var Var
  3674. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  3675. * @return void
  3676. */
  3677. function printOriginLine($line, $var, $restrictlist='')
  3678. {
  3679. global $langs, $conf;
  3680. //var_dump($line);
  3681. if (!empty($line->date_start))
  3682. {
  3683. $date_start=$line->date_start;
  3684. }
  3685. else
  3686. {
  3687. $date_start=$line->date_debut_prevue;
  3688. if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
  3689. }
  3690. if (!empty($line->date_end))
  3691. {
  3692. $date_end=$line->date_end;
  3693. }
  3694. else
  3695. {
  3696. $date_end=$line->date_fin_prevue;
  3697. if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
  3698. }
  3699. $this->tpl['label'] = '';
  3700. if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
  3701. if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object
  3702. {
  3703. $discount=new DiscountAbsolute($this->db);
  3704. $discount->fk_soc = $this->socid;
  3705. $this->tpl['label'].= $discount->getNomUrl(0,'discount');
  3706. }
  3707. else if (! empty($line->fk_product))
  3708. {
  3709. $productstatic = new Product($this->db);
  3710. $productstatic->id = $line->fk_product;
  3711. $productstatic->ref = $line->ref;
  3712. $productstatic->type = $line->fk_product_type;
  3713. $this->tpl['label'].= $productstatic->getNomUrl(1);
  3714. $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
  3715. // Dates
  3716. if ($line->product_type == 1 && ($date_start || $date_end))
  3717. {
  3718. $this->tpl['label'].= get_date_range($date_start,$date_end);
  3719. }
  3720. }
  3721. else
  3722. {
  3723. $this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
  3724. if (!empty($line->desc)) {
  3725. $this->tpl['label'].=$line->desc;
  3726. }else {
  3727. $this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
  3728. }
  3729. // Dates
  3730. if ($line->product_type == 1 && ($date_start || $date_end))
  3731. {
  3732. $this->tpl['label'].= get_date_range($date_start,$date_end);
  3733. }
  3734. }
  3735. if (! empty($line->desc))
  3736. {
  3737. if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object
  3738. {
  3739. $discount=new DiscountAbsolute($this->db);
  3740. $discount->fetch($line->fk_remise_except);
  3741. $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
  3742. }
  3743. elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object
  3744. {
  3745. $discount=new DiscountAbsolute($this->db);
  3746. $discount->fetch($line->fk_remise_except);
  3747. $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
  3748. }
  3749. elseif ($line->desc == '(EXCESS RECEIVED)')
  3750. {
  3751. $discount=new DiscountAbsolute($this->db);
  3752. $discount->fetch($line->fk_remise_except);
  3753. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
  3754. }
  3755. elseif ($line->desc == '(EXCESS PAID)')
  3756. {
  3757. $discount=new DiscountAbsolute($this->db);
  3758. $discount->fetch($line->fk_remise_except);
  3759. $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
  3760. }
  3761. else
  3762. {
  3763. $this->tpl['description'] = dol_trunc($line->desc,60);
  3764. }
  3765. }
  3766. else
  3767. {
  3768. $this->tpl['description'] = '&nbsp;';
  3769. }
  3770. // VAT Rate
  3771. $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
  3772. $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
  3773. if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
  3774. $this->tpl['price'] = price($line->subprice);
  3775. $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
  3776. $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
  3777. if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
  3778. $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
  3779. // Is the line strike or not
  3780. $this->tpl['strike']=0;
  3781. if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
  3782. // Output template part (modules that overwrite templates must declare this into descriptor)
  3783. // Use global variables + $dateSelector + $seller and $buyer
  3784. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
  3785. foreach($dirtpls as $reldir)
  3786. {
  3787. $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
  3788. if (empty($conf->file->strict_mode)) {
  3789. $res=@include $tpl;
  3790. } else {
  3791. $res=include $tpl; // for debug
  3792. }
  3793. if ($res) break;
  3794. }
  3795. }
  3796. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3797. /**
  3798. * Add resources to the current object : add entry into llx_element_resources
  3799. * Need $this->element & $this->id
  3800. *
  3801. * @param int $resource_id Resource id
  3802. * @param string $resource_type 'resource'
  3803. * @param int $busy Busy or not
  3804. * @param int $mandatory Mandatory or not
  3805. * @return int <=0 if KO, >0 if OK
  3806. */
  3807. function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
  3808. {
  3809. // phpcs:enable
  3810. $this->db->begin();
  3811. $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
  3812. $sql.= "resource_id";
  3813. $sql.= ", resource_type";
  3814. $sql.= ", element_id";
  3815. $sql.= ", element_type";
  3816. $sql.= ", busy";
  3817. $sql.= ", mandatory";
  3818. $sql.= ") VALUES (";
  3819. $sql.= $resource_id;
  3820. $sql.= ", '".$this->db->escape($resource_type)."'";
  3821. $sql.= ", '".$this->db->escape($this->id)."'";
  3822. $sql.= ", '".$this->db->escape($this->element)."'";
  3823. $sql.= ", '".$this->db->escape($busy)."'";
  3824. $sql.= ", '".$this->db->escape($mandatory)."'";
  3825. $sql.= ")";
  3826. dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
  3827. if ($this->db->query($sql))
  3828. {
  3829. $this->db->commit();
  3830. return 1;
  3831. }
  3832. else
  3833. {
  3834. $this->error=$this->db->lasterror();
  3835. $this->db->rollback();
  3836. return 0;
  3837. }
  3838. }
  3839. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3840. /**
  3841. * Delete a link to resource line
  3842. *
  3843. * @param int $rowid Id of resource line to delete
  3844. * @param int $element element name (for trigger) TODO: use $this->element into commonobject class
  3845. * @param int $notrigger Disable all triggers
  3846. * @return int >0 if OK, <0 if KO
  3847. */
  3848. function delete_resource($rowid, $element, $notrigger=0)
  3849. {
  3850. // phpcs:enable
  3851. global $user;
  3852. $this->db->begin();
  3853. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
  3854. $sql.= " WHERE rowid=".$rowid;
  3855. dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
  3856. $resql=$this->db->query($sql);
  3857. if (! $resql)
  3858. {
  3859. $this->error=$this->db->lasterror();
  3860. $this->db->rollback();
  3861. return -1;
  3862. }
  3863. else
  3864. {
  3865. if (! $notrigger)
  3866. {
  3867. $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
  3868. if ($result < 0) { $this->db->rollback(); return -1; }
  3869. }
  3870. $this->db->commit();
  3871. return 1;
  3872. }
  3873. }
  3874. /**
  3875. * Overwrite magic function to solve problem of cloning object that are kept as references
  3876. *
  3877. * @return void
  3878. */
  3879. function __clone()
  3880. {
  3881. // Force a copy of this->lines, otherwise it will point to same object.
  3882. if (isset($this->lines) && is_array($this->lines))
  3883. {
  3884. $nboflines=count($this->lines);
  3885. for($i=0; $i < $nboflines; $i++)
  3886. {
  3887. $this->lines[$i] = clone $this->lines[$i];
  3888. }
  3889. }
  3890. }
  3891. /**
  3892. * Common function for all objects extending CommonObject for generating documents
  3893. *
  3894. * @param string $modelspath Relative folder where generators are placed
  3895. * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
  3896. * @param Translate $outputlangs Output language to use
  3897. * @param int $hidedetails 1 to hide details. 0 by default
  3898. * @param int $hidedesc 1 to hide product description. 0 by default
  3899. * @param int $hideref 1 to hide product reference. 0 by default
  3900. * @param null|array $moreparams Array to provide more information
  3901. * @return int >0 if OK, <0 if KO
  3902. * @see addFileIntoDatabaseIndex
  3903. */
  3904. protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
  3905. {
  3906. global $conf, $langs, $user;
  3907. $srctemplatepath='';
  3908. // Increase limit for PDF build
  3909. $err=error_reporting();
  3910. error_reporting(0);
  3911. @set_time_limit(120);
  3912. error_reporting($err);
  3913. // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
  3914. $tmp=explode(':',$modele,2);
  3915. if (! empty($tmp[1]))
  3916. {
  3917. $modele=$tmp[0];
  3918. $srctemplatepath=$tmp[1];
  3919. }
  3920. // Search template files
  3921. $file=''; $classname=''; $filefound=0;
  3922. $dirmodels=array('/');
  3923. if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
  3924. foreach($dirmodels as $reldir)
  3925. {
  3926. foreach(array('doc','pdf') as $prefix)
  3927. {
  3928. if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php
  3929. else $file = $prefix."_".$modele.".modules.php";
  3930. // On verifie l'emplacement du modele
  3931. $file=dol_buildpath($reldir.$modelspath.$file,0);
  3932. if (file_exists($file))
  3933. {
  3934. $filefound=1;
  3935. $classname=$prefix.'_'.$modele;
  3936. break;
  3937. }
  3938. }
  3939. if ($filefound) break;
  3940. }
  3941. // If generator was found
  3942. if ($filefound)
  3943. {
  3944. global $db; // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
  3945. require_once $file;
  3946. $obj = new $classname($this->db);
  3947. // If generator is ODT, we must have srctemplatepath defined, if not we set it.
  3948. if ($obj->type == 'odt' && empty($srctemplatepath))
  3949. {
  3950. $varfortemplatedir=$obj->scandir;
  3951. if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir))
  3952. {
  3953. $dirtoscan=$conf->global->$varfortemplatedir;
  3954. $listoffiles=array();
  3955. // Now we add first model found in directories scanned
  3956. $listofdir=explode(',',$dirtoscan);
  3957. foreach($listofdir as $key => $tmpdir)
  3958. {
  3959. $tmpdir=trim($tmpdir);
  3960. $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
  3961. if (! $tmpdir) { unset($listofdir[$key]); continue; }
  3962. if (is_dir($tmpdir))
  3963. {
  3964. $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
  3965. if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
  3966. }
  3967. }
  3968. if (count($listoffiles))
  3969. {
  3970. foreach($listoffiles as $record)
  3971. {
  3972. $srctemplatepath=$record['fullname'];
  3973. break;
  3974. }
  3975. }
  3976. }
  3977. if (empty($srctemplatepath))
  3978. {
  3979. $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
  3980. return -1;
  3981. }
  3982. }
  3983. if ($obj->type == 'odt' && ! empty($srctemplatepath))
  3984. {
  3985. if (! dol_is_file($srctemplatepath))
  3986. {
  3987. $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
  3988. return -1;
  3989. }
  3990. }
  3991. // We save charset_output to restore it because write_file can change it if needed for
  3992. // output format that does not support UTF8.
  3993. $sav_charset_output=$outputlangs->charset_output;
  3994. if (in_array(get_class($this), array('Adherent')))
  3995. {
  3996. $arrayofrecords = array(); // The write_file of templates of adherent class need this var
  3997. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
  3998. }
  3999. else
  4000. {
  4001. $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
  4002. }
  4003. // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
  4004. if ($resultwritefile > 0)
  4005. {
  4006. $outputlangs->charset_output=$sav_charset_output;
  4007. // We delete old preview
  4008. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4009. dol_delete_preview($this);
  4010. // Index file in database
  4011. if (! empty($obj->result['fullpath']))
  4012. {
  4013. $destfull = $obj->result['fullpath'];
  4014. $upload_dir = dirname($destfull);
  4015. $destfile = basename($destfull);
  4016. $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
  4017. if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir
  4018. {
  4019. $filename = basename($destfile);
  4020. $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
  4021. $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
  4022. include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  4023. $ecmfile=new EcmFiles($this->db);
  4024. $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename);
  4025. // Set the public "share" key
  4026. $setsharekey = false;
  4027. if ($this->element == 'propal')
  4028. {
  4029. $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
  4030. if ($useonlinesignature) $setsharekey=true;
  4031. if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
  4032. }
  4033. if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
  4034. if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
  4035. if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
  4036. if ($setsharekey)
  4037. {
  4038. if (empty($ecmfile->share)) // Because object not found or share not set yet
  4039. {
  4040. require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
  4041. $ecmfile->share = getRandomPassword(true);
  4042. }
  4043. }
  4044. if ($result > 0)
  4045. {
  4046. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4047. $ecmfile->fullpath_orig = '';
  4048. $ecmfile->gen_or_uploaded = 'generated';
  4049. $ecmfile->description = ''; // indexed content
  4050. $ecmfile->keyword = ''; // keyword content
  4051. $result = $ecmfile->update($user);
  4052. if ($result < 0)
  4053. {
  4054. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4055. }
  4056. }
  4057. else
  4058. {
  4059. $ecmfile->entity = $conf->entity;
  4060. $ecmfile->filepath = $rel_dir;
  4061. $ecmfile->filename = $filename;
  4062. $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
  4063. $ecmfile->fullpath_orig = '';
  4064. $ecmfile->gen_or_uploaded = 'generated';
  4065. $ecmfile->description = ''; // indexed content
  4066. $ecmfile->keyword = ''; // keyword content
  4067. $ecmfile->src_object_type = $this->table_element;
  4068. $ecmfile->src_object_id = $this->id;
  4069. $result = $ecmfile->create($user);
  4070. if ($result < 0)
  4071. {
  4072. setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
  4073. }
  4074. }
  4075. /*$this->result['fullname']=$destfull;
  4076. $this->result['filepath']=$ecmfile->filepath;
  4077. $this->result['filename']=$ecmfile->filename;*/
  4078. //var_dump($obj->update_main_doc_field);exit;
  4079. // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
  4080. $update_main_doc_field=0;
  4081. if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
  4082. if ($update_main_doc_field && ! empty($this->table_element))
  4083. {
  4084. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
  4085. $sql.= ' WHERE rowid = '.$this->id;
  4086. $resql = $this->db->query($sql);
  4087. if (! $resql) dol_print_error($this->db);
  4088. }
  4089. }
  4090. }
  4091. else
  4092. {
  4093. dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
  4094. }
  4095. // Success in building document. We build meta file.
  4096. dol_meta_create($this);
  4097. return 1;
  4098. }
  4099. else
  4100. {
  4101. $outputlangs->charset_output=$sav_charset_output;
  4102. dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
  4103. return -1;
  4104. }
  4105. }
  4106. else
  4107. {
  4108. $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
  4109. dol_print_error('',$this->error);
  4110. return -1;
  4111. }
  4112. }
  4113. /**
  4114. * Build thumb
  4115. * @TODO Move this into files.lib.php
  4116. *
  4117. * @param string $file Path file in UTF8 to original file to create thumbs from.
  4118. * @return void
  4119. */
  4120. function addThumbs($file)
  4121. {
  4122. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
  4123. require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
  4124. $file_osencoded=dol_osencode($file);
  4125. if (file_exists($file_osencoded))
  4126. {
  4127. // Create small thumbs for company (Ratio is near 16/9)
  4128. // Used on logon for example
  4129. vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
  4130. // Create mini thumbs for company (Ratio is near 16/9)
  4131. // Used on menu or for setup page for example
  4132. vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
  4133. }
  4134. }
  4135. /* Functions common to commonobject and commonobjectline */
  4136. /* For default values */
  4137. /**
  4138. * Return the default value to use for a field when showing the create form of object.
  4139. * Return values in this order:
  4140. * 1) If parameter is available into POST, we return it first.
  4141. * 2) If not but an alternate value was provided as parameter of function, we return it.
  4142. * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
  4143. * 4) Return value found into database (TODO No yet implemented)
  4144. *
  4145. * @param string $fieldname Name of field
  4146. * @param string $alternatevalue Alternate value to use
  4147. * @return string|string[] Default value (can be an array if the GETPOST return an array)
  4148. **/
  4149. function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
  4150. {
  4151. global $conf, $_POST;
  4152. // If param here has been posted, we use this value first.
  4153. if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
  4154. if (isset($alternatevalue)) return $alternatevalue;
  4155. $newelement=$this->element;
  4156. if ($newelement == 'facture') $newelement='invoice';
  4157. if ($newelement == 'commande') $newelement='order';
  4158. if (empty($newelement))
  4159. {
  4160. dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
  4161. return '';
  4162. }
  4163. $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
  4164. //var_dump($keyforfieldname);
  4165. if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
  4166. // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
  4167. }
  4168. /* For triggers */
  4169. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4170. /**
  4171. * Call trigger based on this instance.
  4172. * Some context information may also be provided into array property this->context.
  4173. * NB: Error from trigger are stacked in interface->errors
  4174. * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
  4175. *
  4176. * @param string $trigger_name trigger's name to execute
  4177. * @param User $user Object user
  4178. * @return int Result of run_triggers
  4179. */
  4180. function call_trigger($trigger_name, $user)
  4181. {
  4182. // phpcs:enable
  4183. global $langs,$conf;
  4184. include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
  4185. $interface=new Interfaces($this->db);
  4186. $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
  4187. if ($result < 0)
  4188. {
  4189. if (!empty($this->errors))
  4190. {
  4191. $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.
  4192. }
  4193. else
  4194. {
  4195. $this->errors=$interface->errors;
  4196. }
  4197. }
  4198. return $result;
  4199. }
  4200. /* Functions for extrafields */
  4201. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  4202. /**
  4203. * Function to get extra fields of an object into $this->array_options
  4204. * This method is in most cases called by method fetch of objects but you can call it separately.
  4205. *
  4206. * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
  4207. * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
  4208. * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
  4209. */
  4210. function fetch_optionals($rowid=null, $optionsArray=null)
  4211. {
  4212. // phpcs:enable
  4213. if (empty($rowid)) $rowid=$this->id;
  4214. // To avoid SQL errors. Probably not the better solution though
  4215. if (!$this->table_element) {
  4216. return 0;
  4217. }
  4218. $this->array_options=array();
  4219. if (! is_array($optionsArray))
  4220. {
  4221. // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
  4222. // TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
  4223. // global $extrafields;
  4224. //if (! is_object($extrafields))
  4225. //{
  4226. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4227. $extrafields = new ExtraFields($this->db);
  4228. //}
  4229. // Load array of extrafields for elementype = $this->table_element
  4230. if (empty($extrafields->attributes[$this->table_element]['loaded']))
  4231. {
  4232. $extrafields->fetch_name_optionals_label($this->table_element);
  4233. }
  4234. $optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
  4235. }
  4236. else
  4237. {
  4238. global $extrafields;
  4239. dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
  4240. }
  4241. $table_element = $this->table_element;
  4242. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4243. // Request to get complementary values
  4244. if (is_array($optionsArray) && count($optionsArray) > 0)
  4245. {
  4246. $sql = "SELECT rowid";
  4247. foreach ($optionsArray as $name => $label)
  4248. {
  4249. if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
  4250. {
  4251. $sql.= ", ".$name;
  4252. }
  4253. }
  4254. $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
  4255. $sql.= " WHERE fk_object = ".$rowid;
  4256. //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
  4257. $resql=$this->db->query($sql);
  4258. if ($resql)
  4259. {
  4260. $this->array_options = array();
  4261. $numrows=$this->db->num_rows($resql);
  4262. if ($numrows)
  4263. {
  4264. $tab = $this->db->fetch_array($resql);
  4265. foreach ($tab as $key => $value)
  4266. {
  4267. // 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)
  4268. if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
  4269. {
  4270. // we can add this attribute to object
  4271. if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
  4272. {
  4273. //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
  4274. $this->array_options["options_".$key]=$this->db->jdate($value);
  4275. }
  4276. else
  4277. {
  4278. $this->array_options["options_".$key]=$value;
  4279. }
  4280. //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
  4281. }
  4282. }
  4283. }
  4284. $this->db->free($resql);
  4285. if ($numrows) return $numrows;
  4286. else return 0;
  4287. }
  4288. else
  4289. {
  4290. dol_print_error($this->db);
  4291. return -1;
  4292. }
  4293. }
  4294. return 0;
  4295. }
  4296. /**
  4297. * Delete all extra fields values for the current object.
  4298. *
  4299. * @return int <0 if KO, >0 if OK
  4300. */
  4301. function deleteExtraFields()
  4302. {
  4303. $this->db->begin();
  4304. $table_element = $this->table_element;
  4305. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4306. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4307. dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
  4308. $resql=$this->db->query($sql_del);
  4309. if (! $resql)
  4310. {
  4311. $this->error=$this->db->lasterror();
  4312. $this->db->rollback();
  4313. return -1;
  4314. }
  4315. else
  4316. {
  4317. $this->db->commit();
  4318. return 1;
  4319. }
  4320. }
  4321. /**
  4322. * Add/Update all extra fields values for the current object.
  4323. * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4324. * This function delete record with all extrafields and insert them again from the array $this->array_options.
  4325. *
  4326. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4327. * @param User $userused Object user
  4328. * @return int -1=error, O=did nothing, 1=OK
  4329. * @see updateExtraField, setValueFrom
  4330. */
  4331. function insertExtraFields($trigger='', $userused=null)
  4332. {
  4333. global $conf,$langs,$user;
  4334. if (empty($userused)) $userused=$user;
  4335. $error=0;
  4336. if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
  4337. if (! empty($this->array_options))
  4338. {
  4339. // Check parameters
  4340. $langs->load('admin');
  4341. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4342. $extrafields = new ExtraFields($this->db);
  4343. $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
  4344. //Eliminate copied source object extra_fields that do not exist in target object
  4345. $new_array_options=array();
  4346. foreach ($this->array_options as $key => $value) {
  4347. if (in_array(substr($key,8), array_keys($target_extrafields))) // We remove the 'options_' from $key for test
  4348. $new_array_options[$key] = $value;
  4349. elseif (in_array($key, array_keys($target_extrafields))) // We test on $key that does not contains the 'options_' prefix
  4350. $new_array_options['options_'.$key] = $value;
  4351. }
  4352. foreach($new_array_options as $key => $value)
  4353. {
  4354. $attributeKey = substr($key,8); // Remove 'options_' prefix
  4355. $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
  4356. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
  4357. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
  4358. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
  4359. if ($attributeRequired)
  4360. {
  4361. $mandatorypb=false;
  4362. if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
  4363. if ($this->array_options[$key] === '') $mandatorypb=true;
  4364. if ($mandatorypb)
  4365. {
  4366. $this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
  4367. return -1;
  4368. }
  4369. }
  4370. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4371. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4372. switch ($attributeType)
  4373. {
  4374. case 'int':
  4375. if (!is_numeric($value) && $value!='')
  4376. {
  4377. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4378. return -1;
  4379. }
  4380. elseif ($value=='')
  4381. {
  4382. $new_array_options[$key] = null;
  4383. }
  4384. break;
  4385. case 'double':
  4386. $value = price2num($value);
  4387. if (!is_numeric($value) && $value!='')
  4388. {
  4389. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4390. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4391. return -1;
  4392. }
  4393. elseif ($value=='')
  4394. {
  4395. $new_array_options[$key] = null;
  4396. }
  4397. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4398. $new_array_options[$key] = $value;
  4399. break;
  4400. /*case 'select': // Not required, we chosed value='0' for undefined values
  4401. if ($value=='-1')
  4402. {
  4403. $this->array_options[$key] = null;
  4404. }
  4405. break;*/
  4406. case 'password':
  4407. $algo='';
  4408. if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
  4409. {
  4410. // If there is an encryption choice, we use it to crypt data before insert
  4411. $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
  4412. $algo=reset($tmparrays);
  4413. if ($algo != '')
  4414. {
  4415. //global $action; // $action may be 'create', 'update', 'update_extras'...
  4416. //var_dump($action);
  4417. //var_dump($this->oldcopy);exit;
  4418. if (is_object($this->oldcopy)) // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
  4419. {
  4420. //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
  4421. if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
  4422. {
  4423. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4424. }
  4425. else
  4426. {
  4427. // var_dump($algo);
  4428. $newvalue = dol_hash($this->array_options[$key], $algo);
  4429. $new_array_options[$key] = $newvalue;
  4430. }
  4431. }
  4432. else
  4433. {
  4434. $new_array_options[$key] = $this->array_options[$key]; // Value is kept
  4435. }
  4436. }
  4437. }
  4438. else // Common usage
  4439. {
  4440. $new_array_options[$key] = $this->array_options[$key];
  4441. }
  4442. break;
  4443. case 'price':
  4444. $new_array_options[$key] = price2num($this->array_options[$key]);
  4445. break;
  4446. case 'date':
  4447. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  4448. break;
  4449. case 'datetime':
  4450. // If data is a string instead of a timestamp, we convert it
  4451. if (! is_int($this->array_options[$key])) {
  4452. $this->array_options[$key] = strtotime($this->array_options[$key]);
  4453. }
  4454. $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
  4455. break;
  4456. case 'link':
  4457. $param_list=array_keys($attributeParam['options']);
  4458. // 0 : ObjectName
  4459. // 1 : classPath
  4460. $InfoFieldList = explode(":", $param_list[0]);
  4461. dol_include_once($InfoFieldList[1]);
  4462. if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
  4463. {
  4464. if ($value == '-1') // -1 is key for no defined in combo list of objects
  4465. {
  4466. $new_array_options[$key]='';
  4467. }
  4468. elseif ($value)
  4469. {
  4470. $object = new $InfoFieldList[0]($this->db);
  4471. if (is_numeric($value)) $res=$object->fetch($value);
  4472. else $res=$object->fetch('',$value);
  4473. if ($res > 0) $new_array_options[$key]=$object->id;
  4474. else
  4475. {
  4476. $this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
  4477. $this->db->rollback();
  4478. return -1;
  4479. }
  4480. }
  4481. }
  4482. else
  4483. {
  4484. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  4485. }
  4486. break;
  4487. }
  4488. }
  4489. $this->db->begin();
  4490. $table_element = $this->table_element;
  4491. if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
  4492. $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
  4493. dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
  4494. $this->db->query($sql_del);
  4495. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
  4496. foreach($new_array_options as $key => $value)
  4497. {
  4498. $attributeKey = substr($key,8); // Remove 'options_' prefix
  4499. // Add field of attribut
  4500. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
  4501. $sql.=",".$attributeKey;
  4502. }
  4503. $sql .= ") VALUES (".$this->id;
  4504. foreach($new_array_options as $key => $value)
  4505. {
  4506. $attributeKey = substr($key,8); // Remove 'options_' prefix
  4507. // Add field of attribute
  4508. if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
  4509. {
  4510. if ($new_array_options[$key] != '')
  4511. {
  4512. $sql.=",'".$this->db->escape($new_array_options[$key])."'";
  4513. }
  4514. else
  4515. {
  4516. $sql.=",null";
  4517. }
  4518. }
  4519. }
  4520. $sql.=")";
  4521. dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
  4522. $resql = $this->db->query($sql);
  4523. if (! $resql)
  4524. {
  4525. $this->error=$this->db->lasterror();
  4526. $error++;
  4527. }
  4528. if (! $error && $trigger)
  4529. {
  4530. // Call trigger
  4531. $this->context=array('extrafieldaddupdate'=>1);
  4532. $result=$this->call_trigger($trigger, $userused);
  4533. if ($result < 0) $error++;
  4534. // End call trigger
  4535. }
  4536. if ($error)
  4537. {
  4538. $this->db->rollback();
  4539. return -1;
  4540. }
  4541. else
  4542. {
  4543. $this->db->commit();
  4544. return 1;
  4545. }
  4546. }
  4547. else return 0;
  4548. }
  4549. /**
  4550. * Update an extra field value for the current object.
  4551. * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
  4552. *
  4553. * @param string $key Key of the extrafield (without starting 'options_')
  4554. * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY)
  4555. * @param User $userused Object user
  4556. * @return int -1=error, O=did nothing, 1=OK
  4557. * @see setValueFrom, insertExtraFields
  4558. */
  4559. function updateExtraField($key, $trigger, $userused)
  4560. {
  4561. global $conf,$langs,$user;
  4562. if (empty($userused)) $userused=$user;
  4563. $error=0;
  4564. if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
  4565. if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
  4566. {
  4567. // Check parameters
  4568. $langs->load('admin');
  4569. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  4570. $extrafields = new ExtraFields($this->db);
  4571. $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
  4572. $value=$this->array_options["options_".$key];
  4573. $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
  4574. $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
  4575. $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
  4576. $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
  4577. //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
  4578. //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
  4579. switch ($attributeType)
  4580. {
  4581. case 'int':
  4582. if (!is_numeric($value) && $value!='')
  4583. {
  4584. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
  4585. return -1;
  4586. }
  4587. elseif ($value=='')
  4588. {
  4589. $this->array_options["options_".$key] = null;
  4590. }
  4591. break;
  4592. case 'double':
  4593. $value = price2num($value);
  4594. if (!is_numeric($value) && $value!='')
  4595. {
  4596. dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
  4597. $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
  4598. return -1;
  4599. }
  4600. elseif ($value=='')
  4601. {
  4602. $this->array_options["options_".$key] = null;
  4603. }
  4604. //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
  4605. $this->array_options["options_".$key] = $value;
  4606. break;
  4607. /*case 'select': // Not required, we chosed value='0' for undefined values
  4608. if ($value=='-1')
  4609. {
  4610. $this->array_options[$key] = null;
  4611. }
  4612. break;*/
  4613. case 'price':
  4614. $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
  4615. break;
  4616. case 'date':
  4617. $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
  4618. break;
  4619. case 'datetime':
  4620. $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
  4621. break;
  4622. case 'link':
  4623. $param_list=array_keys($attributeParam['options']);
  4624. // 0 : ObjectName
  4625. // 1 : classPath
  4626. $InfoFieldList = explode(":", $param_list[0]);
  4627. dol_include_once($InfoFieldList[1]);
  4628. if ($value)
  4629. {
  4630. $object = new $InfoFieldList[0]($this->db);
  4631. $object->fetch(0,$value);
  4632. $this->array_options["options_".$key]=$object->id;
  4633. }
  4634. break;
  4635. }
  4636. $this->db->begin();
  4637. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
  4638. $sql .= " WHERE fk_object = ".$this->id;
  4639. $resql = $this->db->query($sql);
  4640. if (! $resql)
  4641. {
  4642. $error++;
  4643. $this->error=$this->db->lasterror();
  4644. }
  4645. if (! $error && $trigger)
  4646. {
  4647. // Call trigger
  4648. $this->context=array('extrafieldupdate'=>1);
  4649. $result=$this->call_trigger($trigger, $userused);
  4650. if ($result < 0) $error++;
  4651. // End call trigger
  4652. }
  4653. if ($error)
  4654. {
  4655. dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
  4656. $this->db->rollback();
  4657. return -1;
  4658. }
  4659. else
  4660. {
  4661. $this->db->commit();
  4662. return 1;
  4663. }
  4664. }
  4665. else return 0;
  4666. }
  4667. /**
  4668. * Return HTML string to put an input field into a page
  4669. * Code very similar with showInputField of extra fields
  4670. *
  4671. * @param array $val Array of properties for field to show
  4672. * @param string $key Key of attribute
  4673. * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
  4674. * @param string $moreparam To add more parameters on html input tag
  4675. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  4676. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  4677. * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
  4678. * @return string
  4679. */
  4680. function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
  4681. {
  4682. global $conf,$langs,$form;
  4683. if (! is_object($form))
  4684. {
  4685. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  4686. $form=new Form($this->db);
  4687. }
  4688. $val=$this->fields[$key];
  4689. $out='';
  4690. $type='';
  4691. $param = array();
  4692. $param['options']=array();
  4693. $size =$this->fields[$key]['size'];
  4694. // Because we work on extrafields
  4695. if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
  4696. $param['options']=array($reg[1].':'.$reg[2]=>'N');
  4697. $type ='link';
  4698. } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
  4699. $param['options']=array($reg[1].':'.$reg[2]=>'N');
  4700. $type ='link';
  4701. } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
  4702. $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
  4703. $type ='sellist';
  4704. } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
  4705. $param['options']=array();
  4706. $type ='varchar';
  4707. $size=$reg[1];
  4708. } elseif(preg_match('/varchar/', $val['type'])) {
  4709. $param['options']=array();
  4710. $type ='varchar';
  4711. } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
  4712. $param['options']=$this->fields[$key]['arrayofkeyval'];
  4713. $type ='select';
  4714. } else {
  4715. $param['options']=array();
  4716. $type =$this->fields[$key]['type'];
  4717. }
  4718. $label=$this->fields[$key]['label'];
  4719. //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
  4720. $default=$this->fields[$key]['default'];
  4721. $computed=$this->fields[$key]['computed'];
  4722. $unique=$this->fields[$key]['unique'];
  4723. $required=$this->fields[$key]['required'];
  4724. $langfile=$this->fields[$key]['langfile'];
  4725. $list=$this->fields[$key]['list'];
  4726. $hidden=abs($this->fields[$key]['visible'])!=1?1:0;
  4727. $objectid = $this->id;
  4728. if ($computed)
  4729. {
  4730. if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
  4731. else return '';
  4732. }
  4733. // Use in priority showsize from parameters, then $val['css'] then autodefine
  4734. if (empty($morecss) && ! empty($val['css']))
  4735. {
  4736. $showsize = $val['css'];
  4737. }
  4738. if (empty($morecss))
  4739. {
  4740. if ($type == 'date')
  4741. {
  4742. $morecss = 'minwidth100imp';
  4743. }
  4744. elseif ($type == 'datetime')
  4745. {
  4746. $morecss = 'minwidth200imp';
  4747. }
  4748. elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
  4749. {
  4750. $morecss = 'maxwidth75';
  4751. }elseif ($type == 'url')
  4752. {
  4753. $morecss='minwidth400';
  4754. }
  4755. elseif ($type == 'boolean')
  4756. {
  4757. $morecss='';
  4758. }
  4759. else
  4760. {
  4761. if (round($size) < 12)
  4762. {
  4763. $morecss = 'minwidth100';
  4764. }
  4765. else if (round($size) <= 48)
  4766. {
  4767. $morecss = 'minwidth200';
  4768. }
  4769. else
  4770. {
  4771. $morecss = 'minwidth400';
  4772. }
  4773. }
  4774. }
  4775. if (in_array($type,array('date','datetime')))
  4776. {
  4777. $tmp=explode(',',$size);
  4778. $newsize=$tmp[0];
  4779. $showtime = in_array($type,array('datetime')) ? 1 : 0;
  4780. // Do not show current date when field not required (see selectDate() method)
  4781. if (!$required && $value == '') $value = '-1';
  4782. // TODO Must also support $moreparam
  4783. $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
  4784. }
  4785. elseif (in_array($type,array('int','integer')))
  4786. {
  4787. $tmp=explode(',',$size);
  4788. $newsize=$tmp[0];
  4789. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
  4790. }
  4791. elseif (preg_match('/varchar/', $type))
  4792. {
  4793. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
  4794. }
  4795. elseif (in_array($type, array('mail', 'phone', 'url')))
  4796. {
  4797. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
  4798. }
  4799. elseif ($type == 'text')
  4800. {
  4801. if (! preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field
  4802. {
  4803. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  4804. $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
  4805. $out=$doleditor->Create(1);
  4806. }
  4807. else
  4808. {
  4809. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
  4810. }
  4811. }
  4812. elseif ($type == 'html')
  4813. {
  4814. if (! preg_match('/search_/', $keyprefix)) // If keyprefix is search_ or search_options_, we must just use a simple text field
  4815. {
  4816. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  4817. $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
  4818. $out=$doleditor->Create(1);
  4819. }
  4820. else
  4821. {
  4822. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
  4823. }
  4824. }
  4825. elseif ($type == 'boolean')
  4826. {
  4827. $checked='';
  4828. if (!empty($value)) {
  4829. $checked=' checked value="1" ';
  4830. } else {
  4831. $checked=' value="1" ';
  4832. }
  4833. $out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
  4834. }
  4835. elseif ($type == 'price')
  4836. {
  4837. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  4838. $value=price($value);
  4839. }
  4840. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
  4841. }
  4842. elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
  4843. {
  4844. if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
  4845. $value=price($value);
  4846. }
  4847. $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
  4848. }
  4849. elseif ($type == 'select')
  4850. {
  4851. $out = '';
  4852. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
  4853. {
  4854. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  4855. $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  4856. }
  4857. $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
  4858. if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
  4859. foreach ($param['options'] as $key => $val)
  4860. {
  4861. if ((string) $key == '') continue;
  4862. list($val, $parent) = explode('|', $val);
  4863. $out.='<option value="'.$key.'"';
  4864. $out.= (((string) $value == (string) $key)?' selected':'');
  4865. $out.= (!empty($parent)?' parent="'.$parent.'"':'');
  4866. $out.='>'.$val.'</option>';
  4867. }
  4868. $out.='</select>';
  4869. }
  4870. elseif ($type == 'sellist')
  4871. {
  4872. $out = '';
  4873. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
  4874. {
  4875. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  4876. $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
  4877. }
  4878. $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
  4879. if (is_array($param['options']))
  4880. {
  4881. $param_list=array_keys($param['options']);
  4882. $InfoFieldList = explode(":", $param_list[0]);
  4883. $parentName='';
  4884. $parentField='';
  4885. // 0 : tableName
  4886. // 1 : label field name
  4887. // 2 : key fields name (if differ of rowid)
  4888. // 3 : key field parent (for dependent lists)
  4889. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  4890. $keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
  4891. if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
  4892. {
  4893. if (strpos($InfoFieldList[4], 'extra.') !== false)
  4894. {
  4895. $keyList='main.'.$InfoFieldList[2].' as rowid';
  4896. } else {
  4897. $keyList=$InfoFieldList[2].' as rowid';
  4898. }
  4899. }
  4900. if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
  4901. {
  4902. list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
  4903. $keyList.= ', '.$parentField;
  4904. }
  4905. $fields_label = explode('|',$InfoFieldList[1]);
  4906. if (is_array($fields_label))
  4907. {
  4908. $keyList .=', ';
  4909. $keyList .= implode(', ', $fields_label);
  4910. }
  4911. $sqlwhere='';
  4912. $sql = 'SELECT '.$keyList;
  4913. $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
  4914. if (!empty($InfoFieldList[4]))
  4915. {
  4916. // can use SELECT request
  4917. if (strpos($InfoFieldList[4], '$SEL$')!==false) {
  4918. $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
  4919. }
  4920. // current object id can be use into filter
  4921. if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
  4922. $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
  4923. } else {
  4924. $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
  4925. }
  4926. //We have to join on extrafield table
  4927. if (strpos($InfoFieldList[4], 'extra')!==false)
  4928. {
  4929. $sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
  4930. $sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
  4931. }
  4932. else
  4933. {
  4934. $sqlwhere.= ' WHERE '.$InfoFieldList[4];
  4935. }
  4936. }
  4937. else
  4938. {
  4939. $sqlwhere.= ' WHERE 1=1';
  4940. }
  4941. // Some tables may have field, some other not. For the moment we disable it.
  4942. if (in_array($InfoFieldList[0],array('tablewithentity')))
  4943. {
  4944. $sqlwhere.= ' AND entity = '.$conf->entity;
  4945. }
  4946. $sql.=$sqlwhere;
  4947. //print $sql;
  4948. $sql .= ' ORDER BY ' . implode(', ', $fields_label);
  4949. dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
  4950. $resql = $this->db->query($sql);
  4951. if ($resql)
  4952. {
  4953. $out.='<option value="0">&nbsp;</option>';
  4954. $num = $this->db->num_rows($resql);
  4955. $i = 0;
  4956. while ($i < $num)
  4957. {
  4958. $labeltoshow='';
  4959. $obj = $this->db->fetch_object($resql);
  4960. // Several field into label (eq table:code|libelle:rowid)
  4961. $notrans = false;
  4962. $fields_label = explode('|',$InfoFieldList[1]);
  4963. if (is_array($fields_label))
  4964. {
  4965. $notrans = true;
  4966. foreach ($fields_label as $field_toshow)
  4967. {
  4968. $labeltoshow.= $obj->$field_toshow.' ';
  4969. }
  4970. }
  4971. else
  4972. {
  4973. $labeltoshow=$obj->{$InfoFieldList[1]};
  4974. }
  4975. $labeltoshow=dol_trunc($labeltoshow,45);
  4976. if ($value == $obj->rowid)
  4977. {
  4978. foreach ($fields_label as $field_toshow)
  4979. {
  4980. $translabel=$langs->trans($obj->$field_toshow);
  4981. if ($translabel!=$obj->$field_toshow) {
  4982. $labeltoshow=dol_trunc($translabel,18).' ';
  4983. }else {
  4984. $labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
  4985. }
  4986. }
  4987. $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  4988. }
  4989. else
  4990. {
  4991. if (! $notrans)
  4992. {
  4993. $translabel=$langs->trans($obj->{$InfoFieldList[1]});
  4994. if ($translabel!=$obj->{$InfoFieldList[1]}) {
  4995. $labeltoshow=dol_trunc($translabel,18);
  4996. }
  4997. else {
  4998. $labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
  4999. }
  5000. }
  5001. if (empty($labeltoshow)) $labeltoshow='(not defined)';
  5002. if ($value==$obj->rowid)
  5003. {
  5004. $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
  5005. }
  5006. if (!empty($InfoFieldList[3]) && $parentField)
  5007. {
  5008. $parent = $parentName.':'.$obj->{$parentField};
  5009. }
  5010. $out.='<option value="'.$obj->rowid.'"';
  5011. $out.= ($value==$obj->rowid?' selected':'');
  5012. $out.= (!empty($parent)?' parent="'.$parent.'"':'');
  5013. $out.='>'.$labeltoshow.'</option>';
  5014. }
  5015. $i++;
  5016. }
  5017. $this->db->free($resql);
  5018. }
  5019. else {
  5020. print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
  5021. }
  5022. }
  5023. $out.='</select>';
  5024. }
  5025. elseif ($type == 'checkbox')
  5026. {
  5027. $value_arr=explode(',',$value);
  5028. $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
  5029. }
  5030. elseif ($type == 'radio')
  5031. {
  5032. $out='';
  5033. foreach ($param['options'] as $keyopt => $val)
  5034. {
  5035. $out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
  5036. $out.=' value="'.$keyopt.'"';
  5037. $out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
  5038. $out.= ($value==$keyopt?'checked':'');
  5039. $out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
  5040. }
  5041. }
  5042. elseif ($type == 'chkbxlst')
  5043. {
  5044. if (is_array($value)) {
  5045. $value_arr = $value;
  5046. }
  5047. else {
  5048. $value_arr = explode(',', $value);
  5049. }
  5050. if (is_array($param['options'])) {
  5051. $param_list = array_keys($param['options']);
  5052. $InfoFieldList = explode(":", $param_list[0]);
  5053. $parentName='';
  5054. $parentField='';
  5055. // 0 : tableName
  5056. // 1 : label field name
  5057. // 2 : key fields name (if differ of rowid)
  5058. // 3 : key field parent (for dependent lists)
  5059. // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
  5060. $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
  5061. if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
  5062. list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
  5063. $keyList .= ', ' . $parentField;
  5064. }
  5065. if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
  5066. if (strpos($InfoFieldList[4], 'extra.') !== false) {
  5067. $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
  5068. } else {
  5069. $keyList = $InfoFieldList[2] . ' as rowid';
  5070. }
  5071. }
  5072. $fields_label = explode('|', $InfoFieldList[1]);
  5073. if (is_array($fields_label)) {
  5074. $keyList .= ', ';
  5075. $keyList .= implode(', ', $fields_label);
  5076. }
  5077. $sqlwhere = '';
  5078. $sql = 'SELECT ' . $keyList;
  5079. $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
  5080. if (! empty($InfoFieldList[4])) {
  5081. // can use SELECT request
  5082. if (strpos($InfoFieldList[4], '$SEL$')!==false) {
  5083. $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
  5084. }
  5085. // current object id can be use into filter
  5086. if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
  5087. $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
  5088. } else {
  5089. $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
  5090. }
  5091. // We have to join on extrafield table
  5092. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5093. $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
  5094. $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
  5095. } else {
  5096. $sqlwhere .= ' WHERE ' . $InfoFieldList[4];
  5097. }
  5098. } else {
  5099. $sqlwhere .= ' WHERE 1=1';
  5100. }
  5101. // Some tables may have field, some other not. For the moment we disable it.
  5102. if (in_array($InfoFieldList[0], array ('tablewithentity')))
  5103. {
  5104. $sqlwhere .= ' AND entity = ' . $conf->entity;
  5105. }
  5106. // $sql.=preg_replace('/^ AND /','',$sqlwhere);
  5107. // print $sql;
  5108. $sql .= $sqlwhere;
  5109. dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
  5110. $resql = $this->db->query($sql);
  5111. if ($resql) {
  5112. $num = $this->db->num_rows($resql);
  5113. $i = 0;
  5114. $data=array();
  5115. while ( $i < $num ) {
  5116. $labeltoshow = '';
  5117. $obj = $this->db->fetch_object($resql);
  5118. $notrans = false;
  5119. // Several field into label (eq table:code|libelle:rowid)
  5120. $fields_label = explode('|', $InfoFieldList[1]);
  5121. if (is_array($fields_label)) {
  5122. $notrans = true;
  5123. foreach ( $fields_label as $field_toshow ) {
  5124. $labeltoshow .= $obj->$field_toshow . ' ';
  5125. }
  5126. } else {
  5127. $labeltoshow = $obj->{$InfoFieldList[1]};
  5128. }
  5129. $labeltoshow = dol_trunc($labeltoshow, 45);
  5130. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5131. foreach ( $fields_label as $field_toshow ) {
  5132. $translabel = $langs->trans($obj->$field_toshow);
  5133. if ($translabel != $obj->$field_toshow) {
  5134. $labeltoshow = dol_trunc($translabel, 18) . ' ';
  5135. } else {
  5136. $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
  5137. }
  5138. }
  5139. $data[$obj->rowid]=$labeltoshow;
  5140. } else {
  5141. if (! $notrans) {
  5142. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5143. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5144. $labeltoshow = dol_trunc($translabel, 18);
  5145. } else {
  5146. $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
  5147. }
  5148. }
  5149. if (empty($labeltoshow))
  5150. $labeltoshow = '(not defined)';
  5151. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5152. $data[$obj->rowid]=$labeltoshow;
  5153. }
  5154. if (! empty($InfoFieldList[3]) && $parentField) {
  5155. $parent = $parentName . ':' . $obj->{$parentField};
  5156. }
  5157. $data[$obj->rowid]=$labeltoshow;
  5158. }
  5159. $i ++;
  5160. }
  5161. $this->db->free($resql);
  5162. $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
  5163. } else {
  5164. print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
  5165. }
  5166. }
  5167. }
  5168. elseif ($type == 'link')
  5169. {
  5170. $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath'
  5171. $showempty=(($required && $default != '')?0:1);
  5172. $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
  5173. }
  5174. elseif ($type == 'password')
  5175. {
  5176. // If prefix is 'search_', field is used as a filter, we use a common text field.
  5177. $out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
  5178. }
  5179. elseif ($type == 'array')
  5180. {
  5181. $newval = $val;
  5182. $newval['type'] = 'varchar(256)';
  5183. $out='';
  5184. $inputs = array();
  5185. if(! empty($value)) {
  5186. foreach($value as $option) {
  5187. $out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5188. $out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
  5189. }
  5190. }
  5191. $out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
  5192. $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
  5193. $newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
  5194. if(! empty($conf->use_javascript_ajax)) {
  5195. $out.= '
  5196. <script type="text/javascript">
  5197. $(document).ready(function() {
  5198. $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
  5199. $("'.dol_escape_js($newInput).'").insertBefore(this);
  5200. });
  5201. $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
  5202. $(this).parent().remove();
  5203. });
  5204. });
  5205. </script>';
  5206. }
  5207. }
  5208. if (!empty($hidden)) {
  5209. $out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
  5210. }
  5211. /* Add comments
  5212. if ($type == 'date') $out.=' (YYYY-MM-DD)';
  5213. elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
  5214. */
  5215. return $out;
  5216. }
  5217. /**
  5218. * Return HTML string to show a field into a page
  5219. * Code very similar with showOutputField of extra fields
  5220. *
  5221. * @param array $val Array of properties of field to show
  5222. * @param string $key Key of attribute
  5223. * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
  5224. * @param string $moreparam To add more parametes on html input tag
  5225. * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
  5226. * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
  5227. * @param mixed $showsize Value for css to define size. May also be a numeric.
  5228. * @return string
  5229. */
  5230. function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
  5231. {
  5232. global $conf,$langs,$form;
  5233. if (! is_object($form))
  5234. {
  5235. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  5236. $form=new Form($this->db);
  5237. }
  5238. $objectid = $this->id;
  5239. $label = $val['label'];
  5240. $type = $val['type'];
  5241. $size = $val['css'];
  5242. // Convert var to be able to share same code than showOutputField of extrafields
  5243. if (preg_match('/varchar\((\d+)\)/', $type, $reg))
  5244. {
  5245. $type = 'varchar'; // convert varchar(xx) int varchar
  5246. $size = $reg[1];
  5247. }
  5248. elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
  5249. if (is_array($val['arrayofkeyval'])) $type='select';
  5250. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
  5251. $default=$val['default'];
  5252. $computed=$val['computed'];
  5253. $unique=$val['unique'];
  5254. $required=$val['required'];
  5255. $param=$val['param'];
  5256. if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
  5257. if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
  5258. {
  5259. $type='link';
  5260. $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
  5261. }
  5262. $langfile=$val['langfile'];
  5263. $list=$val['list'];
  5264. $help=$val['help'];
  5265. $hidden=(($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
  5266. if ($hidden) return '';
  5267. // If field is a computed field, value must become result of compute
  5268. if ($computed)
  5269. {
  5270. // Make the eval of compute string
  5271. //var_dump($computed);
  5272. $value = dol_eval($computed, 1, 0);
  5273. }
  5274. if (empty($showsize))
  5275. {
  5276. if ($type == 'date')
  5277. {
  5278. //$showsize=10;
  5279. $showsize = 'minwidth100imp';
  5280. }
  5281. elseif ($type == 'datetime')
  5282. {
  5283. //$showsize=19;
  5284. $showsize = 'minwidth200imp';
  5285. }
  5286. elseif (in_array($type,array('int','double','price')))
  5287. {
  5288. //$showsize=10;
  5289. $showsize = 'maxwidth75';
  5290. }
  5291. elseif ($type == 'url')
  5292. {
  5293. $showsize='minwidth400';
  5294. }
  5295. elseif ($type == 'boolean')
  5296. {
  5297. $showsize='';
  5298. }
  5299. else
  5300. {
  5301. if (round($size) < 12)
  5302. {
  5303. $showsize = 'minwidth100';
  5304. }
  5305. else if (round($size) <= 48)
  5306. {
  5307. $showsize = 'minwidth200';
  5308. }
  5309. else
  5310. {
  5311. //$showsize=48;
  5312. $showsize = 'minwidth400';
  5313. }
  5314. }
  5315. }
  5316. // Format output value differently according to properties of field
  5317. if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
  5318. elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
  5319. elseif ($type == 'date')
  5320. {
  5321. if(! empty($value)) {
  5322. $value=dol_print_date($value,'day');
  5323. } else {
  5324. $value='';
  5325. }
  5326. }
  5327. elseif ($type == 'datetime')
  5328. {
  5329. if(! empty($value)) {
  5330. $value=dol_print_date($value,'dayhour');
  5331. } else {
  5332. $value='';
  5333. }
  5334. }
  5335. elseif ($type == 'double')
  5336. {
  5337. if (!empty($value)) {
  5338. $value=price($value);
  5339. }
  5340. }
  5341. elseif ($type == 'boolean')
  5342. {
  5343. $checked='';
  5344. if (!empty($value)) {
  5345. $checked=' checked ';
  5346. }
  5347. $value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
  5348. }
  5349. elseif ($type == 'mail')
  5350. {
  5351. $value=dol_print_email($value,0,0,0,64,1,1);
  5352. }
  5353. elseif ($type == 'url')
  5354. {
  5355. $value=dol_print_url($value,'_blank',32,1);
  5356. }
  5357. elseif ($type == 'phone')
  5358. {
  5359. $value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
  5360. }
  5361. elseif ($type == 'price')
  5362. {
  5363. $value=price($value,0,$langs,0,0,-1,$conf->currency);
  5364. }
  5365. elseif ($type == 'select')
  5366. {
  5367. $value=$param['options'][$value];
  5368. }
  5369. elseif ($type == 'sellist')
  5370. {
  5371. $param_list=array_keys($param['options']);
  5372. $InfoFieldList = explode(":", $param_list[0]);
  5373. $selectkey="rowid";
  5374. $keyList='rowid';
  5375. if (count($InfoFieldList)>=3)
  5376. {
  5377. $selectkey = $InfoFieldList[2];
  5378. $keyList=$InfoFieldList[2].' as rowid';
  5379. }
  5380. $fields_label = explode('|',$InfoFieldList[1]);
  5381. if(is_array($fields_label)) {
  5382. $keyList .=', ';
  5383. $keyList .= implode(', ', $fields_label);
  5384. }
  5385. $sql = 'SELECT '.$keyList;
  5386. $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
  5387. if (strpos($InfoFieldList[4], 'extra')!==false)
  5388. {
  5389. $sql.= ' as main';
  5390. }
  5391. if ($selectkey=='rowid' && empty($value)) {
  5392. $sql.= " WHERE ".$selectkey."=0";
  5393. } elseif ($selectkey=='rowid') {
  5394. $sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
  5395. }else {
  5396. $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5397. }
  5398. //$sql.= ' AND entity = '.$conf->entity;
  5399. dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
  5400. $resql = $this->db->query($sql);
  5401. if ($resql)
  5402. {
  5403. $value=''; // value was used, so now we reste it to use it to build final output
  5404. $obj = $this->db->fetch_object($resql);
  5405. // Several field into label (eq table:code|libelle:rowid)
  5406. $fields_label = explode('|',$InfoFieldList[1]);
  5407. if(is_array($fields_label) && count($fields_label)>1)
  5408. {
  5409. foreach ($fields_label as $field_toshow)
  5410. {
  5411. $translabel='';
  5412. if (!empty($obj->$field_toshow)) {
  5413. $translabel=$langs->trans($obj->$field_toshow);
  5414. }
  5415. if ($translabel!=$field_toshow) {
  5416. $value.=dol_trunc($translabel,18).' ';
  5417. }else {
  5418. $value.=$obj->$field_toshow.' ';
  5419. }
  5420. }
  5421. }
  5422. else
  5423. {
  5424. $translabel='';
  5425. if (!empty($obj->{$InfoFieldList[1]})) {
  5426. $translabel=$langs->trans($obj->{$InfoFieldList[1]});
  5427. }
  5428. if ($translabel!=$obj->{$InfoFieldList[1]}) {
  5429. $value=dol_trunc($translabel,18);
  5430. }else {
  5431. $value=$obj->{$InfoFieldList[1]};
  5432. }
  5433. }
  5434. }
  5435. else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
  5436. }
  5437. elseif ($type == 'radio')
  5438. {
  5439. $value=$param['options'][$value];
  5440. }
  5441. elseif ($type == 'checkbox')
  5442. {
  5443. $value_arr=explode(',',$value);
  5444. $value='';
  5445. if (is_array($value_arr))
  5446. {
  5447. foreach ($value_arr as $keyval=>$valueval) {
  5448. $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
  5449. }
  5450. }
  5451. $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5452. }
  5453. elseif ($type == 'chkbxlst')
  5454. {
  5455. $value_arr = explode(',', $value);
  5456. $param_list = array_keys($param['options']);
  5457. $InfoFieldList = explode(":", $param_list[0]);
  5458. $selectkey = "rowid";
  5459. $keyList = 'rowid';
  5460. if (count($InfoFieldList) >= 3) {
  5461. $selectkey = $InfoFieldList[2];
  5462. $keyList = $InfoFieldList[2] . ' as rowid';
  5463. }
  5464. $fields_label = explode('|', $InfoFieldList[1]);
  5465. if (is_array($fields_label)) {
  5466. $keyList .= ', ';
  5467. $keyList .= implode(', ', $fields_label);
  5468. }
  5469. $sql = 'SELECT ' . $keyList;
  5470. $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
  5471. if (strpos($InfoFieldList[4], 'extra') !== false) {
  5472. $sql .= ' as main';
  5473. }
  5474. // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
  5475. // $sql.= ' AND entity = '.$conf->entity;
  5476. dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
  5477. $resql = $this->db->query($sql);
  5478. if ($resql) {
  5479. $value = ''; // value was used, so now we reste it to use it to build final output
  5480. $toprint=array();
  5481. while ( $obj = $this->db->fetch_object($resql) ) {
  5482. // Several field into label (eq table:code|libelle:rowid)
  5483. $fields_label = explode('|', $InfoFieldList[1]);
  5484. if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
  5485. if (is_array($fields_label) && count($fields_label) > 1) {
  5486. foreach ( $fields_label as $field_toshow ) {
  5487. $translabel = '';
  5488. if (! empty($obj->$field_toshow)) {
  5489. $translabel = $langs->trans($obj->$field_toshow);
  5490. }
  5491. if ($translabel != $field_toshow) {
  5492. $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
  5493. } else {
  5494. $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
  5495. }
  5496. }
  5497. } else {
  5498. $translabel = '';
  5499. if (! empty($obj->{$InfoFieldList[1]})) {
  5500. $translabel = $langs->trans($obj->{$InfoFieldList[1]});
  5501. }
  5502. if ($translabel != $obj->{$InfoFieldList[1]}) {
  5503. $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
  5504. } else {
  5505. $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
  5506. }
  5507. }
  5508. }
  5509. }
  5510. $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5511. } else {
  5512. dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
  5513. }
  5514. }
  5515. elseif ($type == 'link')
  5516. {
  5517. $out='';
  5518. // only if something to display (perf)
  5519. if ($value)
  5520. {
  5521. $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath'
  5522. $InfoFieldList = explode(":", $param_list[0]);
  5523. $classname=$InfoFieldList[0];
  5524. $classpath=$InfoFieldList[1];
  5525. $getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
  5526. if (! empty($classpath))
  5527. {
  5528. dol_include_once($InfoFieldList[1]);
  5529. if ($classname && class_exists($classname))
  5530. {
  5531. $object = new $classname($this->db);
  5532. $object->fetch($value);
  5533. $value=$object->getNomUrl($getnomurlparam);
  5534. }
  5535. }
  5536. else
  5537. {
  5538. dol_syslog('Error bad setup of extrafield', LOG_WARNING);
  5539. return 'Error bad setup of extrafield';
  5540. }
  5541. }
  5542. else $value='';
  5543. }
  5544. elseif ($type == 'text' || $type == 'html')
  5545. {
  5546. $value=dol_htmlentitiesbr($value);
  5547. }
  5548. elseif ($type == 'password')
  5549. {
  5550. $value=preg_replace('/./i','*',$value);
  5551. }
  5552. elseif ($type == 'array')
  5553. {
  5554. $value = implode('<br>', $value);
  5555. }
  5556. //print $type.'-'.$size;
  5557. $out=$value;
  5558. return $out;
  5559. }
  5560. /**
  5561. * Function to show lines of extrafields with output datas
  5562. *
  5563. * @param Extrafields $extrafields Extrafield Object
  5564. * @param string $mode Show output (view) or input (edit) for extrafield
  5565. * @param array $params Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
  5566. * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names)
  5567. * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names)
  5568. * @param string $onetrtd All fields in same tr td
  5569. * @return string
  5570. */
  5571. function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
  5572. {
  5573. global $db, $conf, $langs, $action, $form;
  5574. if (! is_object($form)) $form=new Form($db);
  5575. $out = '';
  5576. if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
  5577. {
  5578. $out .= "\n";
  5579. $out .= '<!-- showOptionalsInput --> ';
  5580. $out .= "\n";
  5581. $e = 0;
  5582. foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
  5583. {
  5584. //Show only the key field in params
  5585. if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
  5586. $enabled = 1;
  5587. if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
  5588. {
  5589. $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
  5590. }
  5591. $perms = 1;
  5592. if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
  5593. {
  5594. $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
  5595. }
  5596. if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
  5597. if (empty($perms)) continue;
  5598. // Load language if required
  5599. if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
  5600. if (is_array($params) && count($params)>0) {
  5601. if (array_key_exists('colspan',$params)) {
  5602. $colspan=$params['colspan'];
  5603. }
  5604. }else {
  5605. $colspan='3';
  5606. }
  5607. switch($mode) {
  5608. case "view":
  5609. $value=$this->array_options["options_".$key.$keysuffix];
  5610. break;
  5611. case "edit":
  5612. $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values.
  5613. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
  5614. if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
  5615. {
  5616. if (is_array($getposttemp)) {
  5617. // $getposttemp is an array but following code expects a comma separated string
  5618. $value = implode(",", $getposttemp);
  5619. } else {
  5620. $value = $getposttemp;
  5621. }
  5622. } else {
  5623. $value = $this->array_options["options_" . $key]; // No GET, no POST, no default value, so we take value of object.
  5624. }
  5625. //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
  5626. break;
  5627. }
  5628. if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
  5629. {
  5630. $out .= $extrafields->showSeparator($key, $this);
  5631. }
  5632. else
  5633. {
  5634. $csstyle='';
  5635. $class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
  5636. if (is_array($params) && count($params)>0) {
  5637. if (array_key_exists('style',$params)) {
  5638. $csstyle=$params['style'];
  5639. }
  5640. }
  5641. // add html5 elements
  5642. $domData = ' data-element="extrafield"';
  5643. $domData .= ' data-targetelement="'.$this->element.'"';
  5644. $domData .= ' data-targetid="'.$this->id.'"';
  5645. $html_id = !empty($this->id) ? 'extrarow-'.$this->element.'_'.$key.'_'.$this->id : '';
  5646. $out .= '<tr id="'.$html_id.'" '.$csstyle.' class="'.$class.$this->element.'_extras_'.$key.'" '.$domData.' >';
  5647. if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
  5648. {
  5649. if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan='0'; }
  5650. }
  5651. if ($action == 'selectlines') { $colspan++; }
  5652. // Convert date into timestamp format (value in memory must be a timestamp)
  5653. if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
  5654. {
  5655. $datenotinstring = $this->array_options['options_' . $key];
  5656. if (! is_numeric($this->array_options['options_' . $key])) // For backward compatibility
  5657. {
  5658. $datenotinstring = $this->db->jdate($datenotinstring);
  5659. }
  5660. $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$datenotinstring;
  5661. }
  5662. // Convert float submited string into real php numeric (value in memory must be a php numeric)
  5663. if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
  5664. {
  5665. $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
  5666. }
  5667. $labeltoshow = $langs->trans($label);
  5668. $out .= '<td class="titlefield';
  5669. if (GETPOST('action','none') == 'create') $out.='create';
  5670. if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
  5671. $out .= '">';
  5672. if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
  5673. else $out .= $labeltoshow;
  5674. $out .= '</td>';
  5675. $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
  5676. $out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
  5677. switch($mode) {
  5678. case "view":
  5679. $out .= $extrafields->showOutputField($key, $value);
  5680. break;
  5681. case "edit":
  5682. $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id);
  5683. break;
  5684. }
  5685. $out .= '</td>';
  5686. if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
  5687. else $out .= '</tr>';
  5688. $e++;
  5689. }
  5690. }
  5691. $out .= "\n";
  5692. // Add code to manage list depending on others
  5693. if (! empty($conf->use_javascript_ajax)) {
  5694. $out .= '
  5695. <script type="text/javascript">
  5696. jQuery(document).ready(function() {
  5697. function showOptions(child_list, parent_list)
  5698. {
  5699. var val = $("select[name=\"options_"+parent_list+"\"]").val();
  5700. var parentVal = parent_list + ":" + val;
  5701. if(val > 0) {
  5702. $("select[name=\""+child_list+"\"] option[parent]").hide();
  5703. $("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
  5704. } else {
  5705. $("select[name=\""+child_list+"\"] option").show();
  5706. }
  5707. }
  5708. function setListDependencies() {
  5709. jQuery("select option[parent]").parent().each(function() {
  5710. var child_list = $(this).attr("name");
  5711. var parent = $(this).find("option[parent]:first").attr("parent");
  5712. var infos = parent.split(":");
  5713. var parent_list = infos[0];
  5714. $("select[name=\""+parent_list+"\"]").change(function() {
  5715. showOptions(child_list, parent_list);
  5716. });
  5717. });
  5718. }
  5719. setListDependencies();
  5720. });
  5721. </script>'."\n";
  5722. $out .= '<!-- /showOptionalsInput --> '."\n";
  5723. }
  5724. }
  5725. return $out;
  5726. }
  5727. /**
  5728. * Returns the rights used for this class
  5729. * @return stdClass
  5730. */
  5731. public function getRights()
  5732. {
  5733. global $user;
  5734. $element = $this->element;
  5735. if ($element == 'facturerec') $element='facture';
  5736. return $user->rights->{$element};
  5737. }
  5738. /**
  5739. * Function used to replace a thirdparty id with another one.
  5740. * This function is meant to be called from replaceThirdparty with the appropiate tables
  5741. * Column name fk_soc MUST be used to identify thirdparties
  5742. *
  5743. * @param DoliDB $db Database handler
  5744. * @param int $origin_id Old thirdparty id (the thirdparty to delete)
  5745. * @param int $dest_id New thirdparty id (the thirdparty that will received element of the other)
  5746. * @param string[] $tables Tables that need to be changed
  5747. * @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)
  5748. * @return bool True if success, False if error
  5749. */
  5750. public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
  5751. {
  5752. foreach ($tables as $table)
  5753. {
  5754. $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
  5755. if (! $db->query($sql))
  5756. {
  5757. 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.
  5758. //$this->errors = $db->lasterror();
  5759. return false;
  5760. }
  5761. }
  5762. return true;
  5763. }
  5764. /**
  5765. * Get buy price to use for margin calculation. This function is called when buy price is unknown.
  5766. * Set buy price = sell price if ForceBuyingPriceIfNull configured,
  5767. * else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
  5768. * else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
  5769. * else set min buy price as buy price
  5770. *
  5771. * @param float $unitPrice Product unit price
  5772. * @param float $discountPercent Line discount percent
  5773. * @param int $fk_product Product id
  5774. * @return float <0 if KO, buyprice if OK
  5775. */
  5776. public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
  5777. {
  5778. global $conf;
  5779. $buyPrice = 0;
  5780. if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
  5781. {
  5782. $buyPrice = $unitPrice * (1 - $discountPercent / 100);
  5783. }
  5784. else
  5785. {
  5786. // Get cost price for margin calculation
  5787. if (! empty($fk_product))
  5788. {
  5789. if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
  5790. {
  5791. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5792. $product = new Product($this->db);
  5793. $result = $product->fetch($fk_product);
  5794. if ($result <= 0)
  5795. {
  5796. $this->errors[] = 'ErrorProductIdDoesNotExists';
  5797. return -1;
  5798. }
  5799. if ($product->cost_price > 0)
  5800. {
  5801. $buyPrice = $product->cost_price;
  5802. }
  5803. else if ($product->pmp > 0)
  5804. {
  5805. $buyPrice = $product->pmp;
  5806. }
  5807. }
  5808. else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
  5809. {
  5810. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5811. $product = new Product($this->db);
  5812. $result = $product->fetch($fk_product);
  5813. if ($result <= 0)
  5814. {
  5815. $this->errors[] = 'ErrorProductIdDoesNotExists';
  5816. return -1;
  5817. }
  5818. if ($product->pmp > 0)
  5819. {
  5820. $buyPrice = $product->pmp;
  5821. }
  5822. }
  5823. if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
  5824. {
  5825. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5826. $productFournisseur = new ProductFournisseur($this->db);
  5827. if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
  5828. {
  5829. $buyPrice = $productFournisseur->fourn_unitprice;
  5830. }
  5831. else if ($result < 0)
  5832. {
  5833. $this->errors[] = $productFournisseur->error;
  5834. return -2;
  5835. }
  5836. }
  5837. }
  5838. }
  5839. return $buyPrice;
  5840. }
  5841. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  5842. /**
  5843. * Show photos of an object (nbmax maximum), into several columns
  5844. *
  5845. * @param string $modulepart 'product', 'ticket', ...
  5846. * @param string $sdir Directory to scan (full absolute path)
  5847. * @param int $size 0=original size, 1='small' use thumbnail if possible
  5848. * @param int $nbmax Nombre maximum de photos (0=pas de max)
  5849. * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1.
  5850. * @param int $showfilename 1=Show filename
  5851. * @param int $showaction 1=Show icon with action links (resize, delete)
  5852. * @param int $maxHeight Max height of original image when size='small' (so we can use original even if small requested). If 0, always use 'small' thumb image.
  5853. * @param int $maxWidth Max width of original image when size='small'
  5854. * @param int $nolink Do not add a href link to view enlarged imaged into a new tab
  5855. * @param int $notitle Do not add title tag on image
  5856. * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
  5857. * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto
  5858. */
  5859. function show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $notitle=0, $usesharelink=0)
  5860. {
  5861. // phpcs:enable
  5862. global $conf,$user,$langs;
  5863. include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
  5864. include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
  5865. $sortfield='position_name';
  5866. $sortorder='asc';
  5867. $dir = $sdir . '/';
  5868. $pdir = '/';
  5869. if ($modulepart == 'ticket')
  5870. {
  5871. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
  5872. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
  5873. }
  5874. else
  5875. {
  5876. $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  5877. $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
  5878. }
  5879. // For backward compatibility
  5880. if ($modulepart == 'product' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
  5881. {
  5882. $dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
  5883. $pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
  5884. }
  5885. // Defined relative dir to DOL_DATA_ROOT
  5886. $relativedir = '';
  5887. if ($dir)
  5888. {
  5889. $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
  5890. $relativedir = preg_replace('/^[\\/]/','',$relativedir);
  5891. $relativedir = preg_replace('/[\\/]$/','',$relativedir);
  5892. }
  5893. $dirthumb = $dir.'thumbs/';
  5894. $pdirthumb = $pdir.'thumbs/';
  5895. $return ='<!-- Photo -->'."\n";
  5896. $nbphoto=0;
  5897. $filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  5898. /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
  5899. {
  5900. $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
  5901. $filearray=array_merge($filearray, $filearrayold);
  5902. }*/
  5903. completeFileArrayWithDatabaseInfo($filearray, $relativedir);
  5904. if (count($filearray))
  5905. {
  5906. if ($sortfield && $sortorder)
  5907. {
  5908. $filearray=dol_sort_array($filearray, $sortfield, $sortorder);
  5909. }
  5910. foreach($filearray as $key => $val)
  5911. {
  5912. $photo='';
  5913. $file = $val['name'];
  5914. //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory
  5915. //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
  5916. if (image_format_supported($file) >= 0)
  5917. {
  5918. $nbphoto++;
  5919. $photo = $file;
  5920. $viewfilename = $file;
  5921. if ($size == 1 || $size == 'small') { // Format vignette
  5922. // Find name of thumb file
  5923. $photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
  5924. if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
  5925. // Get filesize of original file
  5926. $imgarray=dol_getImageSize($dir.$photo);
  5927. if ($nbbyrow > 0)
  5928. {
  5929. if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
  5930. if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
  5931. $return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
  5932. }
  5933. else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
  5934. $return.= "\n";
  5935. $relativefile=preg_replace('/^\//', '', $pdir.$photo);
  5936. if (empty($nolink))
  5937. {
  5938. $urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
  5939. if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
  5940. else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
  5941. }
  5942. // Show image (width height=$maxHeight)
  5943. // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
  5944. $alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
  5945. $alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
  5946. if ($notitle) $alt='';
  5947. if ($usesharelink)
  5948. {
  5949. if ($val['share'])
  5950. {
  5951. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  5952. {
  5953. $return.= '<!-- Show original file (thumb not yet available with shared links) -->';
  5954. $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  5955. }
  5956. else {
  5957. $return.= '<!-- Show original file -->';
  5958. $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
  5959. }
  5960. }
  5961. else
  5962. {
  5963. $return.= '<!-- Show nophoto file (because file is not shared) -->';
  5964. $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
  5965. }
  5966. }
  5967. else
  5968. {
  5969. if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
  5970. {
  5971. $return.= '<!-- Show thumb -->';
  5972. $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
  5973. }
  5974. else {
  5975. $return.= '<!-- Show original file -->';
  5976. $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
  5977. }
  5978. }
  5979. if (empty($nolink)) $return.= '</a>';
  5980. $return.="\n";
  5981. if ($showfilename) $return.= '<br>'.$viewfilename;
  5982. if ($showaction)
  5983. {
  5984. $return.= '<br>';
  5985. // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
  5986. if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
  5987. {
  5988. $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'),'refresh').'&nbsp;&nbsp;</a>';
  5989. }
  5990. // Special cas for product
  5991. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  5992. {
  5993. // Link to resize
  5994. $return.= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  5995. // Link to delete
  5996. $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
  5997. $return.= img_delete().'</a>';
  5998. }
  5999. }
  6000. $return.= "\n";
  6001. if ($nbbyrow > 0)
  6002. {
  6003. $return.= '</td>';
  6004. if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
  6005. }
  6006. else if ($nbbyrow < 0) $return.='</div>';
  6007. }
  6008. if (empty($size)) { // Format origine
  6009. $return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
  6010. if ($showfilename) $return.= '<br>'.$viewfilename;
  6011. if ($showaction)
  6012. {
  6013. // Special case for product
  6014. if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
  6015. {
  6016. // Link to resize
  6017. $return.= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
  6018. // Link to delete
  6019. $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
  6020. $return.= img_delete().'</a>';
  6021. }
  6022. }
  6023. }
  6024. // On continue ou on arrete de boucler ?
  6025. if ($nbmax && $nbphoto >= $nbmax) break;
  6026. }
  6027. }
  6028. if ($size==1 || $size=='small')
  6029. {
  6030. if ($nbbyrow > 0)
  6031. {
  6032. // Ferme tableau
  6033. while ($nbphoto % $nbbyrow)
  6034. {
  6035. $return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
  6036. $nbphoto++;
  6037. }
  6038. if ($nbphoto) $return.= '</table>';
  6039. }
  6040. }
  6041. }
  6042. $this->nbphoto = $nbphoto;
  6043. return $return;
  6044. }
  6045. /**
  6046. * Function test if type is array
  6047. *
  6048. * @param array $info content informations of field
  6049. * @return bool
  6050. */
  6051. protected function isArray($info)
  6052. {
  6053. if(is_array($info))
  6054. {
  6055. if(isset($info['type']) && $info['type']=='array') return true;
  6056. else return false;
  6057. }
  6058. else return false;
  6059. }
  6060. /**
  6061. * Function test if type is null
  6062. *
  6063. * @param array $info content informations of field
  6064. * @return bool
  6065. */
  6066. protected function isNull($info)
  6067. {
  6068. if(is_array($info))
  6069. {
  6070. if(isset($info['type']) && $info['type']=='null') return true;
  6071. else return false;
  6072. }
  6073. else return false;
  6074. }
  6075. /**
  6076. * Function test if type is date
  6077. *
  6078. * @param array $info content informations of field
  6079. * @return bool
  6080. */
  6081. public function isDate($info)
  6082. {
  6083. if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
  6084. else return false;
  6085. }
  6086. /**
  6087. * Function test if type is integer
  6088. *
  6089. * @param array $info content informations of field
  6090. * @return bool
  6091. */
  6092. public function isInt($info)
  6093. {
  6094. if(is_array($info))
  6095. {
  6096. if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
  6097. else return false;
  6098. }
  6099. else return false;
  6100. }
  6101. /**
  6102. * Function test if type is float
  6103. *
  6104. * @param array $info content informations of field
  6105. * @return bool
  6106. */
  6107. public function isFloat($info)
  6108. {
  6109. if(is_array($info))
  6110. {
  6111. if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
  6112. else return false;
  6113. }
  6114. else return false;
  6115. }
  6116. /**
  6117. * Function test if type is text
  6118. *
  6119. * @param array $info content informations of field
  6120. * @return bool
  6121. */
  6122. public function isText($info)
  6123. {
  6124. if(is_array($info))
  6125. {
  6126. if(isset($info['type']) && $info['type']=='text') return true;
  6127. else return false;
  6128. }
  6129. else return false;
  6130. }
  6131. /**
  6132. * Function test if is indexed
  6133. *
  6134. * @param array $info content informations of field
  6135. * @return bool
  6136. */
  6137. protected function isIndex($info)
  6138. {
  6139. if(is_array($info))
  6140. {
  6141. if(isset($info['index']) && $info['index']==true) return true;
  6142. else return false;
  6143. }
  6144. else return false;
  6145. }
  6146. /**
  6147. * Function to prepare the values to insert.
  6148. * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
  6149. *
  6150. * @return array
  6151. */
  6152. protected function setSaveQuery()
  6153. {
  6154. global $conf;
  6155. $queryarray=array();
  6156. foreach ($this->fields as $field=>$info) // Loop on definition of fields
  6157. {
  6158. // Depending on field type ('datetime', ...)
  6159. if($this->isDate($info))
  6160. {
  6161. if(empty($this->{$field}))
  6162. {
  6163. $queryarray[$field] = null;
  6164. }
  6165. else
  6166. {
  6167. $queryarray[$field] = $this->db->idate($this->{$field});
  6168. }
  6169. }
  6170. else if($this->isArray($info))
  6171. {
  6172. if(! empty($this->{$field})) {
  6173. if(! is_array($this->{$field})) {
  6174. $this->{$field} = array($this->{$field});
  6175. }
  6176. $queryarray[$field] = serialize($this->{$field});
  6177. } else {
  6178. $queryarray[$field] = null;
  6179. }
  6180. }
  6181. else if($this->isInt($info))
  6182. {
  6183. if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field]=$conf->entity;
  6184. else
  6185. {
  6186. $queryarray[$field] = (int) price2num($this->{$field});
  6187. if (empty($queryarray[$field])) $queryarray[$field]=0; // May be reset to null later if property 'notnull' is -1 for this field.
  6188. }
  6189. }
  6190. else if($this->isFloat($info))
  6191. {
  6192. $queryarray[$field] = (double) price2num($this->{$field});
  6193. if (empty($queryarray[$field])) $queryarray[$field]=0;
  6194. }
  6195. else
  6196. {
  6197. $queryarray[$field] = $this->{$field};
  6198. }
  6199. if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
  6200. if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
  6201. }
  6202. return $queryarray;
  6203. }
  6204. /**
  6205. * Function to load data from a SQL pointer into properties of current object $this
  6206. *
  6207. * @param stdClass $obj Contain data of object from database
  6208. * @return void
  6209. */
  6210. protected function setVarsFromFetchObj(&$obj)
  6211. {
  6212. foreach ($this->fields as $field => $info)
  6213. {
  6214. if($this->isDate($info))
  6215. {
  6216. if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
  6217. else $this->{$field} = strtotime($obj->{$field});
  6218. }
  6219. elseif($this->isArray($info))
  6220. {
  6221. if(! empty($obj->{$field})) {
  6222. $this->{$field} = @unserialize($obj->{$field});
  6223. // Hack for data not in UTF8
  6224. if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
  6225. } else {
  6226. $this->{$field} = array();
  6227. }
  6228. }
  6229. elseif($this->isInt($info))
  6230. {
  6231. if ($field == 'rowid') $this->id = (int) $obj->{$field};
  6232. else $this->{$field} = (int) $obj->{$field};
  6233. }
  6234. elseif($this->isFloat($info))
  6235. {
  6236. $this->{$field} = (double) $obj->{$field};
  6237. }
  6238. elseif($this->isNull($info))
  6239. {
  6240. $val = $obj->{$field};
  6241. // zero is not null
  6242. $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
  6243. }
  6244. else
  6245. {
  6246. $this->{$field} = $obj->{$field};
  6247. }
  6248. }
  6249. // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
  6250. if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
  6251. }
  6252. /**
  6253. * Function to concat keys of fields
  6254. *
  6255. * @return string
  6256. */
  6257. protected function getFieldList()
  6258. {
  6259. $keys = array_keys($this->fields);
  6260. return implode(',', $keys);
  6261. }
  6262. /**
  6263. * Add quote to field value if necessary
  6264. *
  6265. * @param string|int $value Value to protect
  6266. * @param array $fieldsentry Properties of field
  6267. * @return string
  6268. */
  6269. protected function quote($value, $fieldsentry)
  6270. {
  6271. if (is_null($value)) return 'NULL';
  6272. else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
  6273. else return "'".$this->db->escape($value)."'";
  6274. }
  6275. /**
  6276. * Create object into database
  6277. *
  6278. * @param User $user User that creates
  6279. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6280. * @return int <0 if KO, Id of created object if OK
  6281. */
  6282. public function createCommon(User $user, $notrigger = false)
  6283. {
  6284. global $langs;
  6285. $error = 0;
  6286. $now=dol_now();
  6287. $fieldvalues = $this->setSaveQuery();
  6288. if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
  6289. if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
  6290. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
  6291. $keys=array();
  6292. $values = array();
  6293. foreach ($fieldvalues as $k => $v) {
  6294. $keys[$k] = $k;
  6295. $value = $this->fields[$k];
  6296. $values[$k] = $this->quote($v, $value);
  6297. }
  6298. // Clean and check mandatory
  6299. foreach($keys as $key)
  6300. {
  6301. // If field is an implicit foreign key field
  6302. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
  6303. if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
  6304. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  6305. if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
  6306. {
  6307. $error++;
  6308. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  6309. }
  6310. // If field is an implicit foreign key field
  6311. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
  6312. if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
  6313. }
  6314. if ($error) return -1;
  6315. $this->db->begin();
  6316. if (! $error)
  6317. {
  6318. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
  6319. $sql.= ' ('.implode( ", ", $keys ).')';
  6320. $sql.= ' VALUES ('.implode( ", ", $values ).')';
  6321. $res = $this->db->query($sql);
  6322. if ($res===false) {
  6323. $error++;
  6324. $this->errors[] = $this->db->lasterror();
  6325. }
  6326. }
  6327. if (! $error)
  6328. {
  6329. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
  6330. }
  6331. // Create extrafields
  6332. if (! $error)
  6333. {
  6334. $result=$this->insertExtraFields();
  6335. if ($result < 0) $error++;
  6336. }
  6337. // Triggers
  6338. if (! $error && ! $notrigger)
  6339. {
  6340. // Call triggers
  6341. $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
  6342. if ($result < 0) { $error++; }
  6343. // End call triggers
  6344. }
  6345. // Commit or rollback
  6346. if ($error) {
  6347. $this->db->rollback();
  6348. return -1;
  6349. } else {
  6350. $this->db->commit();
  6351. return $this->id;
  6352. }
  6353. }
  6354. /**
  6355. * Load object in memory from the database
  6356. *
  6357. * @param int $id Id object
  6358. * @param string $ref Ref
  6359. * @param string $morewhere More SQL filters (' AND ...')
  6360. * @return int <0 if KO, 0 if not found, >0 if OK
  6361. */
  6362. public function fetchCommon($id, $ref = null, $morewhere = '')
  6363. {
  6364. if (empty($id) && empty($ref) && empty($morewhere)) return -1;
  6365. $sql = 'SELECT '.$this->getFieldList();
  6366. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  6367. if (!empty($id)) $sql.= ' WHERE rowid = '.$id;
  6368. elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
  6369. else $sql.=' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
  6370. if ($morewhere) $sql.= $morewhere;
  6371. $sql.=' LIMIT 1'; // This is a fetch, to be sure to get only one record
  6372. $res = $this->db->query($sql);
  6373. if ($res)
  6374. {
  6375. $obj = $this->db->fetch_object($res);
  6376. if ($obj)
  6377. {
  6378. $this->setVarsFromFetchObj($obj);
  6379. return $this->id;
  6380. }
  6381. else
  6382. {
  6383. return 0;
  6384. }
  6385. }
  6386. else
  6387. {
  6388. $this->error = $this->db->lasterror();
  6389. $this->errors[] = $this->error;
  6390. return -1;
  6391. }
  6392. }
  6393. /**
  6394. * Update object into database
  6395. *
  6396. * @param User $user User that modifies
  6397. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6398. * @return int <0 if KO, >0 if OK
  6399. */
  6400. public function updateCommon(User $user, $notrigger = false)
  6401. {
  6402. global $conf, $langs;
  6403. $error = 0;
  6404. $now=dol_now();
  6405. $fieldvalues = $this->setSaveQuery();
  6406. if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
  6407. if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
  6408. unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
  6409. $keys=array();
  6410. $values = array();
  6411. foreach ($fieldvalues as $k => $v) {
  6412. $keys[$k] = $k;
  6413. $value = $this->fields[$k];
  6414. $values[$k] = $this->quote($v, $value);
  6415. $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
  6416. }
  6417. // Clean and check mandatory
  6418. foreach($keys as $key)
  6419. {
  6420. if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; // This is an implicit foreign key field
  6421. if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; // This is an explicit foreign key field
  6422. //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
  6423. /*
  6424. if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
  6425. {
  6426. $error++;
  6427. $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
  6428. }*/
  6429. }
  6430. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
  6431. $this->db->begin();
  6432. if (! $error)
  6433. {
  6434. $res = $this->db->query($sql);
  6435. if ($res===false)
  6436. {
  6437. $error++;
  6438. $this->errors[] = $this->db->lasterror();
  6439. }
  6440. }
  6441. // Update extrafield
  6442. if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
  6443. {
  6444. $result=$this->insertExtraFields();
  6445. if ($result < 0)
  6446. {
  6447. $error++;
  6448. }
  6449. }
  6450. // Triggers
  6451. if (! $error && ! $notrigger)
  6452. {
  6453. // Call triggers
  6454. $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
  6455. if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
  6456. // End call triggers
  6457. }
  6458. // Commit or rollback
  6459. if ($error) {
  6460. $this->db->rollback();
  6461. return -1;
  6462. } else {
  6463. $this->db->commit();
  6464. return $this->id;
  6465. }
  6466. }
  6467. /**
  6468. * Delete object in database
  6469. *
  6470. * @param User $user User that deletes
  6471. * @param bool $notrigger false=launch triggers after, true=disable triggers
  6472. * @return int <0 if KO, >0 if OK
  6473. */
  6474. public function deleteCommon(User $user, $notrigger = false)
  6475. {
  6476. $error=0;
  6477. $this->db->begin();
  6478. if (! $error) {
  6479. if (! $notrigger) {
  6480. // Call triggers
  6481. $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
  6482. if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
  6483. // End call triggers
  6484. }
  6485. }
  6486. if (! $error && ! empty($this->isextrafieldmanaged))
  6487. {
  6488. $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
  6489. $sql.= " WHERE fk_object=" . $this->id;
  6490. $resql = $this->db->query($sql);
  6491. if (! $resql)
  6492. {
  6493. $this->errors[] = $this->db->lasterror();
  6494. $error++;
  6495. }
  6496. }
  6497. if (! $error)
  6498. {
  6499. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
  6500. $res = $this->db->query($sql);
  6501. if($res===false) {
  6502. $error++;
  6503. $this->errors[] = $this->db->lasterror();
  6504. }
  6505. }
  6506. // Commit or rollback
  6507. if ($error) {
  6508. $this->db->rollback();
  6509. return -1;
  6510. } else {
  6511. $this->db->commit();
  6512. return 1;
  6513. }
  6514. }
  6515. /**
  6516. * Initialise object with example values
  6517. * Id must be 0 if object instance is a specimen
  6518. *
  6519. * @return void
  6520. */
  6521. public function initAsSpecimenCommon()
  6522. {
  6523. $this->id = 0;
  6524. // TODO...
  6525. }
  6526. /* Part for comments */
  6527. /**
  6528. * Load comments linked with current task
  6529. * @return boolean 1 if ok
  6530. */
  6531. public function fetchComments()
  6532. {
  6533. require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
  6534. $comment = new Comment($this->db);
  6535. $result=$comment->fetchAllFor($this->element, $this->id);
  6536. if ($result<0) {
  6537. $this->errors=array_merge($this->errors, $comment->errors);
  6538. return -1;
  6539. } else {
  6540. $this->comments = $comment->comments;
  6541. }
  6542. return count($this->comments);
  6543. }
  6544. /**
  6545. * Return nb comments already posted
  6546. *
  6547. * @return int
  6548. */
  6549. public function getNbComments()
  6550. {
  6551. return count($this->comments);
  6552. }
  6553. /**
  6554. * Trim object parameters
  6555. * @param string[] $parameters array of parameters to trim
  6556. *
  6557. * @return void
  6558. */
  6559. public function trimParameters($parameters)
  6560. {
  6561. if (!is_array($parameters)) return;
  6562. foreach ($parameters as $parameter) {
  6563. if (isset($this->$parameter)) {
  6564. $this->$parameter = trim($this->$parameter);
  6565. }
  6566. }
  6567. }
  6568. }